1. Overview

This article is about spring clear all cache or spring cache evict programmatically.  Spring internally create org.springframework.cache.CacheManager bean which help us to manage the cache. Here is an article on how to configure spring cache with the database.

If we want to clear particular cache then @CacheEvict annotation can be used. Here is example of clear cache using @CacheEvict annotation.

2. Ways to clear all cache

  • CacheManager.getCacheNames() return name of all caches which is stored internally by spring cache.
  • CacheManager.getCache() return org.springframework.cache.Cache object which contains actual data. org.springframework.cache.Cache has clear() method using that we can clear cache data.

1. Clear or evict cache programmatically

When we call localhost:[port]/clearCache it will evict all cache.

package com.javadeveloperzone.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Created by JavaDeveloperZone on 30-04-2018.
 */
@RestController     // for rest response
public class CacheController {

    @Autowired
    private CacheManager cacheManager;      // autowire cache manager

    // clear all cache using cache manager
    @RequestMapping(value = "clearCache")
    public void clearCache(){
        for(String name:cacheManager.getCacheNames()){
            cacheManager.getCache(name).clear();            // clear cache by name
        }
    }
}

2. Clear or evict cache by the time interval

To delete all cache at every 30 min we have set here,@Scheduled So at every 30 min scheduler will be executed and cache will be cleared. We can write Scheduler inside Controller, Component and Service.

    @Autowired 
    private CacheManager cacheManager;               // autowire cache manager

    @Scheduled(cron = "0 0/30 * * * ?")              // execure after every 30 min
    public void clearCacheSchedule(){
        for(String name:cacheManager.getCacheNames()){
            cacheManager.getCache(name).clear();            // clear cache by name
        }
    }

3. References

Was this post helpful?
Let us know, if you liked the post. Only in this way, we can improve us.
Yes
No

Leave a Reply

Your email address will not be published. Required fields are marked *