2014-11-04 42 views
1

我想在我的spring mvc web應用程序中使用ehcache。因爲我的服務器每天都會重置,因此我希望緩存是永久的。我是否將它保存在硬路徑中?和鋤保存它? 謝謝。如何在spring中使用ehcache永久緩存mvc

在我的調度員servlet.xml中

我添加此

<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"> 
    <property name="cacheManager" ref="ehcache"/> 
</bean> 
<bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"> 
    <property name="configLocation" value="classpath:ehcache.xml"/> 
    <property name="shared" value="true"/> 
</bean> 

和我ehcach.xml是

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"> 
<diskStore path="c:/tmp"/> 

<defaultCache 
     maxElementsInMemory="500" eternal="true" overflowToDisk="false" memoryStoreEvictionPolicy="LFU"/> 
     <cache name="mycache" 
     maxElementsInMemory="0" 
     eternal="true" 
     timeToIdleSeconds="120" 
     timeToLiveSeconds="120" 
     overflowToDisk="true" 
     maxElementsOnDisk="10000000" 
     diskPersistent="true" 
     diskExpiryThreadIntervalSeconds="1200" 
     memoryStoreEvictionPolicy="LRU"> 
     [1] <persistence strategy="localRestartable" synchronousWrites="false" /> 
     </cache> 

我添加此[1],直到緩存是永久性的,後服務器重置不是remove.but發生此異常元素不允許嵌套元素。 還我使用ehcach-core2.7.0.jar

Element <cache> does not allow nested <persistence> elements. 

回答

0

你試過嗎?

<cache eternal="true" 
    maxElementsInMemory="0" 
    name="<cache name>" 
    overflowToDisk="true"/> 
+0

緩存數據保存在哪裏?我使用來保存它,但是在緩存之後它的大小爲零。 – ali 2014-11-05 06:06:41

+0

你需要發佈一個完整的工作示例供人檢查。這些信息不足以評論正在發生的事情和原因。 – manish 2014-11-05 07:44:11

+0

我編輯我的問題。 – ali 2014-11-05 08:20:48

3

你不應該混合遺產的配置選項 - 與建議persistence元素cache元素的屬性diskPersistentoverflowToDisk

但是,要獲得開源磁盤永久性設置,您需要堅持使用舊版選項。

所以,你的配置應該放下persistence元素成爲:

<cache name="mycache" 
    maxElementsInMemory="0" 
    eternal="true" 
    timeToIdleSeconds="120" 
    timeToLiveSeconds="120" 
    overflowToDisk="true" 
    maxElementsOnDisk="10000000" 
    diskPersistent="true" 
    diskExpiryThreadIntervalSeconds="1200" 
    memoryStoreEvictionPolicy="LRU"> 
</cache> 

不過,你也應該給一個有意義的價值maxElementsInMemory,這樣你就可以有一個熱集,而您不需要的條目在訪問它們時支付反序列化價格。

您還需要決定是否需要永久元素或過期。爲此,請刪除eternal="true"timeToLiveSecondstimeToIdleSeconds對。由於兼容性的原因,兩者在Ehcache中都不是錯誤,但是很難了解您最初的意圖。

作爲最後一條建議,我會將緩存內容移到具有更多描述性名稱而不是c:/tmp的文件夾中。

請注意,開源磁盤持久層不具有容錯能力,因此在執行IO時不正確地關閉CacheCacheManager或異常會損壞數據。如果發生這種情況,您必須先清除數據文件夾,然後才能重新啓動緩存。

有關更多詳細信息,請參閱the Ehcache 2.7 persistence documentation

+0

爲什麼重新運行項目後所有的數據緩存被刪除? – ali 2014-11-05 10:25:49

+0

你可以檢查你的日誌,看看有沒有關於磁盤數據的警告?否則,很難得出任何結論... – 2014-11-05 16:32:02

+0

當我重置服務器的緩存數據保存路徑(C:/ mycache),但當啓動服務器的所有請求不使用緩存。例如:當獲取這個id的請求時,我緩存一個id = 20的請求(20)從db.獲取數據的方法運行的主體,同時緩存這個id。 – ali 2014-11-05 16:52:25