Memcache 範例

本頁提供 Java 的程式碼範例,說明如何使用低階 Memcache API。 使用 Memcache 的 Python 程式碼。 Memcache 是高效能的分散式記憶體物件快取系統,可快速存取快取資料。如要進一步瞭解 Memcache,請參閱 Memcache 總覽

Memcache 模式

Memcache 通常於下列模式中使用:

  • 應用程式接收來自使用者或應用程式的查詢。
  • 應用程式會檢查滿足該查詢所需的資料是否位於記憶體快取中。
    • 如果資料在 Memcache 中,則應用程式會使用該資料。
    • 如果資料不在 Memcache 中,應用程式會查詢資料儲存庫,並將結果儲存在 Memcache 中,供日後的要求使用。

下列虛擬程式碼代表的是一般的 Memcache 要求:

def get_data():
    data = memcache.get('key')
    if data is not None:
        return data
    else:
        data = query_for_data()
        memcache.add('key', data, 60)
    return data

ndb 內部會使用 Memcache 加快查詢速度。然而,如有需要,您也可以明確新增 Memcache 呼叫來進一步控管加速作業。

快取資料

下列範例示範多種使用 Python API 在 Memcache 中設定值的方法。

# Add a value if it doesn't exist in the cache
# with a cache expiration of 1 hour.
memcache.add(key="weather_USA_98105", value="raining", time=3600)

# Set several values, overwriting any existing values for these keys.
memcache.set_multi(
    {"USA_98115": "cloudy", "USA_94105": "foggy", "USA_94043": "sunny"},
    key_prefix="weather_",
    time=3600
)

# Atomically increment an integer value.
memcache.set(key="counter", value=0)
memcache.incr("counter")
memcache.incr("counter")
memcache.incr("counter")

如要進一步瞭解 add()set_multi()set() 方法,請參閱 Memcache Python API 說明文件