ehcache 让内容一直持久化在磁盘,防止异常丢失

公司让做一个项目,客户提交一批100万的数据上来,程序异步保存提交上来的数据。
于是我把这100万数据缓存在ehcache 里,一开始,保存进去的数据只能读取一次,强行关闭tomcat ,再次读取,缓存的内容就丢失了。经过多次测试发现,当调用 cache.getValue(key) 方法时,xxx.index 文件大小变为0了(我测试只有一条element,取一个即将全部取出,故为0),如果程序非正常关闭,那么xxx.index 文件就永久为0了,xxx.data 倒是还有内容。如果程序正常退出(会触发ehcache 的 despose事件),则xxx.index 索引文件恢复原来的大小。
        后来经过多次测试,发现,cache.flush() 也有效果,于是在每次cache.getValue(key)之后立马执行一下 cache.flush() ,这样ehcache 会将索引(xxx.index)回写到磁盘。这样就不用担心程序是否非正常退出导致缓存丢失了。
附上配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<ehcache>
    <diskStore path="mmsehcache" />

    <defaultCache maxElementsInMemory="10000" eternal="true"
        overflowToDisk="true" />
    <cache 
        name="mms" 
        maxElementsInMemory="0" 
        eternal="true"
        overflowToDisk="true" 
        diskPersistent="true" 
        memoryStoreEvictionPolicy="LFU" >
        <cacheEventListenerFactory class="com.fractal.gateway.util.EhcacheListenerFactory" properties=""/><!--此为监听事件,可去掉-->
    </cache>
</ehcache>

猜你喜欢

转载自blog.csdn.net/q1054261752/article/details/78691357