从 Cloud Run functions 连接到 Redis 实例

您可以使用直接 VPC 出站流量从 Cloud Run functions 连接到 Redis 实例。

设置

如果您已安装 Google Cloud CLI 且已创建 Redis 实例,则可以跳过这些步骤。

  1. 安装 gcloud CLI 并初始化:

    gcloud init
    
  2. 按照快速入门指南创建一个 Redis 实例。记下该 Redis 实例的地区、IP 地址和端口。

准备 VPC 网络出站流量以进行配置

如需连接到 Redis 实例,您的 Cloud Run 函数必须有权访问 Redis 实例的已获授权的 VPC 网络。

如需查找此网络的名称,请运行以下命令:

  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 计数器:

Go

此函数使用 github.com/gomodule/redigo/redis 客户端。


// Package visitcount provides a Cloud Function that connects
// to a managed Redis instance.
package visitcount

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

	"github.com/GoogleCloudPlatform/functions-framework-go/functions"
	"github.com/gomodule/redigo/redis"
)

var redisPool *redis.Pool

func init() {
	// Register the HTTP handler with the Functions Framework
	functions.HTTP("VisitCount", visitCount)
}

// initializeRedis initializes and returns a connection pool
func initializeRedis() (*redis.Pool, error) {
	redisHost := os.Getenv("REDISHOST")
	if redisHost == "" {
		return nil, errors.New("REDISHOST must be set")
	}
	redisPort := os.Getenv("REDISPORT")
	if redisPort == "" {
		return nil, errors.New("REDISPORT must be set")
	}
	redisAddr := fmt.Sprintf("%s:%s", redisHost, redisPort)

	const maxConnections = 10
	return &redis.Pool{
		MaxIdle: maxConnections,
		Dial: func() (redis.Conn, error) {
			c, err := redis.Dial("tcp", redisAddr)
			if err != nil {
				return nil, fmt.Errorf("redis.Dial: %w", err)
			}
			return c, err
		},
	}, nil
}

// visitCount increments the visit count on the Redis instance
// and prints the current count in the HTTP response.
func visitCount(w http.ResponseWriter, r *http.Request) {
	// Initialize connection pool on first invocation
	if redisPool == nil {
		// Pre-declare err to avoid shadowing redisPool
		var err error
		redisPool, err = initializeRedis()
		if err != nil {
			log.Printf("initializeRedis: %v", err)
			http.Error(w, "Error initializing connection pool", http.StatusInternalServerError)
			return
		}
	}

	conn := redisPool.Get()
	defer conn.Close()

	counter, err := redis.Int(conn.Do("INCR", "visits"))
	if err != nil {
		log.Printf("redis.Int: %v", err)
		http.Error(w, "Error incrementing visit count", http.StatusInternalServerError)
		return
	}
	fmt.Fprintf(w, "Visit count: %d", counter)
}

Node.js

此函数使用 redis 模块。


const functions = require('@google-cloud/functions-framework');
const redis = require('redis');

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

const redisClient = redis.createClient({
  socket: {
    host: REDISHOST,
    port: REDISPORT,
  },
});
redisClient.on('error', err => console.error('ERR:REDIS:', err));
redisClient.connect();

functions.http('visitCount', async (req, res) => {
  try {
    const response = await redisClient.incr('visits');
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end(`Visit count: ${response}`);
  } catch (err) {
    console.log(err);
    res.status(500).send(err.message);
  }
});

Python

此函数使用 redis-py 软件包。


import os

import functions_framework
import redis

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)


@functions_framework.http
def visit_count(request):
    value = redis_client.incr("visits", 1)
    return f"Visit count: {value}"

将示例部署到 Cloud Run functions

如需部署函数,请执行以下操作:

  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 \
        --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 或更大。直接 VPC 出站流量支持 RFC 1918RFC 6598 和 E 类 IPv4 范围。
    • REDIS_IPREDIS_PORT 是 Redis 实例的 IP 地址和端口号。

函数部署完成后,检索函数的网址:

gcloud run services describe visit-count \
--region=REGION

每次通过向函数的网址发送 GET 请求来触发函数时,您都可以看到计数器增加。