具有生存时间的 Python 内存缓存

标签 python caching

我有多个线程运行同一个进程,它们需要能够相互通知在接下来的 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/

相关文章:

python - pandas:使用 apply 获取具有两个最高值的列

python - 如何计算相似度矩阵的均值和标准差?

python - 检测单词中的重音(Python)

HTML5 应用缓存 : How to exclude the htm-file from cache where the manifest is defined

具有多个列表的 Python 循环?

ascii的Python产物,错误的启动

asp.net - 缓存是客户端还是服务器端?

security - 刷新和重新加载缓存侧信道攻击

java - 是否有任何第三方java缓存可以提供对过期事件的控制?

c# - 如何使用c#访问vista和7的缩略图缓存