skip to Main Content

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


  1. Chosen as BEST ANSWER

    If it helps anyone, I am using redisTemplate.expireAt(String Key, Date date) method for this purpose. It works for me.


  2. In Redis (and also Spring Data Redis) you can only use EXPIRE (which is what expireAt(String key, Date date) uses) on an entire key – you cannot expire some fields (entries) of a hash but not others. You can only expire the entire hash.

    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 second hash (or a zset) with the same fields as my hash, but where the value of each field (score if using a zset) 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 a hash. But that comes with its own drawbacks (e.g. if you need HLEN you’ll need to implement that in your code using SCAN).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search