// Command redis is a basic app that connects to a managed Redis instance.packagemainimport("fmt""log""net/http""os""github.com/gomodule/redigo/redis")varredisPool*redis.PoolfuncincrementHandler(whttp.ResponseWriter,r*http.Request){conn:=redisPool.Get()deferconn.Close()counter,err:=redis.Int(conn.Do("INCR","visits"))iferr!=nil{http.Error(w,"Error incrementing visitor counter",http.StatusInternalServerError)return}fmt.Fprintf(w,"Visitor number: %d",counter)}funcmain(){redisHost:=os.Getenv("REDISHOST")redisPort:=os.Getenv("REDISPORT")redisAddr:=fmt.Sprintf("%s:%s",redisHost,redisPort)constmaxConnections=10redisPool=&redis.Pool{MaxIdle:maxConnections,Dial:func()(redis.Conn,error){returnredis.Dial("tcp",redisAddr)},}http.HandleFunc("/",incrementHandler)port:=os.Getenv("PORT")ifport==""{port="8080"}log.Printf("Listening on port %s",port)iferr:=http.ListenAndServe(":"+port,nil);err!=nil{log.Fatal(err)}}
{"name":"memorystore-redis","description":"An example of using Memorystore(Redis) with Node.js","version":"0.0.1","private":true,"license":"Apache Version 2.0","author":"Google Inc.","engines":{"node":">=16.0.0"},"dependencies":{"redis":"^4.0.0"}}
'use strict';consthttp=require('http');constredis=require('redis');constREDISHOST=process.env.REDISHOST||'localhost';constREDISPORT=process.env.REDISPORT||6379;constclient=redis.createClient(REDISPORT,REDISHOST);client.on('error',err=>console.error('ERR:REDIS:',err));// create a serverhttp.createServer((req,res)=>{// increment the visit counterclient.incr('visits',(err,reply)=>{if(err){console.log(err);res.status(500).send(err.message);return;}res.writeHead(200,{'Content-Type':'text/plain'});res.end(`Visitor number: ${reply}\n`);});}).listen(8080);
Python
Esta aplicación usa Flask para la entrega web y el paquete redis-py a fin de comunicarse con la instancia de Redis.
importloggingimportosfromflaskimportFlaskimportredisapp=Flask(__name__)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)@app.route("/")defindex():value=redis_client.incr("counter",1)returnf"Visitor number: {value}"@app.errorhandler(500)defserver_error(e):logging.exception("An error occurred during a request.")return(""" An internal error occurred: <pre>{}</pre> See logs for full stacktrace. """.format(e),500,)if__name__=="__main__":# This is used when running locally. Gunicorn is used to run the# application on Google App Engine and Cloud Run.# See entrypoint in app.yaml or Dockerfile.app.run(host="127.0.0.1",port=8080,debug=True)
Implementa la aplicación en Cloud Run
Para implementar la aplicación, haz lo siguiente:
Copia el archivo Dockerfile en el directorio fuente:
cp cloud_run_deployment/Dockerfile .
Ejecuta el siguiente comando para compilar una imagen de contenedor con Cloud Build:
Ejecuta el siguiente comando para implementar el contenedor en Cloud Run:
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
Donde:
PROJECT_ID es el ID de tu proyecto Google Cloud .
REGION es la región en la que se encuentra tu instancia de Redis.
NETWORK es el nombre de la red de VPC autorizada a la que está conectada tu instancia de Redis.
SUBNET es el nombre de la subred. La subred debe ser /26 o mayor. La salida de VPC directa es compatible con los rangos IPv4 RFC 1918, RFC 6598 y clase E.
REDIS_IP y REDIS_PORT son la dirección IP y el número de puerto de tu instancia de Redis.
Una vez que la implementación se complete de forma correcta, la línea de comandos mostrará la URL de tu servicio de Cloud Run. Visita esta URL en un navegador web (o usa una herramienta como curl) y observa que el recuento en tu instancia de Redis aumenta cada vez que se visita el servicio.
[[["Fácil de comprender","easyToUnderstand","thumb-up"],["Resolvió mi problema","solvedMyProblem","thumb-up"],["Otro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Información o código de muestra incorrectos","incorrectInformationOrSampleCode","thumb-down"],["Faltan la información o los ejemplos que necesito","missingTheInformationSamplesINeed","thumb-down"],["Problema de traducción","translationIssue","thumb-down"],["Otro","otherDown","thumb-down"]],["Última actualización: 2025-09-05 (UTC)"],[],[],null,["# Connecting to a Redis instance from a Cloud Run service\n\nYou can connect to a Redis instance from Cloud Run by using\n[Direct VPC egress](/run/docs/configuring/vpc-direct-vpc).\n| **Important**: We recommend that you use Direct VPC\n| egress because it offers lower latency, higher throughput, and lower\n| costs by eliminating the need for managed connector instances.\n|\n| You can also\n| connect to a Redis instance from Cloud Run\n| by using [Serverless VPC Access](/vpc/docs/configure-serverless-vpc-access). To use a Serverless VPC Access connector, see [VPC with connectors](/run/docs/configuring/vpc-connectors).\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\nPrepare VPC network egress for configuration\n--------------------------------------------\n\nTo connect to your Redis instance, your Cloud Run service\nmust have access to the Redis instance's authorized VPC network.\n\nTo find the name of this network, run the following command: \n\n```sh\n gcloud redis instances describe INSTANCE_ID --region REGION --format \"value(authorizedNetwork)\"\n```\n\nMake a note of the network name.\n\nSample application\n------------------\n\nThis sample HTTP server application establishes a connection to a Redis\ninstance from a Cloud Run service.\n\nClone the repository for your chosen 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/memorystore/redis\n\n### Node.js\n\n git clone https://github.com/GoogleCloudPlatform/nodejs-docs-samples\n cd nodejs-docs-samples/memorystore/redis\n\n### Python\n\n git clone https://github.com/GoogleCloudPlatform/python-docs-samples\n cd python-docs-samples/memorystore/redis\n\nThis sample application increments a Redis counter every time the `/` endpoint\nis accessed. \n\n### Go\n\nThis application uses the\n[`github.com/gomodule/redigo/redis`](https://godoc.org/github.com/gomodule/redigo/redis)\nclient. Install it by running the following command: \n\n go get github.com/gomodule/redigo/redis\n\n\n // Command redis is a basic app that connects to a managed Redis instance.\n package main\n\n import (\n \t\"fmt\"\n \t\"log\"\n \t\"net/http\"\n \t\"os\"\n\n \t\"github.com/gomodule/redigo/redis\"\n )\n\n var redisPool *redis.Pool\n\n func incrementHandler(w http.ResponseWriter, r *http.Request) {\n \tconn := redisPool.Get()\n \tdefer conn.Close()\n\n \tcounter, err := redis.Int(conn.Do(\"INCR\", \"visits\"))\n \tif err != nil {\n \t\thttp.Error(w, \"Error incrementing visitor counter\", http.StatusInternalServerError)\n \t\treturn\n \t}\n \tfmt.Fprintf(w, \"Visitor number: %d\", counter)\n }\n\n func main() {\n \tredisHost := os.Getenv(\"REDISHOST\")\n \tredisPort := os.Getenv(\"REDISPORT\")\n \tredisAddr := fmt.Sprintf(\"%s:%s\", redisHost, redisPort)\n\n \tconst maxConnections = 10\n \tredisPool = &redis.Pool{\n \t\tMaxIdle: maxConnections,\n \t\tDial: func() (redis.Conn, error) { return redis.Dial(\"tcp\", redisAddr) },\n \t}\n\n \thttp.HandleFunc(\"/\", incrementHandler)\n\n \tport := os.Getenv(\"PORT\")\n \tif port == \"\" {\n \t\tport = \"8080\"\n \t}\n \tlog.Printf(\"Listening on port %s\", port)\n \tif err := http.ListenAndServe(\":\"+port, nil); err != nil {\n \t\tlog.Fatal(err)\n \t}\n }\n\n### Node.js\n\nThis application uses the [`redis`](https://www.npmjs.com/package/redis)\nmodule. \n\n {\n \"name\": \"memorystore-redis\",\n \"description\": \"An example of using Memorystore(Redis) with Node.js\",\n \"version\": \"0.0.1\",\n \"private\": true,\n \"license\": \"Apache Version 2.0\",\n \"author\": \"Google Inc.\",\n \"engines\": {\n \"node\": \"\u003e=16.0.0\"\n },\n \"dependencies\": {\n \"redis\": \"^4.0.0\"\n }\n }\n\n 'use strict';\n const http = require('http');\n const redis = require('redis');\n\n const REDISHOST = process.env.REDISHOST || 'localhost';\n const REDISPORT = process.env.REDISPORT || 6379;\n\n const client = redis.createClient(REDISPORT, REDISHOST);\n client.on('error', err =\u003e console.error('ERR:REDIS:', err));\n\n // create a server\n http\n .createServer((req, res) =\u003e {\n // increment the visit counter\n client.incr('visits', (err, reply) =\u003e {\n if (err) {\n console.log(err);\n res.status(500).send(err.message);\n return;\n }\n res.writeHead(200, {'Content-Type': 'text/plain'});\n res.end(`Visitor number: ${reply}\\n`);\n });\n })\n .listen(8080);\n\n### Python\n\nThis application uses [Flask](https://flask.palletsprojects.com/en/1.1.x/)\nfor web serving and the [`redis-py`](https://redis-py.readthedocs.io/en/latest/)\npackage to communicate with the Redis instance. \n\n Flask==3.0.3\n gunicorn==23.0.0\n redis==6.0.0\n Werkzeug==3.0.3\n\n import logging\n import os\n\n from flask import Flask\n import redis\n\n app = Flask(__name__)\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 @app.route(\"/\")\n def index():\n value = redis_client.incr(\"counter\", 1)\n return f\"Visitor number: {value}\"\n\n\n @app.errorhandler(500)\n def server_error(e):\n logging.exception(\"An error occurred during a request.\")\n return (\n \"\"\"\n An internal error occurred: \u003cpre\u003e{}\u003c/pre\u003e\n See logs for full stacktrace.\n \"\"\".format(\n e\n ),\n 500,\n )\n\n\n if __name__ == \"__main__\":\n # This is used when running locally. Gunicorn is used to run the\n # application on Google App Engine and Cloud Run.\n # See entrypoint in app.yaml or Dockerfile.\n app.run(host=\"127.0.0.1\", port=8080, debug=True)\n\nDeploying the application to Cloud Run\n--------------------------------------\n\nTo deploy the application:\n\n1. Copy the `Dockerfile` into the source directory:\n\n cp cloud_run_deployment/Dockerfile .\n\n2. Build a container image using Cloud Build by running the following\n command:\n\n ```\n gcloud builds submit --tag gcr.io/PROJECT_ID/visit-count\n ```\n3. Deploy the container to Cloud Run by running the following\n command:\n\n ```\n gcloud run deploy \\\n --image gcr.io/PROJECT_ID/visit-count \\\n --allow-unauthenticated \\\n --region REGION \\\n --network NETWORK \\\n --subnet SUBNET \\\n --set-env-vars REDISHOST=REDIS_IP,REDISPORT=REDIS_PORT\n ```\n\n where:\n - \u003cvar translate=\"no\"\u003ePROJECT_ID\u003c/var\u003e is your Google Cloud project's ID.\n - \u003cvar translate=\"no\"\u003eREGION\u003c/var\u003e is the region where your Redis instance is located.\n - \u003cvar translate=\"no\"\u003eNETWORK\u003c/var\u003e is the name of the authorized VPC network that your Redis instance is attached to.\n - \u003cvar translate=\"no\"\u003eSUBNET\u003c/var\u003e is the name of your subnet. The subnet must be `/26` or larger. Direct VPC egress supports IPv4 ranges [RFC 1918](https://tools.ietf.org/html/rfc1918#section-3), [RFC 6598](https://tools.ietf.org/html/rfc6598#section-7), and Class E.\n - \u003cvar translate=\"no\"\u003eREDIS_IP\u003c/var\u003e and \u003cvar translate=\"no\"\u003eREDIS_PORT\u003c/var\u003e are the IP address and port number of your Redis instance.\n\nAfter the deployment successfully completes, the command line displays your\nCloud Run service's URL. Visit this URL in a web browser\n(or use a tool like `curl`) and see the count on your Redis instance increase\neach time the service is visited."]]