从 Cloud Functions 连接到 Redis 实例

您可以使用无服务器 VPC 访问通道从 Cloud Functions 连接到 Redis 实例。

设置

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

  1. 安装 gcloud CLI 并进行初始化:

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

配置无服务器 VPC 访问通道

要从 Cloud Functions 连接到 Redis 实例的授权 VPC 网络,您必须设置无服务器 VPC 访问通道。

  1. 通过运行以下命令查找 Redis 实例的授权网络:

    gcloud redis instances describe INSTANCE_ID --region REGION
    
  2. 按照创建连接器中的说明创建无服务器 VPC 访问通道连接器。请务必在要部署函数的同一区域中创建连接器,并确保连接器已连接到 Redis 实例的授权 VPC 网络。记下连接器的名称。

示例函数

此示例函数从 Cloud 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 Functions

使用 Google Cloud CLI 部署函数:

Go

gcloud functions deploy visit-count \
--gen2 \
--region=REGION \
--runtime=go116 \
--source=. \
--entry-point=VisitCount \
--trigger-http \
--vpc-connector=projects/PROJECT_ID/locations/REGION/connectors/CONNECTOR_NAME \
--set-env-vars=REDISHOST=REDIS_IP,REDISPORT=REDIS_PORT

Node.js

gcloud functions deploy visit-count \
--gen2 \
--region=REGION \
--runtime=nodejs16 \
--source=. \
--entry-point=visitCount \
--trigger-http \
--vpc-connector=projects/PROJECT_ID/locations/REGION/connectors/CONNECTOR_NAME \
--set-env-vars=REDISHOST=REDIS_IP,REDISPORT=REDIS_PORT

Python

gcloud functions deploy visit-count \
--gen2 \
--region=REGION \
--runtime=python310 \
--source=. \
--entry-point=visit_count \
--trigger-http \
--vpc-connector=projects/PROJECT_ID/locations/REGION/connectors/CONNECTOR_NAME \
--set-env-vars=REDISHOST=REDIS_IP,REDISPORT=REDIS_PORT

其中:

  • PROJECT_ID 是 Google Cloud 项目 ID。
  • REGION 是您要部署函数的区域。
  • CONNECTOR_NAME 是连接器的名称。
  • REDIS_IPREDIS_PORT 是 Redis 实例的 IP 地址和端口号。

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

gcloud functions describe visit-count \
--gen2 \
--region=REGION \
--format="value(serviceConfig.uri)"

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