Memcache 示例

本页面介绍以 用于使用 Memcache 的 Python 代码。 Memcache 是一个高性能的分布式内存对象缓存系统,可让您快速访问缓存数据。要详细了解 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 文档