【问题标题】:Python in-memory cache with time to livePython 内存缓存与生存时间
【发布时间】:2015-08-02 11:12:58
【问题描述】:

我有多个线程运行相同的进程,它们需要能够相互通知在接下来的 n 秒内不应该处理某些事情,但如果他们这样做了,那也不是世界末日。

我的目标是能够将字符串和 TTL 传递给缓存,并能够以列表的形式获取缓存中的所有字符串。缓存可以驻留在内存中,并且 TTL 不会超过 20 秒。

有人对如何实现这一点有任何建议吗?

【问题讨论】:

  • 关于线程,在现代 Python 中,threading.Barrier 应该很受关注,因为它有一个超时。

标签: python caching


【解决方案1】:

如果您不想使用任何第 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

【讨论】:

  • 这个解决方案真的很优雅。只是遗憾的是,这种方法并不能保证每个缓存值恰好在 TTL 值之后过期。实际上,缓存值在 0 和 TTL 值之间过期。
  • 看起来不错,但您能解释一下它的工作原理/原因吗?这是黑客/解决方法还是公认的习语?
  • @noamtm 谢谢。它之所以有效,是因为它利用了 lru_cache 取决于给定参数集的事实,其中一个 (ttl_hash) 在一段时间内保持不变。然后ttl_hash 发生变化,因此创建了一组新参数。 lru_cache 找不到这个新集合的缓存并调用 cachable 函数。我不会说这是“黑客”,我认为这是“技术”。不幸的是,我没有足够的权力将其标记为“公认的成语”。我希望它只是指“常识”。
  • 这也是一种有效的内存泄漏,因为旧值将继续被缓存,但由于哈希值不断单调增加而永远无法重用?
  • @kardenal.mendoza 应该没问题,因为lru_cache 有maxsize。
【解决方案2】:

OP 使用的是 python 2.7,但如果您使用的是 python 3,则接受的答案中提到的ExpiringDict 目前已经过期。 github repo 的最后一次提交是 2017 年 6 月 17 日,有一个未解决的问题是 doesn't work with Python 3.5

截至 2020 年 9 月 1 日,有一个最近维护的项目 cachetools。

pip install cachetools

from cachetools import TTLCache

cache = TTLCache(maxsize=10, ttl=360)
cache['apple'] = 'top dog'
...
>>> cache['apple']
'top dog'
... after 360 seconds...
>>> cache['apple']
KeyError exception raised

ttl 是以秒为单位的生存时间。

【讨论】:

  • 请注意,如果您不使用缓存工具作为装饰器,则该站点有一个注释,您必须处理锁,因为它不是线程安全的。查看网站顶部的注释:cachetools.readthedocs.io/en/stable
  • @Guigreg 它实际上说您需要使用缓存装饰器和锁。 “必须正确同步从多个线程访问共享缓存,例如,通过使用具有合适锁定对象的记忆装饰器之一。”
【解决方案3】:

关于一个即将过期的内存缓存,对于一般用途,一个常见的设计模式通常不是通过字典,而是通过函数或方法装饰器。缓存字典在后台进行管理。因此,这个答案在某种程度上补充了answer by User,它使用字典而不是装饰器。

cachetools 中的 ttl_cache 装饰器与functools.lru_cache 的工作方式非常相似,但带有time to live。

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

