Verbindung zu einer Redis-Instanz über Cloud Functions herstellen

Sie können über Cloud Functions mithilfe von serverlosem VPC-Zugriff eine Verbindung zu einer Redis-Instanz herstellen.

Einrichtung

Wenn Sie die Google Cloud CLI bereits installiert und eine Redis-Instanz erstellt haben, können Sie diese Schritte überspringen.

  1. Installieren Sie die gcloud CLI und initialisieren Sie:

    gcloud init
    
  2. Folgen Sie der Schnellstartanleitung zum Erstellen einer Redis-Instanz. Notieren Sie sich die Zone, die IP-Adresse und den Port der Redis-Instanz.

Serverlosen VPC-Zugriff konfigurieren

Damit Sie eine Verbindung von Ihrer Cloud Functions-Funktion zum autorisierten VPC-Netzwerk Ihrer Redis-Instanz herstellen können, müssen Sie den serverlosen VPC-Zugriff einrichten.

  1. Suchen Sie mit dem folgenden Befehl nach dem autorisierten Netzwerk Ihrer Redis-Instanz:

    gcloud redis instances describe INSTANCE_ID --region REGION
    
  2. Folgen Sie der Anleitung unter Connector erstellen, um einen Connector für serverlosen VPC-Zugriff zu erstellen. Erstellen Sie den Connector in derselben Region, in der Sie die Funktion bereitstellen möchten, und achten Sie darauf, dass er mit dem autorisierten VPC-Netzwerk der Redis-Instanz verbunden ist. Merken Sie sich den Namen des Connectors.

Beispielfunktion

Diese Beispielfunktion stellt eine Verbindung zu einer Redis-Instanz über Cloud Functions her.

Klonen Sie das Repository für die gewünschte Programmiersprache und rufen Sie den Ordner auf, der den Beispielcode enthält:

Einfach loslegen (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

Der Beispielcode erhöht einen Redis-Zähler jedes Mal, wenn die Funktion ausgelöst wird:

Einfach loslegen (Go)

Diese Funktion verwendet den github.com/gomodule/redigo/redis-Client.


// 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

Diese Funktion verwendet das Modul 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

Diese Funktion verwendet das Paket 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}"

Beispiel in Cloud Functions bereitstellen

Stellen Sie die Funktion über die Google Cloud CLI bereit:

Einfach loslegen (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

Dabei gilt:

  • PROJECT_ID ist die ID Ihres Google Cloud-Projekts.
  • REGION ist die Region, in der Sie die Funktion bereitstellen möchten.
  • CONNECTOR_NAME ist der Name Ihres Connectors.
  • REDIS_IP und REDIS_PORT sind die IP-Adresse und Portnummer Ihrer Redis-Instanz.

Rufen Sie nach Abschluss der Funktionsbereitstellung die URL der Funktion ab:

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

Sie können sehen, wie sich der Zähler jedes Mal erhöht, wenn Sie die Funktion durch Senden einer GET-Anfrage an ihre URL auslösen.