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

  • 相关阅读:
    Javascript进阶(7)---函数参数
    Django连接mssql(SqlServer)
    ORM查询
    Django-Model操作数据库
    Django去操作已经存在的数据库
    如何设置CentOS 7获取动态及静态IP地址
    nginx代理设置
    Django+Linux+Uwsgi+Nginx项目部署文档
    nginx的安装部署
    Django项目在linux系统中虚拟环境部署
  • 原文地址:https://www.cnblogs.com/dw039/p/14121788.html
Copyright © 2020-2023  润新知