使用 Cloud Functions

目标

编写、部署和触发可访问 Bigtable 的 HTTP Cloud Functions 函数

费用

本主题使用了 Bigtable 和 Cloud Functions,它们是 Google Cloud 的收费组件。

准备工作

  1. 本主题假设您有一个名为 test-instance 的 Bigtable 实例和一个名为 test-table 的表。您可以按照创建测试表中的步骤创建这些资源。完成后,请务必删除资源,以免产生不必要的费用。

  2. 启用 Cloud Functions API。

    启用该 API

  3. 安装并初始化 gcloud CLI

    如果您已经安装 gcloud CLI,请运行以下命令进行更新:

    gcloud components update
    
  4. 准备开发环境:

准备应用

  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 文件并将其解压缩。

    Go

    git clone https://github.com/GoogleCloudPlatform/golang-samples.git

    或者,您也可以下载该示例的 zip 文件并将其解压缩。

  2. 切换到包含用于访问 Bigtable 的 Cloud Functions 函数示例代码的目录:

    Node.js

    cd nodejs-docs-samples/functions/bigtable/

    Python

    cd python-docs-samples/functions/bigtable/

    Go

    cd golang-samples/functions/bigtable/
  3. 查看示例代码:

    Node.js

    // Imports the Google Cloud client library
    const {Bigtable} = require('@google-cloud/bigtable');
    
    // Instantiates a client
    const bigtable = new Bigtable();
    
    exports.readRows = async (req, res) => {
      // Gets a reference to a Cloud Bigtable instance and database
      const instance = bigtable.instance(req.body.instanceId);
      const table = instance.table(req.body.tableId);
    
      // Execute the query
      try {
        const prefix = 'phone#';
        const rows = [];
        await table
          .createReadStream({
            prefix,
          })
          .on('error', err => {
            res.send(`Error querying Bigtable: ${err}`);
            res.status(500).end();
          })
          .on('data', row => {
            rows.push(
              `rowkey: ${row.id}, ` +
                `os_build: ${row.data['stats_summary']['os_build'][0].value}\n`
            );
          })
          .on('end', () => {
            rows.forEach(r => res.write(r));
            res.status(200).end();
          });
      } catch (err) {
        res.send(`Error querying Bigtable: ${err}`);
        res.status(500).end();
      }
    };
    

    Python

    from google.cloud import bigtable
    from google.cloud.bigtable.row_set import RowSet
    
    client = bigtable.Client()
    
    def bigtable_read_data(request):
        instance = client.instance(request.headers.get("instance_id"))
        table = instance.table(request.headers.get("table_id"))
    
        prefix = "phone#"
        end_key = prefix[:-1] + chr(ord(prefix[-1]) + 1)
    
        outputs = []
        row_set = RowSet()
        row_set.add_row_range_from_keys(prefix.encode("utf-8"), end_key.encode("utf-8"))
    
        rows = table.read_rows(row_set=row_set)
        for row in rows:
            output = "Rowkey: {}, os_build: {}".format(
                row.row_key.decode("utf-8"),
                row.cells["stats_summary"][b"os_build"][0].value.decode("utf-8"),
            )
            outputs.append(output)
    
        return "\n".join(outputs)
    
    

    Go

    
    // Package bigtable contains an example of using Bigtable from a Cloud Function.
    package bigtable
    
    import (
    	"context"
    	"fmt"
    	"log"
    	"net/http"
    	"sync"
    
    	"cloud.google.com/go/bigtable"
    )
    
    // client is a global Bigtable client, to avoid initializing a new client for
    // every request.
    var client *bigtable.Client
    var clientOnce sync.Once
    
    // BigtableRead is an example of reading Bigtable from a Cloud Function.
    func BigtableRead(w http.ResponseWriter, r *http.Request) {
    	clientOnce.Do(func() {
    		// Declare a separate err variable to avoid shadowing client.
    		var err error
    		client, err = bigtable.NewClient(context.Background(), r.Header.Get("projectID"), r.Header.Get("instanceId"))
    		if err != nil {
    			http.Error(w, "Error initializing client", http.StatusInternalServerError)
    			log.Printf("bigtable.NewClient: %v", err)
    			return
    		}
    	})
    
    	tbl := client.Open(r.Header.Get("tableID"))
    	err := tbl.ReadRows(r.Context(), bigtable.PrefixRange("phone#"),
    		func(row bigtable.Row) bool {
    			osBuild := ""
    			for _, col := range row["stats_summary"] {
    				if col.Column == "stats_summary:os_build" {
    					osBuild = string(col.Value)
    				}
    			}
    
    			fmt.Fprintf(w, "Rowkey: %s, os_build:  %s\n", row.Key(), osBuild)
    			return true
    		})
    
    	if err != nil {
    		http.Error(w, "Error reading rows", http.StatusInternalServerError)
    		log.Printf("tbl.ReadRows(): %v", err)
    	}
    }
    

    该函数会向表发送读取请求,以提取行键前缀为 phone 的行的所有 stats_summary 数据。当您向该函数的端点发出 HTTP 请求时,系统即会执行该函数。

部署函数

如需使用 HTTP 触发器部署该函数,请在 bigtable 目录中运行以下命令:

Node.js

gcloud functions deploy get \
--runtime nodejs20 --trigger-http

使用 --runtime 标志可以指定支持的 Node.js 版本的运行时 ID 来运行您的函数。

Python

gcloud functions deploy bigtable_read_data \
--runtime python312 --trigger-http

使用 --runtime 标志可以指定支持的 Python 版本的运行时 ID 来运行您的函数。

Go

gcloud functions deploy BigtableRead \
--runtime go121 --trigger-http

使用 --runtime 标志可以指定支持的 Go 版本的运行时 ID 来运行您的函数。

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

当您的函数完成部署后,它会返回 url 值。您将会在触发该函数时用到该值。

您可以在 Google Cloud 控制台的 Cloud Functions 页面上查看已部署的函数。还可以在该页面上创建和修改函数,并获取函数的详细信息和诊断信息。

触发函数

向您的函数发出 HTTP 请求:

Node.js

curl "https://REGION-PROJECT_ID.cloudfunctions.net/get" -H "instance_id: test-instance" -H "table_id: test-table"

Python

curl "https://REGION-PROJECT_ID.cloudfunctions.net/bigtable_read_data" -H "instance_id: test-instance" -H "table_id: test-table"

Go

curl "https://REGION-PROJECT_ID.cloudfunctions.net/BigtableRead" -H "instance_id: test-instance" -H "table_id: test-table"

其中,REGIONPROJECT_ID 与函数完成部署时终端中显示的值一致。您应该会看到显示读取请求结果的输出。

您还可以在浏览器中访问函数的网址,以查看读取请求的结果。

清理

为避免系统因本主题中使用的 Bigtable 和 Cloud Functions 资源向您的 Google Cloud 账号收取额外费用,请执行以下操作:

  1. 删除实例:

    gcloud bigtable instances delete test-instance
    
  2. 删除您部署的函数:

    Node.js

    gcloud functions delete get 

    Python

    gcloud functions delete bigtable_read_data 

    Go

    gcloud functions delete BigtableRead 

后续步骤