I am using Spring Boot 2.0.4.RELEASE version with Cache Enabled with default cache provider only No external Cache provider is used.
I have scheduled a batch which run at a specific time everyday. During its run certain method calls which involves Data Access are cached and it works fine.
Now I want to release all the cached items before the next start of function at the scheduled time.
I am not able to implement this feature. Can you all guide me to few ideas or way how to implement it.
This is what I am trying to Implement. I have a JobExecutionListener class marked as @Configuration. I am using its afterJob method to clear all the caches.
@Configuration
@JobScope
public class JobTwoExecutionListener implements JobExecutionListener {
private static final Logger logger = LoggerFactory.getLogger(JobTwoExecutionListener.class);
@Autowired
private CacheManager cacheManager;
@Override
public void beforeJob(JobExecution jobExecution) {
final String methodName = "beforeJob() : ";
logger.info(methodName + "called");
if(cacheManager == null) return;
logger.info(methodName + "CacheManager FOUND. Listing all the caches
before Job Run");
for(String name : cacheManager.getCacheNames()){
logger.info(methodName + "CACHE_NAME BEFORE JOB " + name);
}
}
@Override
public void afterJob(JobExecution jobExecution) {
final String methodName = "afterJob() : ";
logger.info(methodName + "called");
performCacheCleanup();
}
private void performCacheCleanup(){
final String methodName = "performCacheCleanup() : ";
logger.info(methodName + "called");
if(cacheManager == null){
logger.info(methodName + "CacheManager NOT FOUND");
return;
}
logger.info(methodName + "CacheManager FOUND. Listing & clearing all the caches after Job Run");
for(String name : cacheManager.getCacheNames()){
if(name == null) continue;
logger.info(methodName + "CLEARING CACHE " + name + " AFTER JOB");
Cache cache = cacheManager.getCache(name);
if(cache != null) cache.clear();
}
}
}