In spring data redis we have two variables.
RedisTemplate<Key, Value> redisTemplate;
HashOperations<Key, HashKey, HashValue> hashOperations;
There is a method expireAt(String key, Date date) inside RedisTemplate. So if I want to set an expiry for a particular hash key I can use this method or this only works at Key level and expires all the entries inside that key?
2
Answers
If it helps anyone, I am using redisTemplate.expireAt(String Key, Date date) method for this purpose. It works for me.
In Redis (and also Spring Data Redis) you can only use
EXPIRE
(which is whatexpireAt(String key, Date date)
uses) on an entire key – you cannot expire some fields (entries) of ahash
but not others. You can only expire the entirehash
.This means if you want to expire some
hash
fields but not others you’ll need to find a workaround. One that I’ve used before is to have a secondhash
(or azset
) with the same fields as myhash
, but where the value of each field (score if using azset
) is the timestamp at which the field should expire. The drawback here is that you’ll need to have some code to check when fields expire and then remove them.Another option would be to just use regular
string
keys instead of ahash
. But that comes with its own drawbacks (e.g. if you needHLEN
you’ll need to implement that in your code usingSCAN
).