Menghubungkan ke instance Redis dari fungsi Cloud Run

Anda dapat terhubung ke instance Redis dari fungsi Cloud Run menggunakan traffic keluar VPC Langsung.

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.

Menyiapkan traffic keluar jaringan VPC untuk konfigurasi

Agar terhubung ke instance Redis, fungsi Cloud Run Anda harus memiliki akses ke jaringan VPC resmi instance Redis.

Untuk menemukan nama jaringan ini, jalankan perintah berikut:

  gcloud redis instances describe INSTANCE_ID --region REGION --format "value(authorizedNetwork)"

Catat nama jaringan.

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

Untuk men-deploy fungsi tersebut:

  1. Salin Dockerfile ke direktori sumber:

    cp cloud_run_deployment/Dockerfile .
    
  2. Bangun image container menggunakan Cloud Build dengan menjalankan perintah berikut:

    gcloud builds submit --tag gcr.io/PROJECT_ID/visit-count
    
  3. Deploy container ke Cloud Run dengan menjalankan perintah berikut:

        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
    

    dengan:

    • PROJECT_ID adalah ID Google Cloud project's Anda.
    • REGION adalah region tempat instance Redis Anda berada.
    • NETWORK adalah nama jaringan VPC resmi yang terhubung ke instance Redis Anda.
    • SUBNET adalah nama subnet Anda. Subnet harus berukuran /26 atau lebih besar. Traffic keluar VPC langsung mendukung rentang IPv4 RFC 1918, RFC 6598, dan Class E.
    • REDIS_IP dan REDIS_PORT adalah 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.