Expand Authors Top

If you have a few years of experience in the Java ecosystem and you’d like to share that with the community, have a look at our Contribution Guidelines.

Expanded Audience – Frontegg – Security (partner)
announcement - icon User management is very complex, when implemented properly. No surprise here.

Not having to roll all of that out manually, but instead integrating a mature, fully-fledged solution - yeah, that makes a lot of sense.
That's basically what Frontegg is - User Management for your application. It's focused on making your app scalable, secure and enjoyable for your users.
From signup to authentication, it supports simple scenarios all the way to complex and custom application logic.

Have a look:

>> Elegant User Management, Tailor-made for B2B SaaS

November Discount Launch 2022 – Top
We’re finally running a Black Friday launch. All Courses are 30% off until tomorrow:

>> GET ACCESS NOW

November Discount Launch 2022 – TEMP TOP (NPI)
We’re finally running a Black Friday launch. All Courses are 30% off until tomorrow:

>> GET ACCESS NOW

1. Overview

In this quick tutorial, we'll learn how to perform cache eviction using Spring. To demonstrate this, we'll create a small example.

Before proceeding, check out our article, Guide To Caching in Spring, to get familiar with how Spring caching works.

2. How to Evict a Cache?

Spring provides two ways to evict a cache, either by using the @CacheEvict annotation on a method, or by auto-wiring the CacheManger and clearing it by calling the clear() method.

Here's how we can implement these two cache eviction mechanisms in code.

2.1. Using @CacheEvict

Let's create an empty method with the @CacheEvict annotation, and provide the cache name that we want to clear as an argument of the annotation. In this case, we want to clear the cache with the name “first”:

@CacheEvict(value = "first", allEntries = true)
public void evictAllCacheValues() {}

Spring will intercept all the methods annotated with @CacheEvict and clear all the values based on the allEntries flag.

It's also possible to evict values based on a particular key. For this, all we have to do is pass the cache key as an argument to the annotation, instead of the allEntries flag:

@CacheEvict(value = "first", key = "#cacheKey")
public void evictSingleCacheValue(String cacheKey) {}

Since the value of the key attribute is dynamic, we can either use Spring Expression Language, or a custom key generator by implementing KeyGenerator to pick the arguments of interest or the nested properties.

2.2. Using CacheManager

Next, let's look at how we can evict the cache using the CacheManager provided by the Spring Cache module. First, we have to auto-wire the implemented CacheManager bean.

Then we can clear the caches with it based on our needs:

@Autowired
CacheManager cacheManager;

public void evictSingleCacheValue(String cacheName, String cacheKey) {
    cacheManager.getCache(cacheName).evict(cacheKey);
}

public void evictAllCacheValues(String cacheName) {
    cacheManager.getCache(cacheName).clear();
}

As we can see in the code, the clear() method will clear all the cache entries, and the evict() method will clear values based on a key.

3. How to Evict All Caches?

Spring doesn't provide an out of the box functionality to clear all the caches, but we can achieve this easily by using the getCacheNames() method of the cache manager.

3.1. Eviction on Demand

Now let's see how we can clear all the caches on demand. In order to create a trigger point, we have to expose an endpoint first:

@RestController
public class CachingController {
	
    @Autowired
    CachingService cachingService;
	
    @GetMapping("clearAllCaches")
    public void clearAllCaches() {
        cachingService.evictAllCaches();
    }
}

In the CachingService, we can then clear all the caches by iterating over the cache names obtained from the cache manager:

public void evictAllCaches() {
    cacheManager.getCacheNames().stream()
      .forEach(cacheName -> cacheManager.getCache(cacheName).clear());
}

3.2. Automatic Eviction

There are certain use cases where cache eviction should be performed automatically at certain intervals. In this case, we can make use of the Spring's task scheduler:

@Scheduled(fixedRate = 6000)
public void evictAllcachesAtIntervals() {
    evictAllCaches();
}

4. Conclusion

In this article, we learned how to evict caches in different ways. One of the things worth noting about these mechanisms is that it'll work with all of the various cache implementations, like eh-cache, infini-span, apache-ignite etc.

As always, all the examples mentioned in this article can be found over on Github.

November Discount Launch 2022 – Bottom
We’re finally running a Black Friday launch. All Courses are 30% off until tomorrow:

>> GET ACCESS NOW

Generic footer banner
Comments are closed on this article!