您可以使用直接虛擬私有雲輸出,從 Cloud Run 函式連線至 Redis 執行個體。
設定
如果您已安裝 Google Cloud CLI 並建立 Redis 執行個體,可以略過這些步驟。
安裝 gcloud CLI 並初始化:
gcloud init
按照快速入門指南中的說明建立 Redis 執行個體。請記下 Redis 執行個體的區域、IP 位址和通訊埠。
準備設定虛擬私有雲網路輸出
如要連線至 Redis 執行個體,Cloud Run 函式必須有權存取 Redis 執行個體授權的虛擬私有雲網路。
如要找出這個網路的名稱,請執行下列指令:
gcloud redis instances describe INSTANCE_ID --region REGION --format "value(authorizedNetwork)"
記下網路名稱。
範例函式
本範例函式會從 Cloud Run functions 建立與 Redis 執行個體的連線。
複製所需程式語言的存放區,然後前往包含範例程式碼的資料夾:
Go
git clone https://github.com/GoogleCloudPlatform/golang-samples
cd golang-samples/functions/memorystore/redis
Node.js
git clone https://github.com/GoogleCloudPlatform/nodejs-docs-samples
cd nodejs-docs-samples/functions/memorystore/redis
Python
git clone https://github.com/GoogleCloudPlatform/python-docs-samples
cd python-docs-samples/functions/memorystore/redis
範例程式碼會在每次觸發函式時遞增 Redis 計數器:
將範例部署至 Cloud Run 函式
如何部署函式:
將
Dockerfile
複製到來源目錄:cp cloud_run_deployment/Dockerfile .
執行下列指令,使用 Cloud Build 建構容器映像檔:
gcloud builds submit --tag gcr.io/PROJECT_ID/visit-count
執行下列指令,將容器部署至 Cloud Run:
gcloud run deploy \ --image gcr.io/PROJECT_ID/visit-count \ --allow-unauthenticated \ --region REGION \ --network NETWORK \ --subnet SUBNET \ --set-env-vars REDISHOST=REDIS_IP,REDISPORT=REDIS_PORT
其中:
函式部署完成後,請擷取函式的網址:
gcloud run services describe visit-count \ --region=REGION
每次傳送 GET
要求至函式的網址,您都會看到計數器增加。