有没有办法设置django缓存锁的过期时间?

eqzww0vc  于 2021-06-07  发布在  Redis
关注(0)|答案(1)|浏览(527)

我有一个django3.1.3服务器,它通过djangoredis4.12.1使用redis作为缓存。我知道缓存锁通常可以通过以下方式设置:

with cache.lock('my_cache_lock_key'):
    # Execute some logic here, such as:
    cache.set('some_key', 'Hello world', 3000)

通常,当 with 块完成执行。但是,我的代码中有一些自定义逻辑,有时无法释放缓存锁(这是我自己的原因)。
我的问题是:有没有一种方法可以设置django缓存锁的超时值,就像设置缓存值的超时值一样( cache.set('some_key', 'Hello world', 3000) )?

z0qdvdin

z0qdvdin1#

我已经回答了我自己的问题。以下参数可用于 cache.lock() :

def lock(
        self,
        key,
        version=None,
        timeout=None,
        sleep=0.1,
        blocking_timeout=None,
        client=None,
        thread_local=True,
    ):

交叉引用来自python redis源代码的注解,该源代码使用相同的参数:

``timeout`` indicates a maximum life for the lock.
    By default, it will remain locked until release() is called.
    ``timeout`` can be specified as a float or integer, both representing
    the number of seconds to wait.
    ``sleep`` indicates the amount of time to sleep per loop iteration
    when the lock is in blocking mode and another client is currently
    holding the lock.
    ``blocking`` indicates whether calling ``acquire`` should block until
    the lock has been acquired or to fail immediately, causing ``acquire``
    to return False and the lock not being acquired. Defaults to True.
    Note this value can be overridden by passing a ``blocking``
    argument to ``acquire``.
    ``blocking_timeout`` indicates the maximum amount of time in seconds to
    spend trying to acquire the lock. A value of ``None`` indicates
    continue trying forever. ``blocking_timeout`` can be specified as a
    float or integer, both representing the number of seconds to wait.

因此,要设置缓存锁生效的最长时间段(2秒),请执行以下操作:

with cache.lock(key='my_cache_lock_key', timeout=2):
    # Execute some logic here, such as:
    cache.set('some_key', 'Hello world', 3000)

相关问题