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

11 篇文章 0 订阅

配置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上面。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值