创建一个用于返回 Spanner 结果的 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. 切换到包含用于访问 Spanner 的 Cloud Run functions 函数示例代码的目录:

    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

您需要进行如下替换:

函数部署最多可能需要 2 分钟。

当您的函数完成部署时,请记下系统返回的 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 查询结果。

清理

为避免系统因本文档中使用的 Spanner 和 Cloud Run functions 资源向您的 Google Cloud 账号收取额外费用,请执行以下操作:

  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

后续步骤