我有多个线程运行同一个进程,它们需要能够相互通知在接下来的 n 秒内不应该处理某些事情,但是如果他们这样做的话,这不是世界末日。
我的目标是能够将一个字符串和一个 TTL 传递给缓存,并能够将缓存中的所有字符串作为列表获取。缓存可以存在于内存中,TTL 不会超过 20 秒。
有人对如何实现这一目标有任何建议吗?
最佳答案
如果您不想使用任何第 3 个库,您可以在昂贵的函数中再添加一个参数:ttl_hash=None
。这个新参数就是所谓的“时间敏感哈希”,它的唯一目的是影响lru_cache
。
例如:
from functools import lru_cache
import time
@lru_cache()
def my_expensive_function(a, b, ttl_hash=None):
del ttl_hash # to emphasize we don't use it and to shut pylint up
return a + b # horrible CPU load...
def get_ttl_hash(seconds=3600):
"""Return the same value withing `seconds` time period"""
return round(time.time() / seconds)
# somewhere in your code...
res = my_expensive_function(2, 2, ttl_hash=get_ttl_hash())
# cache will be updated once in an hour
关于具有生存时间的 Python 内存缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31771286/