ehcache使用很長時間了,但是卻沒有用到緩存數據序列化(C#中是這么個說法)與再加載。這次因為業務中需要對緩存數據進行臨時存儲並再加載使用,實現該功能的方式多種多樣。既然ehcache有磁盤保存機制,那就用它自帶的功能吧,省時省力。
注意:要使用該功能之前,請先完成ehcache與springboot的整合
1、監聽springboot的關閉事件,並在關閉事件中進行ehcahe緩存的保存。特別注意此處是 net.sf.ehcache.CacheManager,非 org.springframework.cache.CacheManager
import net.sf.ehcache.CacheManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextClosedEvent; import org.springframework.stereotype.Component; @Component public class ApplicationCloseEventListener implements ApplicationListener<ContextClosedEvent> { @Autowired CacheManager cacheManager; @Override public void onApplicationEvent(ContextClosedEvent event) { cacheManager.shutdown(); } }
2、配置ehcache的緩存數據保存路徑
<?xml version="1.0" encoding="UTF-8"?> <ehcache> <!-- 指定一個文件目錄,當EHCache把數據寫到硬盤上時,將把數據寫到這個文件目錄下 --> <diskStore path="D:\ehcache"/> </ehcache>
3、為cache指定 diskPersistent 為true,啟動ehcahe關閉時的數據持久化功能
<?xml version="1.0" encoding="UTF-8"?> <ehcache> <!-- 指定一個文件目錄,當EHCache把數據寫到硬盤上時,將把數據寫到這個文件目錄下 --> <diskStore path="D:\ehcache"/> <!-- 設備Json對象緩存 --> <cache name="JsonObject" maxElementsInMemory="10000" overflowToDisk="false" timeToIdleSeconds="1800" timeToLiveSeconds="3600" memoryStoreEvictionPolicy="LRU" diskPersistent="true"> </cache> </ehcache>
4、為cache指定啟動時的數據加載類工廠
<?xml version="1.0" encoding="UTF-8"?> <ehcache> <!-- 指定一個文件目錄,當EHCache把數據寫到硬盤上時,將把數據寫到這個文件目錄下 --> <diskStore path="D:\ehcache"/> <!-- 設備Json對象緩存 --> <cache name="JsonObject" maxElementsInMemory="10000" overflowToDisk="false" timeToIdleSeconds="1800" timeToLiveSeconds="3600" memoryStoreEvictionPolicy="LRU" diskPersistent="true"> <BootstrapCacheLoaderFactory class="net.sf.ehcache.store.DiskStoreBootstrapCacheLoaderFactory" properties="bootstrapAsynchronously=true" /> </cache> </ehcache>
5、然后運行程序,Run(不是Debug)
6、退出程序,EXIT(不是Stop)
7、查看磁盤文件情況
8、趕快再次運行程序,檢查一下cache數據是否還在吧!