在Django/python中,如何将memcache设置为无限时间?

9 投票
4 回答
12082 浏览
提问于 2025-04-15 23:13
cache.set(key, value, 9999999)

但是这不是无尽的时间……

4 个回答

8

Django 1.6 版本增加了对不失效缓存的支持,你可以通过设置 timeout=None 来实现这个功能。想象一下,这就像是把你喜欢的食物放在冰箱里,不管过了多久,它都不会变坏。

11

来自文档

如果这个设置的值是 None,那么缓存的内容就不会过期。

值得注意的是,这和 Memcache 的标准协议中的过期时间是不同的:

过期时间可以设置为 0,表示“永不过期”,也可以设置到 30 天。任何超过 30 天的时间都会被解释为一个 Unix 时间戳日期。

所以,如果你想让一个键永远不过期,如果你使用的是 Django 的缓存抽象,就把超时时间设置为 None;如果你更直接地使用 Memcache,就把超时时间设置为 0

12
def _get_memcache_timeout(self, timeout):
    """
    Memcached deals with long (> 30 days) timeouts in a special
    way. Call this function to obtain a safe value for your timeout.
    """
    timeout = timeout or self.default_timeout
    if timeout > 2592000: # 60*60*24*30, 30 days
        # See http://code.google.com/p/memcached/wiki/FAQ
        # "You can set expire times up to 30 days in the future. After that
        # memcached interprets it as a date, and will expire the item after
        # said date. This is a simple (but obscure) mechanic."
        #
        # This means that we have to switch to absolute timestamps.
        timeout += int(time.time())
    return timeout

来自常见问题解答

设置过期时间有什么限制?(为什么有30天的限制?)

你可以设置的过期时间最长为30天。超过这个时间,memcached就会把它当作一个日期来处理,并在这个日期之后让这个项目过期。这是一个简单(但不太明显)的机制。

撰写回答