使用 Cloud Functions
目标
编写、部署和触发可访问 Bigtable 的 HTTP Cloud Functions 函数。
费用
本主题使用了 Bigtable 和 Cloud Functions,它们是 Google Cloud 的收费组件。
如需了解 Bigtable 的使用费,请参阅 Bigtable 价格。
如需了解 Cloud Functions 的使用费用(包括免费调用),请参阅 Cloud Functions 价格。
准备工作
本主题假设您有一个名为
test-instance
的 Bigtable 实例和一个名为test-table
的表。您可以按照创建测试表中的步骤创建这些资源。完成后,请务必删除资源,以免产生不必要的费用。启用 Cloud Functions API。
-
如果您已经安装 gcloud CLI,请运行以下命令进行更新:
gcloud components update
准备开发环境:
准备应用
将示例应用代码库克隆到本地机器:
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 文件并将其解压缩。
切换到包含用于访问 Bigtable 的 Cloud Functions 函数示例代码的目录:
Node.js
cd nodejs-docs-samples/functions/bigtable/
Python
cd python-docs-samples/functions/bigtable/
Go
cd golang-samples/functions/bigtable/
查看示例代码:
Node.js
Python
Go
该函数会向表发送读取请求,以提取行键前缀为
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
函数部署最多可能需要 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"
其中,REGION
和 PROJECT_ID
与函数完成部署时终端中显示的值一致。您应该会看到显示读取请求结果的输出。
您还可以在浏览器中访问函数的网址,以查看读取请求的结果。
清理
为避免系统因本主题中使用的 Bigtable 和 Cloud Functions 资源向您的 Google Cloud 账号收取额外费用,请执行以下操作:
删除实例:
gcloud bigtable instances delete test-instance
删除您部署的函数:
Node.js
gcloud functions delete get
Python
gcloud functions delete bigtable_read_data
Go
gcloud functions delete BigtableRead