使用ehcache持久化數據到磁盤 並且在應用服務器重啟后不丟失數據


使用ehcache時如何持久化數據到磁盤,並且在應用服務器重啟后不丟失數據
1、如何持久化到磁盤
使用cache.flush(),每次寫入到cache后調用cache.flush() ,這樣ehcache 會將索引(xxx.index)回寫到磁盤。這樣就不用擔心程序是否非正常退出導致緩存丟失了。

2、附上配置文件修改:

 

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="ehcache.xsd" name="ehcache">
    <cacheManagerPeerProviderFactory
        class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory"
        properties="peerDiscovery=manual"/>

    <diskStore path="d:/ehcache"/>
    <cache name="submitProcessInst" maxElementsInMemory="1" eternal="true"
        overflowToDisk="true" diskSpoolBufferSizeMB="10" maxElementsOnDisk="1000000"
        diskPersistent="true" memoryStoreEvictionPolicy="LRU">
        <cacheEventListenerFactory
            class="net.sf.ehcache.distribution.RMICacheReplicatorFactory" />
        <!-- 比一般配置多了這個 -->
        <bootstrapCacheLoaderFactory class="net.sf.ehcache.distribution.RMIBootstrapCacheLoaderFactory"/>
    </cache>

</ehcache>

 

注意:當不需保存數據在內存中時,將maxElementsInMemory="1",而不是0,設置為0時,可以看到ehcache有warning:
2015-03-10 10:44:28,469 WARN  net.sf.ehcache.config.CacheConfiguration.warnMaxEntriesLocalHeap(CacheConfiguration.java:1601) - Cache: submitProcessInst has a maxElementsInMemory of 0. This might lead to performance degradation or OutOfMemoryError at Terracotta client.From Ehcache 2.0 onwards this has been changed to mean a store with no capacity limit. Set it to 1 if you want no elements cached in memory

3、系統初始化時添加:
System.setProperty(net.sf.ehcache.CacheManager.ENABLE_SHUTDOWN_HOOK_PROPERTY,"true");

另外,持久化到硬盤的對象都需要是可序列化的,用以下方法處理:
a)如果類是你自己的,把他設置成可序列化
b)如果類中的某些屬性是是第三方jar包的類,可以將它的字段設置成transient(不需序列化)
c)如果類中的某些屬性是是第三方jar包但你一定要將所有屬性都序列化,可以考慮將這些屬性轉化成json等

注意本文轉載 未親自驗證

http://www.myexception.cn/web-application-server/1874474.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM