天天看點

使用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

繼續閱讀