I am caching with Spring cache. How to clear cache without Scheduled Job?
You can always clear the Cache
manually.
For example, let's suppose you have a shared, distributed cache solution (e.g. Hazelcast, or Redis) and want to clear a specific, "named" cache when your Spring [Boot] application shuts down.
Then, you could do something like this:
@SpringBootApplication
public class MyCachingSpringBootApplication {
public static void main(String[] args) {
SpringApplication.run(MyCachingSpringBootApplication.class, args);
}
private static final Set<String> namedCachesToClear =
new HashSet<>(Arrays.asList("CacheOne", "CacheTwo"));
@Autowired
private final CacheManager cacheManager;
@EventListener
public void clearTargetCaches(ApplicationClosedEvent event) {
this.cacheManager.getCacheNames().stream()
.filter(namedCachesToClear::contains)
.map(cacheName -> this.cacheManager.getCache(cacheName))
.filter(Objects::nonNull)
.forEach(Cache::clear);
}
}
Of course, you can source the name of the caches you want to clear from anywhere, such as Spring Boot application.properties
, or dynamically, if your application creates and uses caches dynamically, whatever.
The primary API's involved come from the CacheManager
interface (Javadoc) and Cache
interface (Javadoc) in the core Spring Framework Cache Abstraction.
However, a word of caution, Spring's Cache Abstraction is a SPI and facade for uniformly interfacing with and using different caching providers, such as Hazelcast or Redis (see complete list of supported caching providers in the Spring Boot documentation).
Therefore, you should exercise caution when using Cache.clear()
(Javadoc) since this can have many important implications, depending on the caching provider in use (again, Hazelcast, Redis, other) as well as the topology you are using (embedded, client/server, multi-site) as well as other factors.
Choose caution when using Cache.clear()
.
It would be better to set expiration and eviction policies instead, which again, vary from 1 caching provider to another.
Good luck!
You can use the @CacheEvict annotation to remove entries from the cache when a specific method is called.
@CacheEvict(cacheNames = "myCache", key="#id")
public void clearCacheById(Long id) {
//...
}
You can use the CacheManager interface to access the cache and clear it manually. For example, you can add the following code to a method:
@Autowired
private CacheManager cacheManager;
public void clearCache() {
cacheManager.getCache("myCache").
clear();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With