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

来源:互联网 发布:边伯贤2017知乎 编辑:程序博客网 时间:2024/04/29 15:30

配置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缓存的时候会调用这个方法@Overridepublic 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缓存的时候会调用这个方法@Overridepublic 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上面。

0 0
原创粉丝点击