Reputation: 17956
Is there an atomic GET
+ EXPIRE
command available for Redis? This would act as a sliding expiration value: attempt to get the value specified by the key, and then only if the key was found with this request, set the time to live for X seconds.
Upvotes: 3
Views: 3660
Reputation: 188
Or, I use simple Lua script:
local val, err = redis.pcall('GET', KEYS[1])
if err then
return err
end
redis.call('EXPIRE', KEYS[1], ARGV[1])
return {val}
In Golang you can do:
import "github.com/go-redis/redis"
const lua = `
local val, err = redis.pcall('GET', KEYS[1])
if err then
return err
end
redis.call('EXPIRE', KEYS[1], ARGV[1])
return {val}
`
redisGetEx = redis.NewScript(lua)
result, err = redisGetEx.Run(redisClient, []string{"key"}, 1800).Result()
Upvotes: 2
Reputation: 50112
No, there isn't, but there's nothing preventing you from sending the two commands one after the other in a MULTI/EXEC
block or using a Lua script. Using EXPIRE
on a non-existent key does nothing.
Upvotes: 5