建立可傳回 Spanner 結果的 Cloud Run 函式

本教學課程將說明如何編寫可傳回 Spanner 結果的 HTTP Cloud Run 函式。

目標

編寫、部署及觸發可存取 Spanner 的 HTTP 函式

費用

本文使用 Spanner 和 Cloud Run,這兩者都是 Google Cloud的可計費元件。

  • 如要瞭解 Spanner 的使用費用,請參閱 Spanner 定價

  • 如要瞭解 Cloud Run 的使用費用,包括免費叫用,請參閱 Cloud Run 定價

事前準備

  1. 本文假設您擁有一個名稱為 test-instance 的 Spanner 執行個體,與一個名稱為 example-db 且使用音樂應用程式結構定義的資料庫。如需使用音樂應用程式結構定義建立執行個體與資料庫的操作說明,請參閱使用主控台的快速入門導覽課程,或 Node.jsPython 中的入門指南教學課程。

  2. 啟用 Cloud Run 和 Cloud Build API。

    啟用 API

  3. 安裝並初始化 gcloud CLI

    如果您已安裝 gcloud CLI,請執行下列指令來更新:

    gcloud components update
    
  4. 準備您的開發環境:

    Node.js

    請參閱 Node.js 設定指南

    Python

    請參閱 Python 設定指南

準備應用程式

  1. 將應用程式存放區範例複製到本機電腦中:

    Node.js

    git clone https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git

    您也可以下載 zip 格式的範例,然後解壓縮該檔案。

    Python

    git clone https://github.com/GoogleCloudPlatform/python-docs-samples.git

    您也可以下載 zip 格式的範例,然後解壓縮該檔案。

  2. 變更為包含 Cloud Run 函式範例程式碼的目錄,以存取 Spanner:

    Node.js

    cd nodejs-docs-samples/functions/spanner

    Python

    cd python-docs-samples/functions/spanner
  3. 查看程式碼範例:

    Node.js

    // Imports the Google Cloud client library
    const {Spanner} = require('@google-cloud/spanner');
    
    // Imports the functions framework to register your HTTP function
    const functions = require('@google-cloud/functions-framework');
    
    // Instantiates a client
    const spanner = new Spanner();
    
    // Your Cloud Spanner instance ID
    const instanceId = 'test-instance';
    
    // Your Cloud Spanner database ID
    const databaseId = 'example-db';
    
    /**
     * HTTP Cloud Function.
     *
     * @param {Object} req Cloud Function request context.
     * @param {Object} res Cloud Function response context.
     */
    functions.http('spannerQuickstart', async (req, res) => {
      // Gets a reference to a Cloud Spanner instance and database
      const instance = spanner.instance(instanceId);
      const database = instance.database(databaseId);
    
      // The query to execute
      const query = {
        sql: 'SELECT * FROM Albums',
      };
    
      // Execute the query
      try {
        const results = await database.run(query);
        const rows = results[0].map(row => row.toJSON());
        rows.forEach(row => {
          res.write(
            `SingerId: ${row.SingerId}, ` +
              `AlbumId: ${row.AlbumId}, ` +
              `AlbumTitle: ${row.AlbumTitle}\n`
          );
        });
        res.status(200).end();
      } catch (err) {
        res.status(500).send(`Error querying Spanner: ${err}`);
      }
    });

    Python

    import functions_framework
    from google.cloud import spanner
    
    instance_id = "test-instance"
    database_id = "example-db"
    
    client = spanner.Client()
    instance = client.instance(instance_id)
    database = instance.database(database_id)
    
    
    @functions_framework.http
    def spanner_read_data(request):
        query = "SELECT * FROM Albums"
    
        outputs = []
        with database.snapshot() as snapshot:
            results = snapshot.execute_sql(query)
    
            for row in results:
                output = "SingerId: {}, AlbumId: {}, AlbumTitle: {}".format(*row)
                outputs.append(output)
    
        return "\n".join(outputs)
    
    

    函式會傳送 SQL 查詢,從資料庫擷取所有 Albums 資料。函式會在您對函式的端點提出 HTTP 要求時執行。

部署函式

如要使用 HTTP 觸發條件部署函式,請在 spanner 目錄中執行下列指令:

Node.js

gcloud run deploy nodejs-spanner-function \
    --source . \
    --region REGION \
    --function spannerQuickstart \
    --base-image RUNTIME_ID \
    --log-http

Python

gcloud run deploy python-spanner-function \
    --source . \
    --region REGION \
    --function spanner_read_data \
    --base-image RUNTIME_ID \
    --log-http

取代:

部署函式可能需要兩分鐘的時間。

請注意函式完成部署時傳回的 url 值。您將會在觸發函式時使用它。

您可以在Google Cloud 控制台的「Cloud Run」頁面查看已部署的函式。您也可在該頁面上建立及編輯函式,並取得函式的詳細資料與診斷資訊。

觸發函式

對您的函式提出 HTTP 要求:

curl URL

URL 取代為函式完成部署時傳回的網址值。

您應會看見輸出顯示 SQL 查詢的結果。假設您完成了入門指南教學課程並填入資料庫:

SingerId: 2, AlbumId: 2, AlbumTitle: Forever Hold Your Peace
SingerId: 1, AlbumId: 2, AlbumTitle: Go, Go, Go
SingerId: 2, AlbumId: 1, AlbumTitle: Green
SingerId: 2, AlbumId: 3, AlbumTitle: Terrified
SingerId: 1, AlbumId: 1, AlbumTitle: Total Junk

您也可以透過瀏覽器造訪函式的網址,查看 SQL 查詢的結果。

清除所用資源

如要避免系統向您的 Google Cloud 帳戶收取您在本文件中使用 Spanner 和 Cloud Run 函式資源的相關費用,請按照下列步驟操作:

  1. 刪除執行個體:

    gcloud CLI instances delete test-instance
    
  2. 刪除您在本教學課程中部署的 Cloud Run 服務:

    Node.js

    gcloud run services delete nodejs-spanner-function

    Python

    gcloud run services delete python-spanner-function

後續步驟