Spring Redis - Indexes not deleted after main entry expires

后端 未结 2 414
暗喜
暗喜 2020-12-31 13:40

I am saving new entries with a Spring Data Repository. I have a TTL of 10 seconds for each entry.

When I save an entry with indexes, here is what i get in Redis

2条回答
  •  梦谈多话
    2020-12-31 13:46

    No key/values will be deleted automatically if you don't set Expiration Time.

    So to automatically delete a data you have to set Expiration Time.

    redis> SET mykey "Hello"
    "OK"
    redis> EXPIRE mykey 10
    (integer) 1
    

    Ref : https://redis.io/commands/expire

    Below is the Spring code snippet to add a data to redis and set expiration time

    @Component
    public class RedisUtil {
        @Autowired
        private RedisTemplate template;
    
        @Resource(name = "redisTemplate")
        ValueOperations ops;
    
        public boolean addValue(String key, String value) {
    
            if (template.hasKey(Constants.REDIS_KEY_PREFIX + key)) {
                // key is already there
                return false;
            } else {
                ops.set(Constants.REDIS_KEY_PREFIX + key, value);
                template.expireAt(Constants.REDIS_KEY_PREFIX + key, 10);
            }
            return true;
        }
    }
    

提交回复
热议问题