Can I set a TTL for @Cacheable by key?

Viewed 484

I use @Cacheable(name = "rates", key = "#car.name")

Can I set up a TTL for this cache? and the TTL is by the car.name?

for example

I want to set name = "rates" TTL 60 secs running the java:

time: 0 car.name = 1, return "11" time: 30 car.name = 2, return "22"

time: 60 car.name = 1 key should be gone.
time: 90 car.name = 2 key should be gone.

and I want to set multiple TTL for multiple names.

name = "rates2" TTL 90 secs.

1 Answers

You can't @Cacheable is static configuration and what you want is more on the dynamic side. Keep in mind that Spring just provides abstraction that is supposed to fit all providers. You should either specify different regions for the different entries, or do a background process invalidating the keys that need invalidation.

Time to live setting is on per region basis when statically configured.

If you walk away from the static configuration you can set expiration while inserting an entry , but then you are getting away from spring(one size to fit them all remember) and entering the territory of the caching provider which can be anything Redis, Hazelcast,Ehcache,infinispan and each will have different contract

Here is example contract of IMap interface from Hazelcast:

IMap::put(Key, Value, TTL, TimeUnit) 

But this has nothing to do with spring.

With Spring means you can do the following:

    @Cacheable(name="floatingRates")
List<Rate> floatingRates;
    @Cacheable(name="fixedRates")
List<Rate> fixedRates;

and then define TTL for each.

Related