Menghubungkan ke instance Redis dari fungsi Cloud Run

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

Penyiapan

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

  1. Instal gcloud CLI dan lakukan inisialisasi:

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

Mengonfigurasi Akses VPC Serverless

Untuk terhubung dari fungsi Cloud Run ke jaringan VPC resmi instance Redis, Anda harus menyiapkan Akses VPC Serverless.

  1. Temukan jaringan resmi instance Redis Anda dengan menjalankan perintah:

    gcloud redis instances describe INSTANCE_ID --region REGION
  2. Ikuti petunjuk di Membuat konektor untuk membuat konektor Akses VPC Tanpa Server. Pastikan Anda membuat konektor di region yang sama dengan tempat Anda ingin men-deploy fungsi, dan pastikan konektor terhubung ke jaringan VPC yang diizinkan instance Redis. Ingat nama konektor.

Fungsi contoh

Fungsi contoh ini membuat koneksi ke instance Redis dari fungsi Cloud Run.

Buat 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 menambahkan 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 fungsi Cloud Run

Deploy fungsi menggunakan Google Cloud CLI:

Go

gcloud run deploy visit-count \
    --region=REGION \
    --source=. \
    --base-image=BASE_IMAGE \
    --function=VisitCount \
    --vpc-connector=projects/PROJECT_ID/locations/REGION/connectors/CONNECTOR_NAME \
    --set-env-vars=REDISHOST=REDIS_IP,REDISPORT=REDIS_PORT

Node.js

gcloud run deploy visit-count \
    --region=REGION \
    --source=. \
    --base-image=BASE_IMAGE \
    --entry-point=visitCount \
    --vpc-connector=projects/PROJECT_ID/locations/REGION/connectors/CONNECTOR_NAME \
    --set-env-vars=REDISHOST=REDIS_IP,REDISPORT=REDIS_PORT

Python

gcloud run deploy visit-count \
    --region=REGION \
    --source=. \
    --base-image=BASE_IMAGE \
    --function=visit_count \
    --vpc-connector=projects/PROJECT_ID/locations/REGION/connectors/CONNECTOR_NAME \
    --set-env-vars=REDISHOST=REDIS_IP,REDISPORT=REDIS_PORT

Ganti:

  • REGION dengan region tempat Anda ingin men-deploy fungsi.
  • BASE_IMAGE dengan image dasar untuk fungsi, misalnya, go116, nodejs16, atau python310. Untuk mengetahui informasi selengkapnya, lihat Runtime bahasa dan image dasar yang didukung untuk mengetahui informasi selengkapnya.
  • PROJECT_ID dengan ID Google Cloud project Anda.
  • CONNECTOR_NAME dengan nama konektor Anda.
  • REDIS_IP dan REDIS_PORT dengan alamat IP dan nomor port instance Redis Anda.

Setelah deployment fungsi selesai, ambil URL fungsi Anda:

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

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