日期:2014-05-16  浏览次数:20441 次

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

http://kangzye.blog.163.com/blog/static/3681922320113881344329/

?

? ? ? 公司让做一个项目,客户提交一批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>

1 楼 w11h22j33 2011-11-01  
Ehcache和MemCached比较分析
http://www.zoomhoo.com/thread-831-1-1.html
2 楼 w11h22j33 2011-11-01  
http://sourceforge.net/projects/ehcache/files/