函数的基本redis缓存
python-redis-cache的Python项目详细描述
python redis缓存
python函数的简单redis缓存
要求
- Redis 5+
- Python3.6+
如何安装
pip install python-redis-cache
如何使用
fromredisimportStrictRedisfromredis_cacheimportRedisCacheclient=StrictRedis(host="redis",decode_responses=True)cache=RedisCache(redis_client=client)@cache.cache()defmy_func(arg1,arg2):result=some_expensive_operation()returnresult# Use the functionmy_func(1,2)# Call it again with the same arguments and it will use cachemy_func(1,2)# Invalidate a single valuemy_func.invalidate(1,2)# Invalidate all values for functionmy_func.invalidate_all()
限制和需要了解的内容
默认情况下,参数和返回类型必须是JSON可序列化的。可以重写序列化程序,但要小心使用pickle。确保你了解安全风险。pickle不应与不受信任的值一起使用。 https://security.stackexchange.com/questions/183966/safely-load-a-pickle-file
- ttl-基于它第一次插入缓存的时间,而不是基于最后一次访问的时间
- limit-该限制将基于fifo而不是基于lru撤销密钥(一旦达到该限制)
API
RedisCache(redis_client,prefix="rc",serializer=dumps,deserializer=loads)RedisCache.cache(ttl=None,limit=None,namespace=None)# Cached function API# Returns a cached value, if it exists in cache. Saves value in cache if it doesn't existcached_func(*args,*kwargs)# Invalidates a single valuecached_func.invalidate(*args,**kwargs)# Invalidates all values for cached functioncached_func.invalidate_all()
- prefix-在redis键前面加上前缀的字符串
- 序列化器/反序列化器-用于将参数和返回值转换为字符串的函数(默认情况下为用户json)
- ttl-缓存返回值的时间(秒)
- namespace—缓存的字符串命名空间。这对于允许多个函数使用同一缓存很有用。默认情况下,它的
f'{function.__module__}.{function.__file__}'