從 Cloud Run 服務連線至 Redis 執行個體

您可以使用直接虛擬私有雲輸出無伺服器虛擬私有雲存取,從 Cloud Run 連線至 Redis 執行個體。

設定

如果您已安裝 Google Cloud CLI 並建立 Redis 執行個體,可以略過這些步驟。

  1. 安裝 gcloud CLI 並初始化:

    gcloud init
    
  2. 按照快速入門指南中的說明建立 Redis 執行個體。請記下 Redis 執行個體的區域、IP 位址和通訊埠。

準備設定虛擬私有雲網路的輸出端

如要連線至 Redis 執行個體,Cloud Run 服務必須能存取 Redis 執行個體的授權虛擬私有雲網路。如要啟用這項存取權,您必須使用直接虛擬私有雲輸出或無伺服器虛擬私有雲存取連接器。比較兩種網路出口方法

  1. 執行下列指令,找出 Redis 執行個體的授權網路名稱:

    gcloud redis instances describe INSTANCE_ID --region REGION --format "value(authorizedNetwork)"
    

    請記下網路名稱。

  2. 如果您使用無伺服器虛擬私有雲端存取,請建立連接器。請務必使用與 Redis 執行個體相同的地區和 VPC 網路。請記下連接器的名稱。

應用程式範例

這個 HTTP 伺服器應用程式範例會從 Cloud Run 服務建立與 Redis 執行個體的連線。

複製所選程式設計語言的存放區,然後前往包含範例程式碼的資料夾:

Go

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

Node.js

git clone https://github.com/GoogleCloudPlatform/nodejs-docs-samples
cd nodejs-docs-samples/memorystore/redis

Python

git clone https://github.com/GoogleCloudPlatform/python-docs-samples
cd python-docs-samples/memorystore/redis

這個範例應用程式會在每次存取 / 端點時遞增 Redis 計數器。

Go

這個應用程式使用 github.com/gomodule/redigo/redis 用戶端。執行下列指令即可安裝:

go get github.com/gomodule/redigo/redis

// Command redis is a basic app that connects to a managed Redis instance.
package main

import (
	"fmt"
	"log"
	"net/http"
	"os"

	"github.com/gomodule/redigo/redis"
)

var redisPool *redis.Pool

func incrementHandler(w http.ResponseWriter, r *http.Request) {
	conn := redisPool.Get()
	defer conn.Close()

	counter, err := redis.Int(conn.Do("INCR", "visits"))
	if err != nil {
		http.Error(w, "Error incrementing visitor counter", http.StatusInternalServerError)
		return
	}
	fmt.Fprintf(w, "Visitor number: %d", counter)
}

func main() {
	redisHost := os.Getenv("REDISHOST")
	redisPort := os.Getenv("REDISPORT")
	redisAddr := fmt.Sprintf("%s:%s", redisHost, redisPort)

	const maxConnections = 10
	redisPool = &redis.Pool{
		MaxIdle: maxConnections,
		Dial:    func() (redis.Conn, error) { return redis.Dial("tcp", redisAddr) },
	}

	http.HandleFunc("/", incrementHandler)

	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
	}
	log.Printf("Listening on port %s", port)
	if err := http.ListenAndServe(":"+port, nil); err != nil {
		log.Fatal(err)
	}
}

Node.js

這個應用程式會使用 redis 模組。

{
  "name": "memorystore-redis",
  "description": "An example of using Memorystore(Redis) with Node.js",
  "version": "0.0.1",
  "private": true,
  "license": "Apache Version 2.0",
  "author": "Google Inc.",
  "engines": {
    "node": ">=16.0.0"
  },
  "dependencies": {
    "redis": "^4.0.0"
  }
}

'use strict';
const http = require('http');
const redis = require('redis');

const REDISHOST = process.env.REDISHOST || 'localhost';
const REDISPORT = process.env.REDISPORT || 6379;

