在此时,如果时间限制超过getTimeToLive()
,则cacheManager不会自动刷新private void setCacheInstance() {
cacheManager
.createCache("rateDataCached", CacheConfigurationBuilder
.newCacheConfigurationBuilder(
Integer.class, PostageServicesResultHolder.class,
ResourcePoolsBuilder.heap(100))
.withExpiry(Expirations.timeToLiveExpiration(Duration.of(getTimeToLive(), TimeUnit.MINUTES))).build());
}
private long getTimeToLive() {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("HH.mm");
Float currentTime = Float.parseFloat(sdf.format(cal.getTime()));
return (long) ((24.00-currentTime) * 60);
}
答案 0 :(得分:2)
你可以configure a loader。一旦缓存的值到期,它就会加载新值。
然后,在访问时测试值的到期时间。所以目前不可能在后台使它过期,只使用Ehcache预取它,如果你想做的话。一般来说,无论如何都是不必要的。
如果你真的想这样做,你确实需要你自己的调度程序,它会定期获取值并使其预取(通过使用加载器或放置新值)。
如果你想知道,如果Ehcache在内部进行,我们会安排清道夫和预取任务。所以无论谁做这件事都需要预定的工作。
回答评论。为了使所有条目在午夜到期,您可以使用自定义到期时间来计算每个条目的午夜时间。以下是该示例代码:
Expiry expiry = new Expiry() {
@Override
public Duration getExpiryForCreation(Object key, Object value) {
long msUntilMidnight = LocalTime.now().until(LocalTime.MAX, ChronoUnit.MILLIS);
return Duration.of(msUntilMidnight, TimeUnit.MILLISECONDS);
}
@Override
public Duration getExpiryForAccess(Object key, ValueSupplier value) {
return null;
}
@Override
public Duration getExpiryForUpdate(Object key, ValueSupplier oldValue, Object newValue) {
return null;
}
};
try(CacheManager cm = CacheManagerBuilder.newCacheManagerBuilder()
.withCache("cache",
CacheConfigurationBuilder.newCacheConfigurationBuilder(Integer.class, String.class,
ResourcePoolsBuilder.newResourcePoolsBuilder()
.heap(10))
.withExpiry(expiry))
.build(true)) {
// ...
}
答案 1 :(得分:0)
我尝试使用Expiry类
来使用日历实例公共类CustomExpiry实现Expiry {
@Override
public Duration getExpiryForCreation(Object key, Object value) {
return Duration.of(getTimeToLive(), TimeUnit.MILLISECONDS);
}
@Override
public Duration getExpiryForAccess(Object key, ValueSupplier value) {
return null;
}
@Override
public Duration getExpiryForUpdate(Object key, ValueSupplier oldValue, Object newValue) {
return null;
}
private long getTimeToLive() {
Calendar now = Calendar.getInstance();
Calendar midnight = Calendar.getInstance();
midnight.set(Calendar.HOUR_OF_DAY,0);
midnight.set(Calendar.MINUTE,0);
midnight.set(Calendar.SECOND,0);
midnight.set(Calendar.MILLISECOND,0);
midnight.add(Calendar.DATE, 1);
long difference = midnight.getTimeInMillis() - now.getTimeInMillis();
System.out.println("caching time : "+ difference);
return difference;
}
}