skip to Main Content

I have a String RedisTemplate to access REDIS. Underneath there is a connection that I get through a LettuceConnectionFactory.

I would like to accomplish the equivalent to these REDIS commands with the RedisTemplate instance.

set my_key new_value keepttl

What I have now is this:

RedisTemplate<String, String> redisTemplate = getMyRedisTemplate();
final ValueOperations<String, String> ops = redisTemplate.opsForValue();
ops.set("my_key", "new_value");

But if I do this, I loose the ttl previously set.

On the other hand, if I do this:

RedisTemplate<String, String> redisTemplate = getMyRedisTemplate();
final ValueOperations<String, String> ops = redisTemplate.opsForValue();
Long expire = redisTemplate.getExpire("my_key");
ops.set("my_key", "new_value", expire);

I feel like I am doing an extra unnecessary roundtrip to REDIS. That’s what’s the KEEPTTL is all about. Preventing this.

Any Ideas?

2

Answers


  1. You can use LUA.

    RedisScript script = RedisScript.of("return redis.call('SET', KEYS[1], ARGV[1], 'KEEPTTL')");
    redisTemplate.execute(script, Collections.singletonList("my_key"), "new_value");
    
    Login or Signup to reply.
  2. I use Redisson. It nicely integrates with Spring Data Redis.
    It has built-in option for setting value along with ttl.

    https://github.com/redisson/redisson

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