I am using Spring Boot and for caching I am using Ehcache. It’s working fine till now. But now I have to reload / refresh so how can I do this so that my application will not be having any downtime.
I have tried many ways in Spring Ehcache but it didn’t work or Else have to write a scheduler and reload the data.
@Override
@Cacheable(value="partTypeCache", key="#partKey")
public List<PartType> loadPartType(String partKey) throws CustomException {
return productIdentityDao.loadPartType();
}
6
Answers
Try something like this, as mentioned in comments also:
Apparently all the comments about your problem were right. You should use CacheEvict. I found solution here: https://www.baeldung.com/spring-boot-evict-cache and it looks like this:
All you have to do is create class called e.g. CacheService and create method that will evict all cached objects you have. Then you annotate that method @Scheduled and put your interval rate.
Do you know what partKeys you are looking to renew specifically? If you don’t, you’ll have to find the keys from the cache itself. You can use @CachePut to update cache values with no downtime. The performance of my suggestion will not be great, but it should do exactly what you’re looking for.
For EhCache specifically:
To be clear, the worst part of this is getting keys from the existing cache. If you have a short list of "hot" parts that you’re wanting to keep in cache, you could just call updatePartTypeCache for those instead.
The option suggested by many to use
@CacheEvict
is correct. Additionally, to ensure your cache (near) always has latest data loaded, even if data is updated in database out of bounds to your running app, you need to reload the whole dataset periodically with an interval matching your app’s SLAs. In the solution suggested above, add logic to reload all data like below:Apart from above answers you can use cron inside your scheduler which gives more flexibility. you can have a scheduler running daily,weekly ,yearly,daily at 12pm etc whiout writing much code.
@Service
public class CacheService {
}
The requirement is to refresh 1 cache at X interval and another cache at Y interval. If we write the below code in only 1 class then the cache NOT gets reloaded.