代码之家  ›  专栏  ›  技术社区  ›  buxizhizhoum

如何根据密钥的存在设置redis中的哈希密钥过期

  •  0
  • buxizhizhoum  · 技术社区  · 8 年前

    我想设置一些哈希键的过期时间,如果是第一次设置该键,我想设置一个过期时间,否则,我宁愿保留第一次设置的过期时间。

    由于有大量的散列键,我更喜欢在管道中进行,但是下面的函数不能很好地工作。

    这条线 pipe.exists(hkey) 返回管道的obj,该值始终为true,因此if子句总是转到一个部分,而不管哈希键是否存在。

    我的问题是:有没有一种方法可以根据管道中哈希键的存在来设置哈希键的过期?

    def test1(hkey, v):
        with r.pipeline() as pipe:
            # tmp = pipe.exists(hkey)
            # pipe.exists(hkey) is a pipe obj, which is always True, 
            # this line not work as expected and the two lines below it will never be excuted.
            if not pipe.exists(hkey):
                pipe.hset(hkey, v, v)
                pipe.expire(hkey, 3600)
            else:
                # no matter whether the hash key is exist or not, the if else statment always goes to this line.
                pipe.hset(hkey, v, v)
            pipe.execute()
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   for_stack    7 年前

    Lua scripting

    local key = KEYS[1]
    local field = ARGV[1]
    local value = ARGV[2]
    local ttl = ARGV[3]
    
    local exist = redis.call('exists', key)
    
    redis.call('hset', key, field, value)
    
    if exist == 0 then
        redis.call('expire', key, ttl)
    end
    

    检查 this RTT .

    WATCH

    with r.pipeline() as pipe:
        while 1:
            try:
                pipe.watch(hkey)
    
                exist = pipe.exists(hkey)
    
                pipe.multi()
    
                if not exist:
                    pipe.hset(hkey, v, v)
                    pipe.expire(hkey, 3600)
                else:
                    pipe.hset(hkey, v, v)
    
                pipe.execute()
                break;
            except WatchError:
                continue