Search code examples
javaspring-data-redisspring-repositories

Retrieve TTL of POJO stored using spring redis repository


I'm using a Spring redis repository for my project to persist a POJO into redis. Following example details what I'm trying to achieve.

@Data
@RedisHash("Example")
public class Example {
    @Id
    private String id;
    private String attributeA;
    private String attirbuteB;

    @TimeToLive(unit = TimeUnit.SECONDS)
    private Long timeToLive;
}

The repository for above POJO looks as shown below.

public interface ExampleRepository extends CrudRepository<Example, String> {

}

@TimeToLive works fine in setting the expiry into redis. In my code, I tried setting the value of timeToLive = 1200. The code goes as below...

Example example = new Example();
example.setId("abc");
example.setTimeToLive(1200L);
exampleRepository.save(example);

My problem starts when I attempt to retrieve the POJO from redis.

Example example = exampleRepository.findOne(id);
System.out.println(example.getTimeToLive());

Above code always prints 1200 as the output. From the CLI I can confirm that the TTL for object existing in redis is reducing as time passes. Yet, it is not set to the POJO I'm trying to retrieve.

Why am I not able to retrieve the current value of ttl set in redis for this POJO instance?

Is there an alternate way of achieving this using spring redis repository!

Thanks in advance!


Solution

  • Reading back the time to live value into the domain object is currently not directly supported. There is DATAREDIS-523 which targets this issue.

    Meanwhile you can retrieve the value via RedisTemplate.getExpire(key, timeUnit) eg. template.getExpire("Example:abc".getBytes(), TimeUnit.SECONDS).