Can Spring @Cacheable be configured to block cache gaps?

Is it possible to configure Spring @Cacheable so that if there are no cache gaps to the cached method, it will be blocked until the caching method is executed once and the cache is full?

In my case, I am dealing with data from db that does not change often actually, if this data changes, the application will need to be restarted. I can create @PostConstruct methods and initialize the data as each service starts, but it does not seem "elegant" like the @Cacheable annotation.

I plan to use EhCache with Spring @Cacheable annotation.

update:

Here are some issues that I encountered when trying to use @PostConstruct if anyone else came across these problems. @PostConstruct methods cannot be @Transactional , because they are launched after the properties of the object are set, and not after the Spring context is configured. Thus, you cannot assume that the TX dispatcher is configured and configured at the time the @PostConstruct method is @PostConstruct . The workaround for this is to implement the ApplicationListener and manually enter the TransactionTemplate ... etc. A lot of extra work that is simplified with @Cacheable .

+4
source share
4 answers

I don't think @PostConstruct is inelegant, seems like the perfect solution for me. You want the method to be called only when the application restarts. What could be better?

But you can also do this to block calls until the cache is available

 @Cacheable(cacheName="yourCache", decoratedCacheType= DecoratedCacheType.SELF_POPULATING_CACHE) public List<String> getWhatever(int id) { //call database } 

and make the autorefresh cache as follows:

 @Cacheable(cacheName="yourCache", refreshInterval=1000, decoratedCacheType= DecoratedCacheType.REFRESHING_SELF_POPULATING_CACHE) public List<String> getWhatever(int id) { //call database } 

kudos

+1
source

Support for synchronized caches was added in Spring 4.3:

 @Service public class FooService { @Cacheable(cacheNames = "foos", sync = true) public Foo getFoo(String id) { ... } } 

See: https://spring.io/blog/2016/03/04/core-container-refinements-in-spring-framework-4-3

+2
source

"block on concurrent miss" is supported directly (annoying annotation name) @Cacheable from ehcache-spring -nnotes . Just set selfPopulating = true .

Spring XML configuration is also much cleaner than using spring @Cacheable .

The biggest drawback is that you will be bound to ehcache and will not be able to connect other implementations (for example, useful for unit testing).

+1
source

I have a special problem. When I join sync = true, my cache will no longer have an expiration time in redis, TTL = -1, and there will be an expiration time without overtime

0
source

All Articles