Java 缓存之Ehcache 的源码 write 方法了解

本文详细解析了Ehcache如何实现元素的字节写入,并提供了自定义写入方法的步骤,包括修改主类、重写write方法及重新发布。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

话说这个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 的写文件的方法了。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值