有没有办法为 Django 缓存锁设置过期时间?
Posted
技术标签:
【中文标题】有没有办法为 Django 缓存锁设置过期时间?【英文标题】:Is there a way to set an expiration time for a Django cache lock? 【发布时间】:2021-04-02 10:35:49 【问题描述】:我有一个 Django 3.1.3 服务器,它通过 django-redis 4.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)
) 一样?
【问题讨论】:
【参考方案1】:我已经回答了我自己的问题。 following arguments 可用于cache.lock()
:
def lock(
self,
key,
version=None,
timeout=None,
sleep=0.1,
blocking_timeout=None,
client=None,
thread_local=True,
):
使用来自 Python Redis source 的 cmets 交叉引用它,它使用相同的参数:
``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)
【讨论】:
以上是关于有没有办法为 Django 缓存锁设置过期时间?的主要内容,如果未能解决你的问题,请参考以下文章