const client = redis.createClient(REDISPORT, REDISHOST);
client.on('error', err => console.error('ERR:REDIS:', err));

// create a server
http
  .createServer((req, res) => {
    // increment the visit counter
    client.incr('visits', (err, reply) => {
      if (err) {
        console.log(err);
        res.status(500).send(err.message);
        return;
      }
      res.writeHead(200, {'Content-Type': 'text/plain'});
      res.end(`Visitor number: ${reply}\n`);
    });
  })
  .listen(8080);

Python

此應用程式使用 Flask 提供網頁服務,並使用 redis-py 套件與 Redis 執行個體通訊。

Flask==3.0.3
gunicorn==23.0.0
redis==6.0.0
Werkzeug==3.0.3
import logging
import os

from flask import Flask
import redis

app = Flask(__name__)

redis_host = os.environ.get("REDISHOST", "localhost")
redis_port = int(os.environ.get("REDISPORT", 6379))
redis_client = redis.StrictRedis(host=redis_host, port=redis_port)


@app.route("/")
def index():
    value = redis_client.incr("counter", 1)
    return f"Visitor number: {value}"


@app.errorhandler(500)
def server_error(e):
    logging.exception("An error occurred during a request.")
    return (
        """
    An internal error occurred: <pre>{}</pre>
    See logs for full stacktrace.
    """.format(
            e
        ),
        500,
    )


if __name__ == "__main__":
    # This is used when running locally. Gunicorn is used to run the
    # application on Google App Engine and Cloud Run.
    # See entrypoint in app.yaml or Dockerfile.
    app.run(host="127.0.0.1", port=8080, debug=True)

將應用程式部署至 Cloud Run

如要部署應用程式,請按照下列步驟操作:

  1. Dockerfile 複製到來源目錄:

    cp cloud_run_deployment/Dockerfile .
    
  2. 使用下列指令,透過 Cloud Build 建構容器映像檔:

    gcloud builds submit --tag gcr.io/PROJECT_ID/visit-count
    
  3. 將容器部署至 Cloud Run。

    • 如果您使用直接虛擬私有雲來處理輸出流量,請執行下列指令:

      gcloud run deploy \
      --image gcr.io/PROJECT_ID/visit-count \
      --platform managed \
      --allow-unauthenticated \
      --region REGION \
      --network NETWORK \
      --subnet SUBNET \
      --set-env-vars REDISHOST=REDIS_IP,REDISPORT=REDIS_PORT
      

      其中:

      • PROJECT_ID 是您的 Google Cloud 專案 ID。
      • REGION 是 Redis 執行個體所在的地區。
      • NETWORK 是 Redis 執行個體所屬的授權 VPC 網路名稱。
      • SUBNET 是子網路的名稱。子網路不得小於 /26。直接虛擬私人雲端出口支援 IPv4 範圍 RFC 1918RFC 6598 和 Class E。
      • REDIS_IPREDIS_PORT 分別是 Redis 執行個體的 IP 位址和通訊埠編號。
    • 如果您使用無伺服器虛擬私有雲存取連接器,請執行下列指令:

      gcloud run deploy \
      --image gcr.io/PROJECT_ID/visit-count \
      --platform managed \
      --allow-unauthenticated \
      --region REGION \
      --vpc-connector CONNECTOR_NAME \
      --set-env-vars REDISHOST=REDIS_IP,REDISPORT=REDIS_PORT
      

      其中:

      • PROJECT_ID 是 Google Cloud 專案 ID。
      • REGION 是無伺服器虛擬私有雲存取連接器和 Redis 執行個體所在的區域。
      • CONNECTOR_NAME 是連接器名稱。
      • REDIS_IPREDIS_PORT 分別是 Redis 執行個體的 IP 位址和通訊埠編號。

部署作業完成後,指令列會顯示 Cloud Run 服務的網址。在網路瀏覽器中造訪這個網址 (或使用 curl 等工具),即可查看每次造訪服務時,Redis 例項的計數會增加。