yi zhang
yi zhang

Reputation: 3

how to redis hset only if key exists

I use redis to cache my web blog.My article has a field "checked",if this field changed in database,I also need to set the new value to redis,here is code

if redis_conn.exists("article"):
    redis_conn.hset("article", "checked",1)

it seems like ok,but if article key expired after exists and before hset,there will be some problems.the article key will only has one field of checked,other field like title,content,etc...will gone.

how to hset only if key exists,if key is expired just do nothing.

Upvotes: 0

Views: 1988

Answers (1)

Itamar Haber
Itamar Haber

Reputation: 49942

You can use a Lua script for that, i.e. (pseudo NodeJS):

redis_conn.eval("if redis.call('EXISTS', KEYS[1])==1 then redis.call('HSET', KEYS[1], ARGV[1], ARGV[2]) end", 1, "article", "checked", 1)

Server-side Lua scripts are atomic, so you are assured that the key will not expire in between calls.

Note: Redis does have the HSETNX command, but not the HSETEX command, which is apparently what you're looking for.

Upvotes: 3

Related Questions