目標
編寫、部署及觸發可存取 Spanner 的 HTTP Cloud Run 函式。
費用
本文使用 Spanner 和 Cloud Run 函式,這兩者都是 Google Cloud的計費元件。
如要瞭解 Spanner 的使用費用,請參閱 Spanner 定價。
如要瞭解 Cloud Run functions 的使用費用,包括免費叫用,請參閱 Cloud Run functions 定價。
事前準備
本文假設您擁有一個名為
test-instance
的 Spanner 執行個體,以及一個名為example-db
且使用音樂應用程式結構定義的資料庫。如需使用音樂應用程式結構定義建立執行個體與資料庫的操作說明,請參閱使用主控台的快速入門導覽課程,或 Go、Java、Node.js 或 Python 中的入門指南教學課程。啟用 Cloud Run functions 和 Cloud Build 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 格式的範例,然後解壓縮該檔案。
Java
git clone https://github.com/GoogleCloudPlatform/java-docs-samples.git
您也可以 下載 zip 格式的範例,然後解壓縮該檔案。
變更到包含 Cloud Run 函式程式碼範例的目錄,以存取 Spanner:
Node.js
cd nodejs-docs-samples/functions/spanner/
Python
cd python-docs-samples/functions/spanner/
Go
cd golang-samples/functions/spanner/
Java
cd java-docs-samples/functions/spanner/
查看程式碼範例:
Node.js
Python
Go
Java
函式會傳送 SQL 查詢,從您的資料庫擷取所有
Albums
資料。當您對函式端點提出 HTTP 要求時,函式就會執行。
部署函式
如要使用 HTTP 觸發條件部署函式,請在 spanner
目錄中執行下列指令:
Node.js
gcloud functions deploy get \ --runtime nodejs20 --trigger-http
使用 --runtime
標記指定支援的 Node.js 版本執行階段 ID,以執行函式。
Python
gcloud functions deploy spanner_read_data \ --runtime python312 --trigger-http
使用 --runtime
標記指定支援的 Python 版本執行階段 ID,以執行函式。
Go
gcloud functions deploy HelloSpanner \ --runtime go121 --trigger-http
Java
gcloud functions deploy java-spanner-function \ --entry-point functions.HelloSpanner \ --runtime java17 \ --memory 512MB --trigger-http
使用 --runtime
標記指定支援的 Java 版本執行函式的執行階段 ID。
部署函式可能需要兩分鐘的時間。
請注意函式完成部署時傳回的 url
值。您將會在觸發函式時使用它。
您可以在Google Cloud 控制台的「Cloud Run functions」頁面中,查看已部署的函式。您也可在該頁面上建立及編輯函式,並取得函式的詳細資料與診斷資訊。
觸發函式
對您的函式提出 HTTP 要求:
Node.js
curl "https://REGION-PROJECT_ID.cloudfunctions.net/get"
Python
curl "https://REGION-PROJECT_ID.cloudfunctions.net/spanner_read_data"
Go
curl "https://REGION-PROJECT_ID.cloudfunctions.net/HelloSpanner"
Java
curl "https://REGION-PROJECT_ID.cloudfunctions.net/java-spanner-function"
其中 REGION
和 PROJECT_ID
符合函式完成部署時,您在終端機中看見的值。您應會看見輸出顯示 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 函式資源的額外費用,請執行下列操作:
刪除執行個體:
gcloud spanner instances delete test-instance
刪除您部署的函式: <0
Node.js
gcloud functions delete get
Python
gcloud functions delete spanner_read_data
Go
gcloud functions delete HelloSpanner
Java
gcloud functions delete java-spanner-function