[英]cache implementation on DAO with custom refresh and evictions java
In my application, I have a scenario where I have to refresh cache each 24hrs. 在我的应用程序中,我有一个场景,我必须每24小时刷新一次缓存。 I'm expecting database downtime so I need to implement a use case to refresh cache after 24hrs only if the database is up running.
我预计数据库会停机,因此仅在数据库运行时,我才需要实现一个用例来在24小时后刷新缓存。
I'm using spring-ehache and I did implement simple cache to refresh for each 24 hrs, but unable to get my head around to make the retention possible on database downtime . 我使用的是spring-ehache ,确实实现了每24小时刷新一次的简单缓存,但是却无法动手以确保在数据库停机时进行保留。
Conceptually you could split the scheduling and cache eviction into two modules and only clear your cache if certain condition (in this case, database's healthcheck returns true
) is met: 从概念上讲,您可以将调度和缓存逐出分为两个模块,并且仅在满足某些条件(在这种情况下,数据库的运行状况检查返回
true
)时清除缓存:
SomeCachedService.java : SomeCachedService.java :
class SomeCachedService {
@Autowired
private YourDao dao;
@Cacheable("your-cache")
public YourData getData() {
return dao.queryForData();
}
@CacheEvict("your-cache")
public void evictCache() {
// no body needed
}
}
CacheMonitor.java CacheMonitor.java
class CacheMonitor {
@Autowired
private SomeCachedService service;
@Autowired
private YourDao dao;
@Scheduled(fixedDelay = TimeUnit.DAYS.toMillis(1))
public conditionallyClearCache() {
if (dao.isDatabaseUp()) {
service.evictCache();
}
}
}
Ehcache also allows you to create a custom eviction algorithm but the documentation doesn't seem too helpful in this case. Ehcache还允许您创建自定义逐出算法,但是在这种情况下文档似乎不太有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.