0

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?

Community
  • 1
  • 1
Auro
  • 1,578
  • 3
  • 31
  • 62

1 Answers1

0

Spring CacheManager API doesn't allow to define different TTL per entry. RMapCache object is the only way in this case.

Nikita Koksharov
  • 10,283
  • 1
  • 62
  • 71
  • Thanks. Could you please tell me if there is any difference in performance of the application in terms of CRUD operations using `RMapCache` instead of `@Cacheable`? I am not sure how `@Cacheable` works under the hood – Auro Mar 06 '20 at 09:39
  • It's subject of benchmark of particular use case. You could consider to use RBucket object and `RBucket.expire()` method if you use TTL parameter only. – Nikita Koksharov Mar 06 '20 at 09:45