您的位置:首页 > 其它

关于ehCache配置timeToLiveSeconds失效的问题总结

2016-12-22 12:30 357 查看
配置timeToLiveSeconds之前首先配置eternal="false" ,我想要的效果是timeToLiveSeconds="10"10秒失效,但是测试发现一直没有效果,一直缓存活在内存中

我的配置文件:

    <cache name="busCache"  

           maxElementsOnDisk="20000"  

           maxElementsInMemory="20000"  

           eternal="false"

           timeToLiveSeconds="10"

           overflowToDisk="false"  

           diskPersistent="false"

           copyOnRead="true"

           copyOnWrite="true"

           memoryStoreEvictionPolicy="LRU"

           >

           <copyStrategy class="com.shanjin.ehCache.util.MyCopyStrategy" />

    </cache>  

看到里面copyStrategy了吗,是为了不自动更新cache里面的值,具体原因参照这里http://blog.csdn.net/haiyang4988/article/details/53334352

import java.io.Serializable;

import net.sf.ehcache.Element;
import net.sf.ehcache.store.compound.ReadWriteCopyStrategy;

/**
* @author CUIJIAJUN
*
* @date 2016年11月24日 下午2:52:03
*
*/
public class MyCopyStrategy implements ReadWriteCopyStrategy<Element> {
//当write缓存的时候会调用这个方法
@Override
public Element copyForWrite(Element value) {
if(value != null){
System.out.println("value==="+value);
Object temp=(Serializable)value.getObjectValue();
value.setEternal(false);
value.setTimeToLive(5);
return new Element(value.getObjectKey(),temp);
}
return value;
}
//当read缓存的时候会调用这个方法
@Override
public Element copyForRead(Element storedValue) {
if(storedValue != null){
System.out.println("storedValue==="+storedValue);
Object temp=(Serializable)storedValue.getObjectValue();
return new Element(storedValue.getObjectKey(),temp);
}
return storedValue;
}
}


但是实现了这个接口之后,配置文件里面的timeToLiveSeconds="10"就无效了,原因就是在我的自定义实现MyCopyStrategy里面也需要设置“ value.setTimeToLive(5);"  不设置就无效

解决方案:

那么现在要么不要配置copyStrategy,要么在copyStrategy实现里面手动设置value.setTimeToLive(5)。

每个cache配置不同的copyStrategy,然后实现类当中设置失效时间即可,不能一个copyStrategy用在全部cache上面。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息