Menghubungkan ke instance Redis dari Cloud Functions

Anda dapat terhubung ke instance Redis dari Cloud Functions menggunakan Akses VPC Serverless.

Penyiapan

Jika telah menginstal Google Cloud CLI dan telah membuat instance Redis, Anda dapat melewati langkah-langkah ini.

  1. Instal gcloud CLI dan lakukan inisialisasi:

    gcloud init
    
  2. Ikuti Panduan Cepat untuk membuat instance Redis. Catat zona, alamat IP, dan port instance Redis.

Mengonfigurasi Akses VPC Serverless

Untuk terhubung dari Cloud Functions ke jaringan VPC yang diberi otorisasi oleh instance Redis, Anda harus menyiapkan Akses VPC Tanpa Server.

  1. Temukan jaringan yang telah diberi otorisasi untuk instance Redis Anda dengan menjalankan perintah:

    gcloud redis instances describe INSTANCE_ID --region REGION
    
  2. Ikuti petunjuk dalam artikel Membuat konektor untuk membuat konektor Akses VPC Serverless. Pastikan Anda membuat konektor di region yang sama tempat Anda ingin men-deploy fungsi, dan pastikan konektor terhubung ke jaringan VPC yang diberi otorisasi oleh instance Redis. Ingat nama konektornya.

Fungsi contoh

Fungsi contoh ini membuat koneksi ke instance Redis dari Cloud Functions.

Clone repositori untuk bahasa pemrograman yang Anda inginkan dan buka folder yang berisi kode contoh:

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

Kode contoh menambah penghitung Redis setiap kali fungsi dipicu:

Go

Fungsi ini menggunakan klien 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

Fungsi ini menggunakan 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

Fungsi ini menggunakan 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}"

Men-deploy sampel ke Cloud Functions

Deploy fungsi menggunakan 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

dengan:

  • PROJECT_ID adalah ID project Google Cloud Anda.
  • REGION adalah region tempat Anda ingin men-deploy fungsi.
  • CONNECTOR_NAME adalah nama konektor Anda.
  • REDIS_IP dan REDIS_PORT adalah alamat IP dan nomor port instance Redis Anda.

Setelah deployment fungsi selesai, ambil URL fungsi Anda:

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

Anda dapat melihat penghitung meningkat setiap kali memicu fungsi dengan mengirim permintaan GET ke URL-nya.