This Spring library provides the CacheableAutoRefreshed annotation which extends the functionality of Spring's Cacheable annotation, to automatically refresh the cache at a specified point/interval in time.
-
Scheduling has to be enabled (see Enable Support for Scheduling)
-
Caching has to be enabled (see Enable Caching)
-
Add the dependency to your
pom.xml
:<dependency> <groupId>io.github.philkes</groupId> <artifactId>spring-cache-refresh-annotation</artifactId> <version>1.0.0</version> </dependency>
Note: The needed Spring Beans are autoconfigured by CacheableAutoRefreshedConfiguration
-
Annotate a method with the
@CacheableAutoRefreshed
annotation (see e.g. TestBean):@CacheableAutoRefreshed(cacheNames = "someCache", fixedDelay = 10000) public String fetchSomeData(String parameter) { return someService.fetchData(parameter); }
In this example
fetchSomeData
return values will be cached with the default behaviour of@Cacheable
and the cached values will be refreshed every 10 seconds.The cache stays stable even while refreshing.
- Spring's Simple Caching with
ConcurrentHashMap
(synchronously reloads all cached entries) - Caffeine (utilizes the async reloading of all cache entries via LoadingCache.refreshAll())
- TODO: Redis
- TODO: JCache
To configure the caching itself, the @CacheableAutoRefresh
provides the same annotation parameters as @Cacheable
(see Spring/Cacheable) as well as all the parameters from the @Scheduled
annotation (see Spring/Scheduled), to specify when the cache should be refreshed (e.g. via a duration interval, cron expression)
- Built with Java 17
- Spring-Framework for
spring-context
,spring-boot-autoconfigure
- Mockito for mocking tests
- Awaitility for testing spring scheduled tasks
This project is licensed under the terms of the Apache 2.0 license.