Pages

How to clear cache in SpringBoot java

 Clear or evict all cache Programmatically.

Does Java provide something which can clear all the cache at once?👆👆👆👆❓❓❓

The answer is NO 👎👎👎😕😕😕.

Java does not provide any such feature which can clear all the cache at once.👍👍👍👍

So how do clear all the cache?😞😞😞

We have a solution which we can use to achieve this,😀😄✌👌

CacheManager class has a method name getCacheNames() returns the name of the cache, and after that we use clear() to clear that cache.

we use this method to achieve our goal to clear all the cache.

CacheManager.getCacheNames().

CacheManager.getCache(cacheName).clear

Find the code below 👇👇👇👍

@Controller
@CrossOrigin("*")
@RequestMapping("javaoneworld")
public class JavaOneWorldController {

	/* autowire cache manager */
	@Autowired
    private CacheManager cacheManager;      
    
	/* clear all cache using cache manager */
    @RequestMapping(path = "/clearCache")
    public ResponseEntity<String> clearCache(){
    	
    	if(cacheManager.getCacheNames().isEmpty()) {
    		return ResponseEntity.status(HttpStatus.NOT_FOUND).body("No cache record has been found");
    	}else {

        	
            for(String name:cacheManager.getCacheNames()){
            	/* printing cache name */
                System.out.println(name);
				
    			/* clear cache by name */
                cacheManager.getCache(name).clear();
				
            }
    		return ResponseEntity.status(HttpStatus.OK).body("All cache has been cleared");
    	}
    }
	

}

 

Find another must-read post.


 

17 comments:

  1. Thankyou for the information given here and I want some data about clear cache google chrome

    ReplyDelete