多后端异步缓存
项目描述
Asyncio缓存支持多个后端(内存、redis和memcached)。
此库追求简单而非特殊化。所有缓存都包含相同的最小接口,该接口由以下函数组成
add:仅当键不存在时才添加键/值。
get:检索由键标识的值。
set:设置键/值。
multi_get:检索多个键/值。
multi_set:设置多个键/值。
exists:如果键存在返回 True,否则返回 False。
increment:递增给定键存储的值。
delete:删除键并返回删除的项目数。
clear:清除存储的项目。
raw:使用底层客户端执行指定的命令。
安装
pip install aiocache
pip install aiocache[redis]
pip install aiocache[memcached]
pip install aiocache[redis,memcached]
pip install aiocache[msgpack]
用法
使用缓存就像
>>> import asyncio
>>> from aiocache import Cache
>>> cache = Cache(Cache.MEMORY) # Here you can also use Cache.REDIS and Cache.MEMCACHED, default is Cache.MEMORY
>>> with asyncio.Runner() as runner:
>>> runner.run(cache.set('key', 'value'))
True
>>> runner.run(cache.get('key'))
'value'
或者作为一个装饰器
import asyncio
from collections import namedtuple
from aiocache import cached, Cache
from aiocache.serializers import PickleSerializer
# With this we can store python objects in backends like Redis!
Result = namedtuple('Result', "content, status")
@cached(
ttl=10, cache=Cache.REDIS, key="key", serializer=PickleSerializer(), port=6379, namespace="main")
async def cached_call():
print("Sleeping for three seconds zzzz.....")
await asyncio.sleep(3)
return Result("content", 200)
async def run():
await cached_call()
await cached_call()
await cached_call()
cache = Cache(Cache.REDIS, endpoint="127.0.0.1", port=6379, namespace="main")
await cache.delete("key")
if __name__ == "__main__":
asyncio.run(run())
创建新缓存推荐的方式是使用 Cache 构造函数。然而,您也可以直接使用 aiocache.RedisCache、aiocache.SimpleMemoryCache 或 aiocache.MemcachedCache 来实例化。
您还可以设置缓存别名,以便轻松重用配置
import asyncio
from aiocache import caches
# You can use either classes or strings for referencing classes
caches.set_config({
'default': {
'cache': "aiocache.SimpleMemoryCache",
'serializer': {
'class': "aiocache.serializers.StringSerializer"
}
},
'redis_alt': {
'cache': "aiocache.RedisCache",
'endpoint': "127.0.0.1",
'port': 6379,
'timeout': 1,
'serializer': {
'class': "aiocache.serializers.PickleSerializer"
},
'plugins': [
{'class': "aiocache.plugins.HitMissRatioPlugin"},
{'class': "aiocache.plugins.TimingPlugin"}
]
}
})
async def default_cache():
cache = caches.get('default') # This always returns the SAME instance
await cache.set("key", "value")
assert await cache.get("key") == "value"
async def alt_cache():
cache = caches.create('redis_alt') # This creates a NEW instance on every call
await cache.set("key", "value")
assert await cache.get("key") == "value"
async def test_alias():
await default_cache()
await alt_cache()
await caches.get("redis_alt").delete("key")
if __name__ == "__main__":
asyncio.run(test_alias())
它是如何工作的
Aiocache 提供了 3 个主要实体
后端:允许您指定用于缓存的后端。目前支持:SimpleMemoryCache、使用 redis 的 RedisCache 和使用 aiomcache 的 MemCache。
序列化器:在您的代码和后端之间序列化和反序列化数据。这允许您将任何 Python 对象保存到缓存中。目前支持:StringSerializer、PickleSerializer、JsonSerializer 和 MsgPackSerializer。但您也可以构建自定义的。
插件:实现一个钩子系统,允许在每个命令之前和之后执行额外的行为。
如果您缺少后端、序列化器或插件的实施,您认为它可能对包有用,请不要犹豫,提出一个新的问题。
这 3 个实体在执行一些缓存操作时会结合在一起,以应用所需的命令(后端)、数据转换(序列化器)和预/后钩子(插件)。为了更好地了解发生了什么,您可以在以下链接中查看 set 函数如何在 aiocache 中工作
惊人的例子
在 示例文件夹 中,您可以查看不同的用例
文档
项目详情
下载文件
下载适用于您平台的文件。如果您不确定选择哪个,请了解更多关于安装包的信息。