微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

有没有办法为 Django 缓存锁设置过期时间?

如何解决有没有办法为 Django 缓存锁设置过期时间?

我有一个 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',3000)) 设置超时一样?

解决方法

我已经回答了我自己的问题。 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 的注释,使用相同的参数:

   ``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)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?