简介
aiocache
支持多种后端(内存,Redis,Memcached)。
aiocache
的目标是简化而不是特殊化,所有缓存包含相同的最小接口,功能包括:
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]
初试
计算 35 项斐波那契数列。
不加缓存:12s
加缓存:0.009s
import time
import asyncio
from aiocache import cached
@cached(ttl=3600)
async def fib(n):
if n < 2:
return n
return await fib(n - 1) + await fib(n - 2)
async def main():
beg = time.time()
result = [await fib(i) for i in range(35)]
end = time.time()
print(result)
print(end - beg)
# 不加缓存 11.77s
# 加缓存 0.009s
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(main())