springboot 整合 ehcahe后,实现缓存数据 应用关闭时序列化(磁盘持久化),重启再加载

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数据是否还在吧!

 

posted @ 2020-12-11 18:13  DW039  阅读(1519)  评论(0编辑  收藏  举报