Jac*_*Dev 10 java caching hibernate ehcache
我正在使用ehcache 2.5.4.
我有一个对象需要在白天缓存,并在每天00:00 am刷新一个新值.
目前使用ehcache配置我只能设置生存时间和空闲时间,但这取决于我创建对象的时间或使用时间.即:
<cache
name="cache.expiry.application.date_status"
maxElementsInMemory="10"
eternal="false"
timeToIdleSeconds="60"
timeToLiveSeconds="50" />
Run Code Online (Sandbox Code Playgroud)
有没有办法让ehcache根据特定时间使特定缓存过期.
min*_*das 10
我这样做是通过扩展Ehcache的Element类来实现的:
class EvictOnGivenTimestampElement extends Element {
private static final long serialVersionUID = ...;
private final long evictOn;
EvictOnGivenTimestampElement(final Serializable key, final Serializable value, final long evictOn) {
super(key, value);
this.evictOn = evictOn;
}
@Override
public boolean isExpired() {
return System.currentTimeMillis() > evictOn;
}
}
Run Code Online (Sandbox Code Playgroud)
其余的就像将新的EvictOnGivenTimestampElement对象实例放入缓存而不是Element.
这种方法的优点是你不必担心外部cronjobs等.明显的缺点是Ehcache API的附件,我希望不会经常改变.
EHCache 仅支持在一段时间后(在缓存中或由于不活动)后驱逐。但是,您应该能够通过使用以下内容安排删除来轻松完成此操作:
Timer t = new Timer(true);
Integer interval = 24 * 60 * 60 * 1000; //24 hours
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
t.scheduleAtFixedRate( new TimerTask() {
public void run() {
Cache c = //retrieve cache
c.removeAll();
}
}, c.getTime(), interval);
Run Code Online (Sandbox Code Playgroud)
这个基本示例使用 Java Timer 类来说明,但可以使用任何调度程序。每 24 小时,从午夜开始 - 这将运行并从指定的缓存中删除所有元素。run可以修改实际方法以删除符合特定条件的元素。
您只需要确保在应用程序启动时启动它。
| 归档时间: |
|
| 查看次数: |
5449 次 |
| 最近记录: |