Say I have a model Employee
which has an expiry component to it. When the first request comes to retrieve the employee details, I want to store it in cache with a TTL based on the expiry of the Employee
object (employee.getExpiry()
).
I am unable to do it using @Cachable
in Spring. I looked at suggestion given here, but this makes use of cacheManager
and there's no way for me to dynamically set the TTL or expiry on that particular cache object.
I am using Redission for caching and I tried the following:
@Cacheable(value = "employees", key = "#designation")
public Employee retrieve(String designation) {
LOG.info("Retrieving Employee with query parameters: {}", designation);
Employee employee = employeeRepository.findByDesignation(designation);
LOG.info("Retrieved Employee: {}", employee);
RMapCache<String, Employee> employeCache = redissonClient.getMapCache("employees");
employeCache.put(employee.getDesignation(), employee, employee.getExpiry(), TimeUnit.SECONDS);
return employee;
}
But it doesn't work. I am manually setting the TTL using redissionClient
, but that particular entry gets replaced by @Cacheable(value = "employees", key = "#designation")
When I try without the @Cacheable
, it seems to work.
So my question is, how can I set TTL dynamically using @Cacheable
? If not, is manually doing it using RedissonClient
the only way?