【问题标题】:Time expiry dictionary in memory in PythonPython中内存中的时间到期字典
【发布时间】:2019-04-30 00:26:40
【问题描述】:

我只是想知道如何在 Python 中有效地在内存中实现时间过期字典,以便键值对在指定时间间隔后过期。

【问题讨论】:

  • 你有什么是过期哈希表的例子吗?你用另一种语言实现了吗?
  • 不...我只是想知道一个可行的逻辑可能是什么
  • 当它们“过期”时会发生什么?
  • 您可能想查看cachetools,它的 TTL 缓存似乎符合您的描述。

标签: python dictionary caching ttl


【解决方案1】:

通常这样做的设计模式不是通过字典,而是通过函数或方法装饰器。字典由缓存在后台管理。

此答案在 Python 3.7 中使用 cachetools==3.1.0 中的 ttl_cache 装饰器。它的工作原理很像functools.lru_cache,但使用time to live。至于它的实现逻辑,看它的source code。

import cachetools.func

@cachetools.func.ttl_cache(maxsize=128, ttl=10 * 60)
def example_function(key):
    return get_expensively_computed_value(key)


class ExampleClass:
    EXP = 2

    @classmethod
    @cachetools.func.ttl_cache()
    def example_classmethod(cls, i):
        return i**cls.EXP

    @staticmethod
    @cachetools.func.ttl_cache()
    def example_staticmethod(i):
        return i**3

如果你坚持使用字典,cachetools 也有TTLCache。

import cachetools

ttl_cache = cachetools.TTLCache(maxsize=128, ttl=10 * 60)

【讨论】:

  • 能不能一次性设置所有键的TTL,而不是一键设置。例如:ttl_cache 的所有内容在 TTL 后立即消失。
猜你喜欢
  • 2020-11-26
  • 1970-01-01
  • 1970-01-01
  • 2020-06-08
  • 1970-01-01
  • 1970-01-01
  • 2021-09-01
  • 2016-08-13
  • 2016-06-27
相关资源
最近更新 更多