话说这个Ehcache在写element对象的时候,还是很讲究的,实现的是自己的一套字节方式去写的。这个的问题是:我怎么能按照我自己的方式去写呐 ?
个是个问题:
先看原本写的方式:
protected DiskMarker write(Element element) throws IOException {
MemoryEfficientByteArrayOutputStream buffer = serializeElement(element);
int bufferLength = buffer.size();
elementSize = bufferLength;
DiskMarker marker = alloc(element, bufferLength);
// Write the record
final RandomAccessFile data = getDataAccess(element.getObjectKey());
synchronized (data) {
data.seek(marker.getPosition());
data.write(buffer.toByteArray(), 0, bufferLength);
}
return marker;
}
可以看见这个write 方法,调用了另外的一个方法serializeElement(),返回的是一个字节对象MemoryEfficientByteArrayOutputStream.
private MemoryEfficientByteArrayOutputStream serializeElement(Element element) throws IOException {
try {
return MemoryEfficientByteArrayOutputStream.serialize(element);
} catch (ConcurrentModificationException e) {
throw new CacheException("Failed to serialize element due to ConcurrentModificationException. " +
"This is frequently the result of inappropriately sharing thread unsafe object " +
"(eg. ArrayList, HashMap, etc) between threads", e);
}
}
在看看这个serialize 方法,底层调用的是:ObjectOutputStream 对象,O(∩_∩)O哈哈~ 这回算是找到核心了吧。。。。
public static MemoryEfficientByteArrayOutputStream serialize(Serializable serializable) throws IOException {
MemoryEfficientByteArrayOutputStream outstr = new MemoryEfficientByteArrayOutputStream(lastSize);
ObjectOutputStream objstr = new ObjectOutputStream(outstr);
objstr.writeObject(serializable);
objstr.close();
lastSize = outstr.getBytes().length;
return outstr;
}
有此我们就不难看出,要想使用自己的方式来写出element到磁盘上去,那就自己来实现这个方法吧。
具体的做法是:
1. 找到写这个方法对应的主类,DiskStorageFactory ,然后好好研究它是怎么样写磁盘的。
2. 重写这个类中的write方法,按照你的需要去编写。
3. 将写好的类和源码打包,然后重新发布。
通过以上的三个步骤,就可以使用自己的ehcache 的写文件的方法了。