在项目中使用了ehcache后,从Ehcache中取出缓存的对象,之后将对象中的属性进行了修改使用。等再次从缓存中拿到对象后,发现对象的值变成了上一次调用修改后的对象了。
终于找问题所在了;Ehcache中缓存的是原对象的引用,所以引用的内容被修改后cache内部的值也会被修改。
Ehcache提供了copyOnRead="true" copyOnWrite="true"的配置属性。
作用是在读取或写入数据时,不使用原始数据,而是使用拷贝数据。
但是在使用该配置的时候,还要提供copyStrategy class属性,提供Copy策略。
<cache name="boUigroup"
maxEntriesLocalHeap="2000"
eternal="false"
timeToIdleSeconds="3600"
timeToLiveSeconds="0"
overflowToDisk="false"
statistics="true"
copyOnRead="true"
copyOnWrite="true"
>
<copyStrategy class="com.binkai.cache.EhcacheCopyStrategy"/>
</cache>
copy策略类
public class EhcacheCopyStrategy implements ReadWriteCopyStrategy<Element> {
@Override
public Element copyForWrite(Element element, ClassLoader classLoader) {
if(element!=null){
Object temp=element.getObjectValue();
try {
return new Element(element.getObjectKey(),deepCopy(temp));
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
return element;
}
private Object deepCopy(Object temp) throws IOException, ClassNotFoundException {
ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
ObjectOutputStream out=new ObjectOutputStream(byteArrayOutputStream);
out.writeObject(temp);
ByteArrayInputStream byteArrayInputStream=new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
ObjectInputStream in=new ObjectInputStream(byteArrayInputStream);
return in.readObject();
}
@Override
public Element copyForRead(Element element, ClassLoader classLoader) {
if(element!=null){
Object temp=element.getObjectValue();
try {
return new Element(element.getObjectKey(),deepCopy(temp));
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
return element;
}
}
通过以上处理;问题终于解决了
本文暂时没有评论,来添加一个吧(●'◡'●)