目標
編寫、部署及觸發可存取 Spanner 的 HTTP Cloud Run 函式。
費用
本文使用 Spanner 和 Cloud Run 函式,這兩者都是 Google Cloud的計費元件。
如要瞭解 Spanner 的使用費用,請參閱 Spanner 定價。
如要瞭解 Cloud Run 函式的使用費用,包括免費叫用,請參閱 Cloud Run 函式定價。
事前準備
本文假設您擁有一個名為
test-instance的 Spanner 執行個體,以及一個名為example-db且使用音樂應用程式架構的資料庫。如需使用音樂應用程式架構建立執行個體與資料庫的操作說明,請參閱使用主控台的快速入門導覽課程,或 Go、Java、Node.js 或 Python 中的入門指南教學課程。啟用 Cloud Run 函式和 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 nodejs22 --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 函式」頁面中,查看已部署的函式。您也可在該頁面上建立及編輯函式,並取得函式的詳細資料與診斷資訊。
觸發函式
對您的函式提出 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刪除您部署的函式:
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