redis2.8新特性set值的同时设置过期时间

2019-07-31  本文已影响0人  蕴重Liu

具体看文档或注释,如果还是有点懵,那就特意动手试一下
http://redisdoc.com/string/set.html

    def set(self, name, value, ex=None, px=None, nx=False, xx=False):
        """
        Set the value at key ``name`` to ``value``

        ``ex`` sets an expire flag on key ``name`` for ``ex`` seconds.

        ``px`` sets an expire flag on key ``name`` for ``px`` milliseconds.

        ``nx`` if set to True, set the value at key ``name`` to ``value`` only
            if it does not exist.

        ``xx`` if set to True, set the value at key ``name`` to ``value`` only
            if it already exists.
        """
        pieces = [name, value]
        if ex is not None:
            pieces.append('EX')
            if isinstance(ex, datetime.timedelta):
                ex = int(ex.total_seconds())
            pieces.append(ex)
        if px is not None:
            pieces.append('PX')
            if isinstance(px, datetime.timedelta):
                px = int(px.total_seconds() * 1000)
            pieces.append(px)

        if nx:
            pieces.append('NX')
        if xx:
            pieces.append('XX')
        return self.execute_command('SET', *pieces)

本质也是拼接命令在cli界面执行

解释结束,看实际项目的主要应用:

设置60s过期时间
DB.ai_redis.set(name='DETECT_FACE_RESULT:image_id', value=json.dumps(face_list), ex=60)

补充:redis一般采用惰性删除策略,即38分set的值,一分钟有效期,需等到40分才看到该值失效

上一篇下一篇

猜你喜欢

热点阅读