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:
// Package visitcount provides a Cloud Function that connects// to a managed Redis instance.packagevisitcountimport("errors""fmt""log""net/http""os""github.com/GoogleCloudPlatform/functions-framework-go/functions""github.com/gomodule/redigo/redis")varredisPool*redis.Poolfuncinit(){// Register the HTTP handler with the Functions Frameworkfunctions.HTTP("VisitCount",visitCount)}// initializeRedis initializes and returns a connection poolfuncinitializeRedis()(*redis.Pool,error){redisHost:=os.Getenv("REDISHOST")ifredisHost==""{returnnil,errors.New("REDISHOST must be set")}redisPort:=os.Getenv("REDISPORT")ifredisPort==""{returnnil,errors.New("REDISPORT must be set")}redisAddr:=fmt.Sprintf("%s:%s",redisHost,redisPort)constmaxConnections=10return&redis.Pool{MaxIdle:maxConnections,Dial:func()(redis.Conn,error){c,err:=redis.Dial("tcp",redisAddr)iferr!=nil{returnnil,fmt.Errorf("redis.Dial: %w",err)}returnc,err},},nil}// visitCount increments the visit count on the Redis instance// and prints the current count in the HTTP response.funcvisitCount(whttp.ResponseWriter,r*http.Request){// Initialize connection pool on first invocationifredisPool==nil{// Pre-declare err to avoid shadowing redisPoolvarerrerrorredisPool,err=initializeRedis()iferr!=nil{log.Printf("initializeRedis: %v",err)http.Error(w,"Error initializing connection pool",http.StatusInternalServerError)return}}conn:=redisPool.Get()deferconn.Close()counter,err:=redis.Int(conn.Do("INCR","visits"))iferr!=nil{log.Printf("redis.Int: %v",err)http.Error(w,"Error incrementing visit count",http.StatusInternalServerError)return}fmt.Fprintf(w,"Visit count: %d",counter)}
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:
[[["Mudah dipahami","easyToUnderstand","thumb-up"],["Memecahkan masalah saya","solvedMyProblem","thumb-up"],["Lainnya","otherUp","thumb-up"]],[["Sulit dipahami","hardToUnderstand","thumb-down"],["Informasi atau kode contoh salah","incorrectInformationOrSampleCode","thumb-down"],["Informasi/contoh yang saya butuhkan tidak ada","missingTheInformationSamplesINeed","thumb-down"],["Masalah terjemahan","translationIssue","thumb-down"],["Lainnya","otherDown","thumb-down"]],["Terakhir diperbarui pada 2025-09-05 UTC."],[],[],null,["# Connecting to a Redis instance from Cloud Run functions\n\nYou can connect to a Redis instance from Cloud Run functions by using\n[Serverless VPC Access](/vpc/docs/configure-serverless-vpc-access).\n\nSetup\n-----\n\nIf you have already installed the Google Cloud CLI and have created a Redis\ninstance, you can skip these steps.\n\n1. [Install the gcloud CLI](https://cloud.google.com/sdk/docs/) and initialize:\n\n gcloud init\n\n2. Follow the [Quickstart Guide](/memorystore/docs/redis/create-instance-gcloud)\n to create a Redis instance. Take note of the zone, IP address, and port of\n the Redis instance.\n\nConfiguring Serverless VPC Access\n---------------------------------\n\nTo connect from your Cloud Run functions to your Redis instance's\nauthorized VPC network, you must set up Serverless VPC Access.\n\n1. Find your Redis instance's authorized network by running the command:\n\n ```bash\n gcloud redis instances describe INSTANCE_ID --region REGION\n ```\n2. Follow the instructions at\n [Creating a connector](/vpc/docs/configure-serverless-vpc-access#create-connector)\n to create a Serverless VPC Access connector. Make sure you\n create the connector in the same region where you want to deploy your\n function, and make sure the connector is attached to the Redis instance's\n authorized VPC network. Remember the name of the connector.\n\nSample function\n---------------\n\nThis sample function establishes a connection to a Redis instance from\nCloud Run functions.\n\nClone the repository for your desired programming language and navigate\nto the folder that contains the sample code: \n\n### Go\n\n git clone https://github.com/GoogleCloudPlatform/golang-samples\n cd golang-samples/functions/memorystore/redis\n\n### Node.js\n\n git clone https://github.com/GoogleCloudPlatform/nodejs-docs-samples\n cd nodejs-docs-samples/functions/memorystore/redis\n\n### Python\n\n git clone https://github.com/GoogleCloudPlatform/python-docs-samples\n cd python-docs-samples/functions/memorystore/redis\n\nThe sample code increments a Redis counter every time the function is triggered: \n\n### Go\n\nThis function uses the\n[`github.com/gomodule/redigo/redis`](https://godoc.org/github.com/gomodule/redigo/redis)\nclient. \n\n\n // Package visitcount provides a Cloud Function that connects\n // to a managed Redis instance.\n package visitcount\n\n import (\n \t\"errors\"\n \t\"fmt\"\n \t\"log\"\n \t\"net/http\"\n \t\"os\"\n\n \t\"github.com/GoogleCloudPlatform/functions-framework-go/functions\"\n \t\"github.com/gomodule/redigo/redis\"\n )\n\n var redisPool *redis.Pool\n\n func init() {\n \t// Register the HTTP handler with the Functions Framework\n \tfunctions.HTTP(\"VisitCount\", visitCount)\n }\n\n // initializeRedis initializes and returns a connection pool\n func initializeRedis() (*redis.Pool, error) {\n \tredisHost := os.Getenv(\"REDISHOST\")\n \tif redisHost == \"\" {\n \t\treturn nil, errors.New(\"REDISHOST must be set\")\n \t}\n \tredisPort := os.Getenv(\"REDISPORT\")\n \tif redisPort == \"\" {\n \t\treturn nil, errors.New(\"REDISPORT must be set\")\n \t}\n \tredisAddr := fmt.Sprintf(\"%s:%s\", redisHost, redisPort)\n\n \tconst maxConnections = 10\n \treturn &redis.Pool{\n \t\tMaxIdle: maxConnections,\n \t\tDial: func() (redis.Conn, error) {\n \t\t\tc, err := redis.Dial(\"tcp\", redisAddr)\n \t\t\tif err != nil {\n \t\t\t\treturn nil, fmt.Errorf(\"redis.Dial: %w\", err)\n \t\t\t}\n \t\t\treturn c, err\n \t\t},\n \t}, nil\n }\n\n // visitCount increments the visit count on the Redis instance\n // and prints the current count in the HTTP response.\n func visitCount(w http.ResponseWriter, r *http.Request) {\n \t// Initialize connection pool on first invocation\n \tif redisPool == nil {\n \t\t// Pre-declare err to avoid shadowing redisPool\n \t\tvar err error\n \t\tredisPool, err = initializeRedis()\n \t\tif err != nil {\n \t\t\tlog.Printf(\"initializeRedis: %v\", err)\n \t\t\thttp.Error(w, \"Error initializing connection pool\", http.StatusInternalServerError)\n \t\t\treturn\n \t\t}\n \t}\n\n \tconn := redisPool.Get()\n \tdefer conn.Close()\n\n \tcounter, err := redis.Int(conn.Do(\"INCR\", \"visits\"))\n \tif err != nil {\n \t\tlog.Printf(\"redis.Int: %v\", err)\n \t\thttp.Error(w, \"Error incrementing visit count\", http.StatusInternalServerError)\n \t\treturn\n \t}\n \tfmt.Fprintf(w, \"Visit count: %d\", counter)\n }\n\n### Node.js\n\nThis function uses the [`redis`](https://www.npmjs.com/package/redis)\nmodule. \n\n\n const functions = require('@google-cloud/functions-framework');\n const redis = require('redis');\n\n const REDISHOST = process.env.REDISHOST || 'localhost';\n const REDISPORT = process.env.REDISPORT || 6379;\n\n const redisClient = redis.createClient({\n socket: {\n host: REDISHOST,\n port: REDISPORT,\n },\n });\n redisClient.on('error', err =\u003e console.error('ERR:REDIS:', err));\n redisClient.connect();\n\n functions.http('visitCount', async (req, res) =\u003e {\n try {\n const response = await redisClient.incr('visits');\n res.writeHead(200, {'Content-Type': 'text/plain'});\n res.end(`Visit count: ${response}`);\n } catch (err) {\n console.log(err);\n res.status(500).send(err.message);\n }\n });\n\n### Python\n\nThis function uses the\n[`redis-py`](https://redis-py.readthedocs.io/en/latest/) package. \n\n\n import os\n\n import functions_framework\n import redis\n\n redis_host = os.environ.get(\"REDISHOST\", \"localhost\")\n redis_port = int(os.environ.get(\"REDISPORT\", 6379))\n redis_client = redis.StrictRedis(host=redis_host, port=redis_port)\n\n\n @functions_framework.http\n def visit_count(request):\n value = redis_client.incr(\"visits\", 1)\n return f\"Visit count: {value}\"\n\nDeploying the sample to Cloud Run functions\n-------------------------------------------\n\nDeploy the function using the Google Cloud CLI: \n\n### Go\n\n```\ngcloud run deploy visit-count \\\n --region=REGION \\\n --source=. \\\n --base-image=BASE_IMAGE \\\n --function=VisitCount \\\n --vpc-connector=projects/PROJECT_ID/locations/REGION/connectors/CONNECTOR_NAME \\\n --set-env-vars=REDISHOST=REDIS_IP,REDISPORT=REDIS_PORT\n```\n\n### Node.js\n\n```\ngcloud run deploy visit-count \\\n --region=REGION \\\n --source=. \\\n --base-image=BASE_IMAGE \\\n --entry-point=visitCount \\\n --vpc-connector=projects/PROJECT_ID/locations/REGION/connectors/CONNECTOR_NAME \\\n --set-env-vars=REDISHOST=REDIS_IP,REDISPORT=REDIS_PORT\n```\n\n### Python\n\n```\ngcloud run deploy visit-count \\\n --region=REGION \\\n --source=. \\\n --base-image=BASE_IMAGE \\\n --function=visit_count \\\n --vpc-connector=projects/PROJECT_ID/locations/REGION/connectors/CONNECTOR_NAME \\\n --set-env-vars=REDISHOST=REDIS_IP,REDISPORT=REDIS_PORT\n```\n\nReplace:\n\n- \u003cvar translate=\"no\"\u003eREGION\u003c/var\u003e with the region where you want to deploy the function.\n- \u003cvar translate=\"no\"\u003eBASE_IMAGE\u003c/var\u003e with the base image for the function, for example, `go116`, `nodejs16`, or `python310`. For more information, see [Supported language runtimes and base images](/run/docs/configuring/services/runtime-base-images) for more information.\n- \u003cvar translate=\"no\"\u003ePROJECT_ID\u003c/var\u003e with your Google Cloud project's ID.\n- \u003cvar translate=\"no\"\u003eCONNECTOR_NAME\u003c/var\u003e with the name of your connector.\n- \u003cvar translate=\"no\"\u003eREDIS_IP\u003c/var\u003e and \u003cvar translate=\"no\"\u003eREDIS_PORT\u003c/var\u003e with the IP address and port number of your Redis instance.\n\nAfter the function deployment finishes, retrieve your function's URL: \n\n```bash\ngcloud run services describe visit-count \\\n--region=REGION \\\n```\n\nYou can see the counter increase every time you trigger the function by sending\na `GET` request to its URL."]]