0

I have a method (e.g. ValueResponse ApiClient#getValue()) that calls an HTTP API which responds with something like this:

{
    "value": "xyz",
    "ttl":   3600
}

The ttl in the JSON response (in seconds) is not constant and might change between invocations of the API.

I call this method from another method that I want to make @Cacheable:

@Cacheable(...)
public ValueResponse someMethod() {
    return apiClient.getValue();
}

I want ValueResponse to be cached at most for the duration of its ttl field (actually ttl - 60 seconds).

How can I do this with Spring's cache abstraction?

P.S: in case it matters, I am using EhCache for caching, but might switch to Redis or Memcached in the future.

TheFooProgrammer
  • 2,439
  • 5
  • 28
  • 43
  • You can use org.springframework.cache.interceptor.CacheInterceptor extends it: https://stackoverflow.com/a/41979280/3004282 As you can see in this answer there is some cacheManager where the put methods have also the ttl. For Ehcache it's not possible, but there is other provider – EFOE Sep 12 '19 at 12:57

1 Answers1

0

The cache abstraction does not provide any abstraction with regards to configuration, see the documentation.

If you want to go down that road, you should inject the CacheManager in your code, get the Cache and access its NativeCache property and use cache-library specific code to apply the TTL.

Stephane Nicoll
  • 31,977
  • 9
  • 97
  • 89