Go 1.11 はサポートが終了しており、2026 年 1 月 31 日に
非推奨になります。非推奨になると、過去に組織のポリシーを使用して以前のランタイムのデプロイを再度有効にしていた場合でも、Go 1.11 アプリケーションをデプロイできなくなります。既存の Go 1.11 アプリケーションは、
非推奨日以降も引き続き実行され、トラフィックを受信します。
サポートされている最新バージョンの Go に移行することをおすすめします。
Memorystore を使用したデータのキャッシュ
コレクションでコンテンツを整理
必要に応じて、コンテンツの保存と分類を行います。
高パフォーマンスでスケーラブルなウェブ アプリケーションでは多くの場合、一部のタスクの処理に、堅牢で永続的なストレージに優先して(あるいはその代わりに)分散型のインメモリ データ キャッシュを使用します。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 インスタンスを作成し、アプリが Redis インスタンスとの通信に使用するサーバーレス VPC アクセスを作成する必要があります。この 2 つの独立したエンティティを作成する順序は厳密ではなく、どのような順序でも設定が可能です。このガイドでは、まずサーバーレス VPC アクセスを設定する手順について説明します。
Redis のクライアント ライブラリをインストールし、Redis コマンドを使用してデータをキャッシュに保存します。
Memorystore for Redis は Redis 用クライアント ライブラリと互換性があります。このガイドでは、アプリから Redis コマンドを送信する際の redigo クライアント ライブラリの使用について説明します。
更新をテストする。
App Engine にアプリをデプロイする。
Memorystore for Redis のセットアップ
Memorystore for Redis をセットアップするには:
App Engine を VPC ネットワークに接続します。アプリは VPC コネクタを介してのみ Memorystore と通信できます。
コネクタを使用するようにアプリを構成するの説明に沿って、app.yaml
ファイルに VPC 接続情報を追加します。
作成する 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 クライアント ライブラリは、2 つの環境変数を使用して Redis データベースの URL をアセンブルします。
- 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 のドキュメントにある手順を行ってください。現在、Redis を Windows 上でローカルに実行することはできません。
アプリのデプロイ
アプリをローカル開発用サーバーでエラーなしで実行できれば、次の手順を行います。
App Engine でアプリをテストします。
アプリがエラーなしで実行されている場合、トラフィック分割を使用して、更新したアプリのトラフィックを徐々に増やします。更新したアプリへのトラフィックを増やす前に、データベースの問題が発生していないか細かくモニタリングして確認してください。
特に記載のない限り、このページのコンテンツはクリエイティブ・コモンズの表示 4.0 ライセンスにより使用許諾されます。コードサンプルは Apache 2.0 ライセンスにより使用許諾されます。詳しくは、Google Developers サイトのポリシーをご覧ください。Java は Oracle および関連会社の登録商標です。
最終更新日 2025-09-04 UTC。
[[["わかりやすい","easyToUnderstand","thumb-up"],["問題の解決に役立った","solvedMyProblem","thumb-up"],["その他","otherUp","thumb-up"]],[["わかりにくい","hardToUnderstand","thumb-down"],["情報またはサンプルコードが不正確","incorrectInformationOrSampleCode","thumb-down"],["必要な情報 / サンプルがない","missingTheInformationSamplesINeed","thumb-down"],["翻訳に関する問題","translationIssue","thumb-down"],["その他","otherDown","thumb-down"]],["最終更新日 2025-09-04 UTC。"],[[["\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."]]