用法

oslo.cache 的一个简单示例

from oslo_cache import core as cache
from oslo_config import cfg

CONF = cfg.CONF

caching = cfg.BoolOpt('caching', default=True)
cache_time = cfg.IntOpt('cache_time', default=3600)
CONF.register_opts([caching, cache_time], "feature-name")

cache.configure(CONF)
example_cache_region = cache.create_region()
MEMOIZE = cache.get_memoization_decorator(
    CONF, example_cache_region, "feature-name")

# Load config file here

cache.configure_cache_region(CONF, example_cache_region)


@MEMOIZE
def f(x):
    print(x)
    return x

为此示例的配置文件如下所示

[cache]
enabled = true
backend = dogpile.cache.memory

[feature-name]
caching = True
cache_time = 7200

在上面的示例中,调用的顺序有一些微妙之处。要求如下:必须首先完成 configurecreate_region 必须在 get_memoization_decoratorconfigure_cache_region 之前(因为它们使用其输出);在调用 configure_cache_region 之前,配置文件必须完全加载;所有这些调用都必须在实际调用装饰的函数之前完成。原则上,可以有几种不同的顺序。实际上,装饰器将在导入时使用,配置文件将在之后加载,因此上述顺序是唯一的可能顺序。