Python 2.7 はサポートが終了しており、2026 年 1 月 31 日に
非推奨になります。非推奨になると、過去に組織のポリシーを使用して以前のランタイムのデプロイを再度有効にしていた場合でも、Python 2.7 アプリケーションをデプロイできなくなります。既存の Python 2.7 アプリケーションは、
非推奨日以降も引き続き実行され、トラフィックを受信します。
サポートされている最新バージョンの Python に移行することをおすすめします。
Memcache の使用方法
コレクションでコンテンツを整理
必要に応じて、コンテンツの保存と分類を行います。
このページでは、 Google Cloud コンソールを使用してアプリケーションの Memcache サービスを構成、モニタリングする方法について説明します。また、App Engine の Memcache Python API を使用して、キャッシュに保存された値の設定や取得をする方法、同じ Memcache キーに対する同時書き込みリクエストをコンペア アンド セット機能を使用して処理する方法についても説明します。Memcache については、Memcache の概要をご覧ください。
Memcache を構成する
- Google Cloud コンソールの [Memcache] ページに移動します。
[Memcache] ページに移動
使用する Memcache サービスレベルを選択します。
- 共有(デフォルト) - 無料で、ベスト エフォート ベースでキャッシュ容量を提供します。
- 専用 - キャッシュ サイズ使用量の GB 時間で請求され、アプリケーションに対して固定キャッシュ容量が独占的に割り当てられます。
使用可能なサービスクラスについては、Memcache の概要をご覧ください。
値のキャッシュへの保存と取得
値をキャッシュに保存する
キーの値がまだ存在しない場合にのみ、add()
を使用して追加します。有効期限を設定することもできます。
memcache.add(key="[KEY]", value="[VALUE]", time=[EXPIRATION_TIME])
たとえば、値 raining
をキー weather_USA_98105
に追加し、値の書き込み時点から 1 時間の有効期限を設定します。
memcache.add(key="weather_USA_98105", value="raining", time=3600)
add()
や値の設定に使用するその他のメソッドの詳細については、Memcache Python API のドキュメントをご覧ください。
値をキャッシュに保存するその他の例については、Memcache の例をご覧ください。
キャッシュに保存された値を検索する
単一のキーの値を検索するには、get()
を使用します。
memcache.get(key="[KEY]")
たとえば、キー weather_USA_98105
の値を取得するには、次のようにします。
memcache.get(key="weather_USA_98105")
get()
や値の検索に使用するその他のメソッドの詳細については、Memcache Python API のドキュメントをご覧ください。
Google Cloud コンソールで Memcache をモニタリングする
- Google Cloud コンソールの [Memcache] ページに移動します。
[Memcache] ページに移動
- 次のレポートを調べます。
- Memcache サービスレベル: アプリケーションが共有または専用のどちらのサービスレベルを使用しているかを示します。プロジェクトのオーナーの場合は、2 つのサービスレベルを切り替えることができます。詳細については、サービスレベルをご覧ください。
- ヒット率: キャッシュから提供されたデータ リクエストのパーセンテージと、そのデータ リクエストの実数が表示されます。
- キャッシュ内のアイテム。
- 最も古いアイテムの経過期間: 最も古いキャッシュされたアイテムの経過期間。アイテムの経過時間は使用(読み取りまたは書き込み)されるたびにリセットされます。
- 総キャッシュ サイズ。
次の操作を行うことができます。
- 新しいキー: 新しいキーをキャッシュに追加します。
- キーを検索: 既存のキーを取得します。
- キャッシュをフラッシュ: キャッシュからすべてのキーと値のペアを削除します。
(専用 Memcache のみ)ホットキーのリストを参照します。
- 「ホットキー」は Memcache 内の 100 クエリ/秒(QPS)以上を受信するキーです。
- このリストには QPS の高い順で並べ替えられた最大 100 個のホットキーが含まれます。
同時書き込みの処理
複数のリクエストによる同じ Memcache キーへの書き込みをコンペア アンド セット機能を使用して処理するには:
- Memcache
Client
オブジェクトをインスタンス化します。
- 再試行ループを使用します(再試行回数を制限して指数バックオフを使用することをおすすめします)。
- 再試行ループ内で、
gets()
または get_multi()
を使用して、for_cas
パラメータを True
に設定してキーを取得します。
- 再試行ループ内で、
cas()
または cas_multi()
を使用してキーの値を更新します。
次のスニペットは、コンペア アンド セット機能を使用する方法の 1 つを示したものです。
def bump_counter(key):
client = memcache.Client()
while True: # Retry loop
counter = client.gets(key)
if counter is None: raise KeyError('Uninitialized counter')
if client.cas(key, counter+1):
break
このコードでは、必ず再試行ループを使用する必要があります。再試行ループを使用しないと競合状態を避けられず、検出しか行われません。Memcache サービスは、ここに示すパターンで使用された場合(すなわち、gets()
と cas()
を使用する場合)に動作保証します。2 つ以上の異なるクライアント インスタンスが競合状態に陥っている場合は、cas()
オペレーションを実行する 1 番目のみが成功し(戻り値 True
)、2 番目以降は失敗します(戻り値 False
)。
このサンプルコードにさらに改良を加えるとすれば、同じカウンタで多数の競合が生じるような最悪のシナリオで無限ループを回避できるように、再試行回数の上限を設定することが考えられます。このような競合は、カウンタの更新を試行するリクエストの数が Memcache サービスがリアルタイムで処理できる数を超えた場合などに発生する可能性があります。
コンペア アンド セットの詳細については、Memcache の概要をご覧ください。
次のステップ
特に記載のない限り、このページのコンテンツはクリエイティブ・コモンズの表示 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\u003eThis guide explains how to configure and monitor the memcache service through the Google Cloud console, including switching between Shared and Dedicated service levels.\u003c/p\u003e\n"],["\u003cp\u003eYou can cache and retrieve values using the memcache Python API methods like \u003ccode\u003eadd()\u003c/code\u003e for caching and \u003ccode\u003eget()\u003c/code\u003e for retrieval, with the option to set expiration times.\u003c/p\u003e\n"],["\u003cp\u003eThe memcache monitoring in the Google Cloud console offers insights into the service level, hit ratio, cache items, item age, total size, and dedicated memcache allows to see "Hot keys".\u003c/p\u003e\n"],["\u003cp\u003eConcurrent write requests to the same memcache key can be handled using the compare-and-set (CAS) feature, implemented with a retry loop using \u003ccode\u003egets()\u003c/code\u003e and \u003ccode\u003ecas()\u003c/code\u003e.\u003c/p\u003e\n"],["\u003cp\u003eThis API is supported for first-generation runtimes and can be used when upgrading to the corresponding second-generation runtimes.\u003c/p\u003e\n"]]],[],null,["# Using Memcache\n\nThis page describes how to configure and monitor the memcache service for your\napplication using the Google Cloud console. It also describes how to use the App Engine memcache Python\nAPI to set and retrieve cached values and use the compare-and-set feature to\nhandle concurrent write requests to the same memcache\nkey. To learn more about memcache,\nread the [Memcache Overview](/appengine/docs/legacy/standard/python/memcache).\n| This API is supported for first-generation runtimes and can be used when [upgrading to corresponding second-generation runtimes](/appengine/docs/standard/\n| python3\n|\n| /services/access). If you are updating to the App Engine Python 3 runtime, refer to the [migration guide](/appengine/migration-center/standard/migrate-to-second-gen/python-differences) to learn about your migration options for legacy bundled services.\n\nConfiguring memcache\n--------------------\n\n1. Go to the Memcache page in the Google Cloud console. \n [Go to the Memcache page](https://console.cloud.google.com/appengine/memcache)\n2. Select the memcache service level you want to use:\n\n - **Shared** (default) - free and provides cache capacity on a best-effort basis.\n - **Dedicated** - billed by the GB-hour of cache size and provides a fixed cache capacity assigned exclusively to your application.\n\n Learn more about available service classes in [Memcache Overview](#service_levels).\n\nCaching and retrieving values\n-----------------------------\n\n### Caching a value\n\nUse `add()` to add a key's value if and only if it doesn't already exist, with\nan optional expiration time: \n\n memcache.add(key=\"[KEY]\", value=\"[VALUE]\", time=[EXPIRATION_TIME])\n\nFor example, to add the value `raining` to the key `weather_USA_98105` with an\nexpiration time of one hour from when the value is written: \n\n memcache.add(key=\"weather_USA_98105\", value=\"raining\", time=3600)\n\nLearn more about `add()` and other methods for setting values in the [memcache\nPython API\ndocumentation](/appengine/docs/legacy/standard/python/refdocs/google.appengine.api.memcache).\n\nSee other examples of caching values in [Memcache Examples](/appengine/docs/legacy/standard/python/memcache/examples).\n\n### Looking up cached values\n\nUse `get()` to look up the value of a single key: \n\n memcache.get(key=\"[KEY]\")\n\nFor example, to get the value of the key `weather_USA_98105`: \n\n memcache.get(key=\"weather_USA_98105\")\n\nLearn more about `get()` and other methods for looking up values in the\n[memcache Python API\ndocumentation](/appengine/docs/legacy/standard/python/refdocs/google.appengine.api.memcache).\n\nMonitoring memcache in the Google Cloud console\n-----------------------------------------------\n\n1. Go to the Memcache page in the Google Cloud console. \n [Go to the Memcache page](https://console.cloud.google.com/appengine/memcache) \n2. Look at the following reports:\n - **Memcache service level** : Shows if your application is using the Shared or Dedicated service level. If you are an owner of the project, you can switch between the two. Learn more about the [service levels](./#service_levels).\n - **Hit ratio**: Shows the percentage of data requests that were served from the cache, as well as the raw number of data requests that were served from the cache.\n - **Items in the cache**.\n - **Oldest item age**: The age of the oldest cached item. Note that the age of an item is reset every time it is used, either read or written.\n - **Total cache size**.\n3. You can take any of the following actions:\n\n - **New key**: Add a new key to the cache.\n - **Find a key**: Retrieve an existing key.\n - **Flush cache**: Remove all the key-value pairs from the cache.\n4. (Dedicated memcache only) Look through the list of **Hot keys**.\n\n - \"Hot keys\" are keys that receive more than 100 queries per second (QPS) in the memcache.\n - This list includes up to 100 hot keys, sorted by highest QPS.\n\nHandling concurrent writes\n--------------------------\n\nTo use the compare and set feature to handle writes from multiple requests to\nthe same memcache key:\n\n1. Instantiate a memcache `Client` object.\n2. Use a retry loop (preferably with a limit on the number of retries and using exponential backoff)\n 1. Within the retry loop, get the key using `gets()` or `get_multi()` with the `for_cas` parameter set to `True`.\n 2. Within the retry loop, update the key value using `cas()` or `cas_multi()`.\n\nThe following snippet shows one way to use the compare and set feature: \n\n def bump_counter(key):\n client = memcache.Client()\n while True: # Retry loop\n counter = client.gets(key)\n if counter is None: raise KeyError('Uninitialized counter')\n if client.cas(key, counter+1):\n break\n\nThe retry loop is necessary because without the loop this code doesn't actually\navoid race conditions, it just detects them! The memcache service guarantees\nthat when used in the pattern shown here (that is, using `gets()` and `cas()`),\nif two (or more) different client instances happen to be involved in a race\ncondition, only the first one to execute the `cas()` operation succeeds (return\n`True`), while the second one (and subsequent ones) fails (return `False`).\n\nAnother refinement you should add to this sample code is to set a limit on the\nnumber of retries, to avoid an infinite loop in worst-case scenarios where there\nis a lot of contention for the same counter. An example of when such contention\ncould occur is if there are more requests trying to update the counter than the\nmemcache service can process in real time.\n\nLearn more about compare and set in the [Memcache\nOverview](/appengine/docs/legacy/standard/python/memcache#compare_and_set).\n\nWhat's next\n-----------\n\n- Learn more about memcache in the [Memcache Overview](/appengine/docs/legacy/standard/python/memcache).\n- See code examples of using memcache in Python in [Memcache\n Examples](/appengine/docs/legacy/standard/python/memcache/examples)."]]