DEV Community

Cover image for Building an API To Clear All the Caches of Your Spring Boot Application
Antonello Zanini for Writech

Posted on • Originally published at writech.run

Building an API To Clear All the Caches of Your Spring Boot Application

Caching improves performance but introduces the coherence problem as well. This is why, after enabling caching in my Spring Boot application, I realized how important it is to provide a procedure to clear all the caches on-demand.

Logging into your server to manually release all the cached data by your application should be the last and desperate option. As a consequence, I started looking for methods to offer administrators a reliable and secure way to clear all the caches when needed. Fortunately, you can easily achieve that with a few lines of code.

Let's see how to define a custom API aimed at evicting the caches of your Spring Boot application.

Building the API

Let's assume that your application already uses a cache engine, employing the Spring Cache module.

To deal with cache, Spring internally creates a CacheManager bean on startup. Although Spring does not provide a feature to clear all the caches on-demand, you can achieve this by harnessing this cache manager.

In fact, its getCacheNames() method returns the collection of the cache names known by your manager. By iterating over them, you can retrieve each Cache instance that it is currently handling, and call the clear() method on each of them.

With this simple approach, you can define a safe way to clear all the caches used in your Spring Boot Application. This is why designing an API to achieve such a goal is not complex. You can implement it as follows:

Java

@RestController
@RequestMapping("/caches")
public class CachingController {
    @Autowired
    private CacheManager cacheManager;

    @DeleteMapping("clear")
    public ResponseEntity<Void> clearAllCaches() {
        cacheManager
                .getCacheNames()
                .stream()
                .forEach(cacheName -> cacheManager.getCache(cacheName).clear());
    }
}
Enter fullscreen mode Exit fullscreen mode

Kotlin

@RestController
@RequestMapping("/caches")
class CachingController {
    @Autowired
    private lateinit var cacheManager: CacheManager

    @DeleteMapping("clear")
    fun clearCache() : ResponseEntity<Void> {
        cacheManager.cacheNames.forEach { name: String? ->
            name?.let {
                cacheManager.getCache(
                    name
                )?.clear()
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

In both cases, you just need to auto-wire the implemented CacheManager bean and follow the aforementioned approach. By encapsulating this logic in an exposed endpoint you are actually defining a trigger, which can be activated whenever the API is called.

Please, note that the cache will be initialized only when the first entry is inserted. This means that you will not see any cache available in CacheManager before any data is cached.

Plus, only a few selected users should be allowed to access this API. This is why I recommend implementing a custom authentication system. For further reading, you can check out my previous articles, where I showed how to achieve such a goal in Spring Boot.

Conclusion

Dealing with cache might introduce problems that only a complete clean-up can solve. This is exactly why you should protect yourself by adding some administration tools. As I have shown, implementing an API to clear all the caches of your Spring Boot application is not complex, and in most cases, it can save your day.

Thanks for reading! I hope that you found this article helpful.


The post "Building an API To Clear All the Caches of Your Spring Boot Application" appeared first on Writech.

Top comments (0)