【讨论】:

    【解决方案4】:

    您可以使用expiringdict 模块:

    该库的核心是 ExpiringDict 类,它是一个有序字典,具有自动过期值用于缓存目的。

    在描述中他们没有谈论多线程,所以为了不搞砸,使用Lock。

    【讨论】:

    • 实际上他们在内部的设置/获取操作上使用了锁。
    • @alkuzad:好的,那么你可以完全避免 Lock。
    • 我尝试了这个模块,但它需要为我的用例做一些工作,因为我只需要一个列表,而且看起来你不能只循环一个 ExpiringDict 类,因为它给出了重复项
    • @HeDares:我知道您需要一个列表,但是如果您的列表不包含重复项,您可以使用字典键来表示列表值(并将字典值设置为类似 @987654326 @)。然后用d.keys() 遍历它们
    • 正如stackoverflow.com/a/52128389/1260237 中提到的,expiringdict 似乎不再维护,cachetools 似乎是一个很好的继任者。
    【解决方案5】:

    我非常喜欢@iutinvg 的想法,我只是想更进一步;将它与必须知道将ttl 传递到每个函数中并使其成为装饰器而不必考虑它。如果你有django、py3,并且不想 pip 安装任何依赖项,试试这个。

    import time
    from django.utils.functional import lazy
    from functools import lru_cache, partial, update_wrapper
    
    
    def lru_cache_time(seconds, maxsize=None):
        """
        Adds time aware caching to lru_cache
        """
        def wrapper(func):
            # Lazy function that makes sure the lru_cache() invalidate after X secs
            ttl_hash = lazy(lambda: round(time.time() / seconds), int)()
            
            @lru_cache(maxsize)
            def time_aware(__ttl, *args, **kwargs):
                """
                Main wrapper, note that the first argument ttl is not passed down. 
                This is because no function should bother to know this that 
                this is here.
                """
                def wrapping(*args, **kwargs):
                    return func(*args, **kwargs)
                return wrapping(*args, **kwargs)
            return update_wrapper(partial(time_aware, ttl_hash), func)
        return wrapper
    

    证明它有效(通过示例):

    @lru_cache_time(seconds=10)
    def meaning_of_life():
        """
        This message should show up if you call help().
        """
        print('this better only show up once!')
        return 42
    
    
    @lru_cache_time(seconds=10)
    def multiply(a, b):
        """
        This message should show up if you call help().
        """
        print('this better only show up once!')
        return a * b
        
    # This is a test, prints a `.` for every second, there should be 10s 
    # between each "this better only show up once!" *2 because of the two functions.
    for _ in range(20):
        meaning_of_life()
        multiply(50, 99991)
        print('.')
        time.sleep(1)
    

    【讨论】:

      【解决方案6】:

      我知道这有点老了,但对于那些对没有第三方依赖项感兴趣的人,这是内置 functools.lru_cache 的一个小包装(我在写完这篇文章后注意到Javier's similar answer,但我想我会发布它无论如何,因为这不需要 Django):

      import functools
      import time
      
      
      def time_cache(max_age, maxsize=128, typed=False):
          """Least-recently-used cache decorator with time-based cache invalidation.
      
          Args:
              max_age: Time to live for cached results (in seconds).
              maxsize: Maximum cache size (see `functools.lru_cache`).
              typed: Cache on distinct input types (see `functools.lru_cache`).
          """
          def _decorator(fn):
              @functools.lru_cache(maxsize=maxsize, typed=typed)
              def _new(*args, __time_salt, **kwargs):
                  return fn(*args, **kwargs)
      
              @functools.wraps(fn)
              def _wrapped(*args, **kwargs):
                  return _new(*args, **kwargs, __time_salt=int(time.time() / max_age))
      
              return _wrapped
      
          return _decorator
      

      及其用法:

      @time_cache(10)
      def expensive(a: int):
          """An expensive function."""
          time.sleep(1 + a)
      
      
      print("Starting...")
      expensive(1)
      print("Again...")
      expensive(1)
      print("Done")
      

      注意,这使用time.time 并附带所有警告。如果可用/适当,您可能想改用 time.monotonic。

      【讨论】:

      • 使用time.time有哪些注意事项?
      • 嗨。你能解释一下__time_salt是什么吗?我在互联网上找不到任何关于它的信息。
      • @PawanBhandarkar lrc_cache 获取函数的所有参数并创建一个键,因此,即使您更改一个键,它也会映射到因此刷新的新条目。这只是强制 lrc_cache lib 在最大大小之上提供 TTL 的一个技巧。 __time_salt 可以任意命名(hash、timed hash、timed salt 无所谓)
      • @AngryUbuntuNerd time.time 依赖于系统时钟并且可能不是单调的(即它不能保证总是增加,如果你的机器通过网络同步它的系统时钟,它实际上可能会减少)。对于需要增加时间的情况,应该首选time.monotonic。
      【解决方案7】:

      如果你想避免第三方包,你可以添加一个自定义的timed_lru_cache decorator,它基于 lru_cache 装饰器。

      以下默认值为 20 秒的生命周期,最大大小为 128。请注意,整个缓存会在 20 秒后过期,而不是单个项目。

      from datetime import datetime, timedelta
      from functools import lru_cache, wraps
      
      
      def timed_lru_cache(seconds: int = 20, maxsize: int = 128):
          def wrapper_cache(func):
              func = lru_cache(maxsize=maxsize)(func)
              func.lifetime = timedelta(seconds=seconds)
              func.expiration = datetime.utcnow() + func.lifetime
      
              @wraps(func)
              def wrapped_func(*args, **kwargs):
                  if datetime.utcnow() >= func.expiration:
                      func.cache_clear()
                      func.expiration = datetime.utcnow() + func.lifetime
      
                  return func(*args, **kwargs)
      
              return wrapped_func
      
          return wrapper_cache
      

      然后,只需在您的函数上方添加 @timed_lru_cache() 即可:

      @timed_lru_cache()
      def my_function():
        # code goes here...
      

      【讨论】:

      • 即使没有传递任何参数,您也可能需要调用包装器:@timed_lru_cache()。否则,您可能会收到TypeError: Expected first argument to be an integer, a callable, or None。
      【解决方案8】:

      类似的东西?

      from time import time, sleep
      import itertools
      from threading import Thread, RLock
      import signal
      
      
      class CacheEntry():
        def __init__(self, string, ttl=20):
          self.string = string
          self.expires_at = time() + ttl
          self._expired = False
      
        def expired(self):
          if self._expired is False:
            return (self.expires_at < time())
          else:
            return self._expired
      
      class CacheList():
        def __init__(self):
          self.entries = []
          self.lock = RLock()
      
        def add_entry(self, string, ttl=20):
          with self.lock:
              self.entries.append(CacheEntry(string, ttl))
      
        def read_entries(self):
          with self.lock:
              self.entries = list(itertools.dropwhile(lambda x:x.expired(), self.entries))
              return self.entries
      
      def read_entries(name, slp, cachelist):
        while True:
          print "{}: {}".format(name, ",".join(map(lambda x:x.string, cachelist.read_entries())))
          sleep(slp)
      
      def add_entries(name, ttl, cachelist):
        s = 'A'
        while True:
          cachelist.add_entry(s, ttl)
          print("Added ({}): {}".format(name, s))
          sleep(1)
          s += 'A'
      
      
      
      if __name__ == "__main__":
        signal.signal(signal.SIGINT, signal.SIG_DFL)
      
        cl = CacheList()
        print_threads = []
        print_threads.append(Thread(None, read_entries, args=('t1', 1, cl)))
        # print_threads.append(Thread(None, read_entries, args=('t2', 2, cl)))
        # print_threads.append(Thread(None, read_entries, args=('t3', 3, cl)))
      
        adder_thread = Thread(None, add_entries, args=('a1', 2, cl))
        adder_thread.start()
      
        for t in print_threads:
          t.start()
      
        for t in print_threads:
          t.join()
      
        adder_thread.join()
      

      【讨论】:

      • 就像我必须添加的魅力一样: def __repr__(self): return self.string To class CacheEntry()
      【解决方案9】:

      你也可以选择dictttl,它有 MutableMapping、OrderedDict 和 defaultDict(list)

      初始化一个普通的字典,每个键的 ttl 为 30 秒

      data = {'a': 1, 'b': 2}
      dict_ttl = DictTTL(30, data)
      

      OrderedDict

      data = {'a': 1, 'b': 2}
      dict_ttl = OrderedDictTTL(30, data)
      

      defaultDict(列表)

      dict_ttl = DefaultDictTTL(30)
      data = {'a': [10, 20], 'b': [1, 2]}
      [dict_ttl.append_values(k, v) for k, v in data.items()]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-12-21
        • 1970-01-01
        • 2013-06-13
        • 1970-01-01
        • 2021-06-30
        • 2016-06-12
        • 2017-11-19
        • 1970-01-01
        相关资源
        最近更新 更多