Go 1.11 已达到支持终止期限,将于 2026 年 1 月 31 日
弃用。弃用后,您将无法部署 Go 1.11 应用,即使您的组织之前曾使用组织政策重新启用旧版运行时的部署也是如此。现有的 Go 1.11 应用在
弃用日期之后将继续运行并接收流量。我们建议您
迁移到最新支持的 Go 版本。
使用 Memorystore 缓存数据
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
在执行某些任务时,高性能的可扩缩 Web 应用通常会先使用内存中的分布式数据缓存,当其不可用时才会使用可靠的永久性存储空间。我们建议您使用 Memorystore for Redis 作为缓存服务。请注意,
Memorystore for Redis 不提供免费层级。如需了解详情,请参阅
Memorystore 价格。
开始之前,请确保您的应用不会超出 Memorystore for Redis 配额。
何时使用内存缓存
会话数据、用户偏好设置以及网页查询返回的其他数据都非常适合进行缓存。通常,如果频繁运行的查询所返回的结果集不需要立即显示在您的应用中,便可以缓存结果。如此,后续请求可以检查缓存,只有当结果缺失或过期时才会查询数据库。
如果您将某个值仅存储在 Memorystore 中,而没有将其备份到永久性存储空间,请确保在该值过期及从缓存中移除时,您的应用仍可正常运作。例如,如果用户会话数据的突然缺失会导致会话出现故障,则应考虑除了在 Memorystore 中存储该数据之外,还应将其存储在数据库中。
了解 Memorystore 权限
与 Google Cloud 服务之间进行的每一次交互操作都需要经过授权。例如,如需与 Memorystore 托管的 Redis 数据库进行交互,您的应用需要提供有权访问 Memorystore 的账号的相应凭据。
默认情况下,您的应用会提供 App Engine 默认服务账号的凭据,该账号有权访问与您应用同属一个项目中的数据库。
如果满足以下任何条件,则您需要使用明确提供凭据的备用身份验证技术:
如需了解备用身份验证技术,请参阅为服务器到服务器的生产应用设置身份验证。
使用 Memorystore 概览
如需在您的应用中使用 Memorystore,请执行以下操作:
设置 Memorystore for Redis,此操作需要您在 Memorystore 上创建 Redis 实例并创建无服务器 VPC 访问通道,以供您的应用与 Redis 实例通信。 创建这两个独立实体的顺序并不严格,可以按任意顺序设置。本指南中的说明首先显示如何设置无服务器 VPC 访问通道。
安装适用于 Redis 的客户端库并使用 Redis 命令缓存数据。
Memorystore for Redis 与适用于 Redis 的任何客户端库都兼容。本指南介绍如何使用 redigo 客户端库从您的应用发送 Redis 命令。
测试您的更新。
将应用部署到 App Engine。
设置 Memorystore for Redis
如需设置 Memorystore for Redis,请执行以下操作:
将 App Engine 连接到 VPC 网络。您的应用只能通过 VPC 连接器与 Memorystore 通信。
请务必按照将应用配置为使用连接器中的说明,将 VPC 连接信息添加到 app.yaml
文件中。
记下您创建的 Redis 实例的 IP 地址和端口号。您在自己的代码中创建 Redis 客户端时,将会用到这些信息。
在 Memorystore 中创建 Redis 实例。
当系统提示您为 Redis 实例选择地区时,请选择您的 App Engine 应用所在的地区。
安装依赖项
如需使应用在 App Engine 中运行时能够使用 redigo 客户端库,请将该客户端库添加到应用的依赖项中。例如,如果您使用
go.mod
文件声明依赖项,请将下面一行代码添加到
go.mod
文件中:
module github.com/GoogleCloudPlatform/golang-samples/tree/master/memorystore/redis
详细了解如何为 Go 应用指定依赖项。
创建 Redis 客户端
如需与 Redis 数据库进行交互,您的代码需要创建 Redis 客户端才能管理与 Redis 数据库的连接。以下部分介绍如何使用 redigo 客户端库创建 Redis 客户端。
指定环境变量
redigo 客户端库使用两个环境变量为您的 Redis 数据库组建网址:
- 用于标识您在 Memorystore 中创建的 Redis 数据库的 IP 地址的变量。
- 用于标识您在 Memorystore 中创建的 Redis 数据库的端口号的变量。
我们建议您在应用的 app.yaml
文件中定义这些变量,而不是直接在您的代码中定义这些变量。这样可以更轻松地在不同的环境(例如本地环境和 App Engine)中运行您的应用。
例如,请将下面几行内容添加到
app.yaml
文件中:
env_variables:
REDISHOST: '10.112.12.112'
REDISPORT: '6379'
导入 redigo 并创建客户端
定义
REDISHOST
和
REDISPORT
环境变量后,请使用下面若干行代码导入 redigo 库,接着创建连接池,然后从池中检索 Redis 客户端:
使用 Redis 命令在缓存中存储和检索数据
虽然 Memorystore Redis 数据库支持大多数 Redis 命令,但您只需使用几个命令即可在缓存中存储和检索数据。下表建议了一些可用于缓存数据的 Redis 命令。如需了解如何从您的应用调用这些命令,请参阅客户端库的文档。
测试更新
当您在本地测试应用时,请考虑运行 Redis 的本地实例以避免与生产数据交互(Memorystore 不提供模拟器)。如需在本地安装并运行 Redis,请按照 Redis 文档中的说明进行操作。请注意,目前无法在 Windows 上本地运行 Redis。
部署应用
一旦您的应用能够在本地开发服务器上无错误地正常运行,请执行以下操作:
在 App Engine 上测试应用。
如果应用无错误地正常运行,请使用流量拆分功能为更新后的应用缓慢增加流量。请先仔细监控应用是否存在任何数据库问题,然后再将更多流量路由到更新后的应用。
如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2025-09-04。
[[["易于理解","easyToUnderstand","thumb-up"],["解决了我的问题","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["很难理解","hardToUnderstand","thumb-down"],["信息或示例代码不正确","incorrectInformationOrSampleCode","thumb-down"],["没有我需要的信息/示例","missingTheInformationSamplesINeed","thumb-down"],["翻译问题","translationIssue","thumb-down"],["其他","otherDown","thumb-down"]],["最后更新时间 (UTC):2025-09-04。"],[[["\u003cp\u003eMemorystore for Redis is recommended for high-performance, scalable web applications that require an in-memory data cache, but it does not have a free tier, so see pricing details.\u003c/p\u003e\n"],["\u003cp\u003eCaching is beneficial for data like session information and user preferences, especially when query results don't need to be immediately reflected in the application, allowing for reduced database queries.\u003c/p\u003e\n"],["\u003cp\u003eApplications must use proper credentials to interact with Memorystore, typically the App Engine default service account unless specific conditions are met, such as different project locations or modified service account roles.\u003c/p\u003e\n"],["\u003cp\u003eTo use Memorystore, you must set up a Redis instance and Serverless VPC Access, install a Redis client library like redigo, configure environment variables for Redis IP and port, and then deploy the app to App Engine.\u003c/p\u003e\n"],["\u003cp\u003eRedis commands like SET, GET, INCR, and DEL are essential for managing cached data, including creating, retrieving, incrementing, and deleting entries, with concurrent interactions supported through Redis transactions.\u003c/p\u003e\n"]]],[],null,["# Caching data with Memorystore\n\nHigh performance scalable web applications often use a distributed in-memory data cache in front of or in place of robust persistent storage for some tasks. We recommend using Memorystore for Redis as your caching service. Note that **Memorystore for Redis does not provide a free tier** . See [Memorystore Pricing](/memorystore/pricing) for details.\n\n\u003cbr /\u003e\n\nBefore getting started, make sure your app will stay within the\n[Memorystore for Redis quotas](/memorystore/docs/redis/quotas).\n\nWhen to use a memory cache\n--------------------------\n\nSession data, user preferences, and other data returned by queries for web pages\nare good candidates for caching. In general, if a frequently run query returns\na set of results that do not need to appear in your app immediately, you can\ncache the results. Subsequent requests can check the cache and only query the\ndatabase if the results are absent or have expired.\n\nIf you store a value only in Memorystore without backing it up in\npersistent storage, be sure that your application behaves acceptably if the\nvalue expires and is removed from the cache. For example, if the sudden absence\nof a user's session data would cause the session to malfunction, that data\nshould probably be stored in the database in addition to Memorystore.\n\n\nUnderstanding Memorystore permissions\n-------------------------------------\n\nEvery interaction with a Google Cloud service needs to be authorized. For\nexample, to interact with a Redis database hosted by Memorystore, your app\nneeds to supply the credentials of an account that is authorized to access\nMemorystore.\n\nBy default your app supplies the credentials of the App Engine\ndefault [service account](/iam/docs/service-accounts), which is authorized to\naccess databases in the same project as your app.\n\nIf any of the following conditions are true, you need to use an alternative\nauthentication technique that explicitly provides credentials:\n\n- Your app and the Memorystore database are in different\n Google Cloud projects.\n\n- You have changed the roles assigned to the default App Engine\n service account.\n\nFor information about alternative authentication techniques, see\n[Setting up Authentication for Server to Server Production\nApplications](/docs/authentication/production#auth-cloud-implicit-python).\n\nOverview of using Memorystore\n-----------------------------\n\nTo use Memorystore in your app:\n\n\n1. [Set up Memorystore for Redis](#setup_redis_db), which requires you\n to create a Redis instance on Memorystore and create a\n Serverless VPC Access that your app uses to communicate with the\n Redis instance. The order of creating these two independent entities is not\n strict and can be set up in any order. The instructions in this guide show\n setting up Serverless VPC Access first.\n\n2. Install a client library for Redis and use Redis commands to cache data.\n\n Memorystore for Redis is compatible with [any client library for\n Redis](https://redis.io/clients).\n\n This guide describes using the\n [redigo](https://github.com/gomodule/redigo)\n client library to send Redis commands from your app.\n3. [Test your updates](#testing).\n\n4. [Deploy your app to App Engine](#deploying).\n\nSetting up Memorystore for Redis\n--------------------------------\n\nTo set up Memorystore for Redis:\n\n1. [Connect your App Engine to a VPC\n network](/appengine/docs/legacy/standard/go111/connecting-vpc). Your app\n can only communicate with Memorystore through a VPC connector.\n\n Be sure to add the VPC connection information to your `app.yaml` file as\n described in [Configuring your app use the\n connector](/appengine/docs/standard/connecting-vpc#configuring).\n2. Note the IP address and port number of the Redis instance you create.\n You will use this information when you [create a Redis client](#redis_client)\n in your code.\n\n3. [Create a Redis instance](/memorystore/docs/redis/creating-managing-instances#creating_a_redis_instance_on_a_vpc_network)\n in Memorystore.\n\n When prompted to select a region for your Redis instance, select the\n [same region\n in which your App Engine app is located](/appengine/docs/legacy/standard/go111/locations).\n\nInstalling dependencies\n-----------------------\n\nTo make the redigo client library available to your app when it runs in App Engine, add the library to your app's dependencies. For example, if you use a `go.mod` file to declare dependencies, add the following line to your `go.mod` file:\n\n\u003cbr /\u003e\n\n module github.com/GoogleCloudPlatform/golang-samples/tree/master/memorystore/redis\n\nLearn more about [specifying dependencies](/appengine/docs/legacy/standard/go111/specifying-dependencies)\nfor your Go app.\n\nCreating a Redis client\n-----------------------\n\nTo interact with a Redis database, your code needs to create a Redis client to\nmanage the connection to your Redis database. The following sections describe\ncreating a Redis client using the\n\nredigo\n\nclient library.\n\n### Specifying environment variables\n\nThe\n\nredigo\n\nclient library uses two environment variables\nto assemble the URL for your Redis database:\n\n- A variable to identify the IP address of the Redis database you [created in Memorystore](#setup_redis_db).\n- A variable to identify the port number of the Redis database you created in Memorystore.\n\nWe recommend you define these variables in your app's `app.yaml` file instead of\ndefining them directly in your code. This makes it easier to run your app in\ndifferent environments, such as a local environment and App Engine.\nFor example, add the following lines to your `app.yaml` file:\n\n\u003cbr /\u003e\n\n env_variables:\n REDISHOST: '10.112.12.112'\n REDISPORT: '6379'\n\n### Importing\nredigo\nand creating the client\n\nAfter you define the `REDISHOST` and `REDISPORT` environment variables, use the following lines to import the redigo library, create a connection pool, and then retrieve a Redis client from the pool:\n\n\u003cbr /\u003e\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\nUsing Redis commands to store and retrieve data in the cache\n------------------------------------------------------------\n\nWhile the Memorystore Redis database [supports most\nRedis commands](/memorystore/docs/redis/product-constraints), you only need to use a few commands to\nstore and retrieve data from the cache. The following table suggests Redis\ncommands you can use to cache data. To see how to call these commands from your\napp, view your client library's documentation.\n\nTesting your updates\n--------------------\n\nWhen you test your app locally, consider running a local instance of\nRedis to avoid interacting with production data (Memorystore doesn't\nprovide an emulator). To install and run Redis locally, follow the directions in the\n[Redis documentation](http://redis.io/topics/quickstart).\nNote that it currently isn't possible to run Redis locally on Windows.\n\nDeploying your app\n------------------\n\nOnce your app is running in the local development server without errors:\n\n1.\n [Test the app on\n App Engine](/appengine/docs/legacy/standard/go111/testing-and-deploying-your-app#testing-on-app-engine).\n\n2. If the app runs without errors, [use traffic\n splitting](/appengine/docs/legacy/standard/go111/splitting-traffic) to slowly\n ramp up traffic for your updated app. Monitor the app closely for any\n database issues before routing more traffic to the updated app."]]