Building an API To Clear All the Caches of Your Spring Boot Application
Tags: java, programming, softwaredevelopment, softwareengineering
Published: 2024-01-19 21:12:36

Caching improves performance but introduces the [coherence problem](https://en.wikipedia.org/wiki/Cache_coherence) 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](https://spring.io/guides/gs/caching/).

To deal with cache, Spring internally creates a [_CacheManager_](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/cache/CacheManager.html) 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()`](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/cache/CacheManager.html#getCacheNames--) method returns the collection of the cache names known by your manager. By iterating over them, you can retrieve each [_Cache_](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/cache/Cache.html) instance that it is currently handling, and call the [`clear()`](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/cache/Cache.html#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

```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());
    }
}
```

#### Kotlin

```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()
            }
        }
    }
}
```

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](https://writech.run/blog/building-an-api-to-clear-all-the-caches-of-your-spring-boot-application-2d0dfdfe71b3/)" appeared first on [Writech](https://writech.run)._