Skip to content Skip to sidebar Skip to footer

How To Set Hash Key Expiration In Redis According To The Existance Of The Key

I would like to set the expiration of some hash keys, and if it is the first time to hset the key, I wish to set an expiration, other wise, I prefer to keep the expiration that is

Solution 1:

You CANNOT achieve that with pipeline, since you never know whether the key is existed until the whole pipeline has been executed. Instead, you can use Lua scripting to do the job:

localkey= KEYS[1]
localfield= ARGV[1]
localvalue= ARGV[2]
localttl= ARGV[3]

localexist= redis.call('exists', key)

redis.call('hset', key, field, value)

ifexist== 0 then
    redis.call('expire', key, ttl)
end

Check this to see how to run Lua script with redis-py. Then run the script with pipeline to reduce the RTT.

UPDATE

If you insist on using WATCH to do the job, you can try the following code:

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

Post a Comment for "How To Set Hash Key Expiration In Redis According To The Existance Of The Key"