zoukankan      html  css  js  c++  java
  • springBoot整合Ehcache——工具类调用

      项目需求要缓存常用数据,整合Ehcache实现,结果@Cacheable注解怎么都不管用,网上找了很多资料各种试各种不行,无奈!只好写个工具类使用。

    一、pom.xml配置

    <dependency>
        <groupId>org.ehcache</groupId>
        <artifactId>ehcache</artifactId>
        <version>${ehcache.version}</version>
    </dependency>
    <dependency>
        <groupId>net.sf.ehcache</groupId>
        <artifactId>ehcache</artifactId>
    </dependency>

    二、ehcache.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
             name="taxiEhcache" updateCheck="false">
    
        <!-- 磁盘缓存位置 -->
        <diskStore path="java.io.tmpdir"/>
    
        <!--
         缓存配置
           name:                            缓存名称。
           maxElementsInMemory:            缓存最大个数。
           eternal:                         对象是否永久有效,一但设置了,timeout将不起作用。
           timeToIdleSeconds:              设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。
           timeToLiveSeconds:              设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。
           overflowToDisk:                 当内存中对象数量达到maxElementsInMemory时,Ehcache将会对象写到磁盘中。
           diskSpoolBufferSizeMB:          这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。
           maxElementsOnDisk:              硬盘最大缓存个数。
           diskPersistent:                 是否缓存虚拟机重启期数据 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.
           diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。
           memoryStoreEvictionPolicy:      当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。
           clearOnFlush:                   内存数量最大时是否清除。
         -->
        <!-- 默认缓存 -->
        <defaultCache eternal="false"
                      maxElementsInMemory="1000"
                      overflowToDisk="false"
                      diskPersistent="false"
                      timeToIdleSeconds="0"
                      timeToLiveSeconds="600"
                      memoryStoreEvictionPolicy="LRU">
        </defaultCache>
    
        <cache name="taxiCache"
               maxEntriesLocalHeap="10000"
               eternal="false"
               timeToIdleSeconds="0"
               timeToLiveSeconds="0"
               overflowToDisk="false"
               statistics="true">
        </cache>
    
    </ehcache>
        

    三、编写工具类

    public class EhCacheUtil {
    
        private static final Logger log = LoggerFactory.getLogger(EhCacheUtil.class);
    
        private static final String PATH = ClassUtils.getDefaultClassLoader().getResource("").getPath()+"ehcache/ehcache.xml";
        private CacheManager manager;
        private static EhCacheUtil ehCache;
    
        public static final String TAXI_CACHE = "taxiCache";
        public static final String GROUP_TREE_KEY = "groupTreeList";
        public static final String GROUP_VEHICLE_TREE_KEY = "groupVehicleTreeList";
    
        /**
         * 获得缓存配置管理
         * @param path
         */
        private EhCacheUtil(String path) {
            try {
                manager = CacheManager.create(path);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("获取配置文件错误:{}",e.getMessage());
            }
        }
    
        /**
         * 初始化缓存管理类
         * @return
         */
        public static EhCacheUtil getInstance() {
            try {
                if (ehCache== null) {
                    ehCache= new EhCacheUtil(PATH);
                }
            } catch (Exception e) {
                e.printStackTrace();
                log.error("初始化错误:{}",e.getMessage());
            }
            return ehCache;
        }
    
        /**
         * 获取Cache类
         * @param cacheName
         * @return
         */
        public Cache getCache(String cacheName) {
            return manager.getCache(cacheName);
        }
    
        /**
         * 添加缓存数据
         * @param cacheName
         * @param key
         * @param value
         */
        public void put(String cacheName, String key, Object value) {
            try {
                Cache cache = manager.getCache(cacheName);
                Element element = new Element(key, value);
                cache.put(element);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("添加缓存失败:{}",e.getMessage());
            }
        }
    
        /**
         * 获取缓存数据
         * @param cacheName
         * @param key
         * @return
         */
        public Object get(String cacheName, String key) {
            try {
                Cache cache = manager.getCache(cacheName);
                Element element = cache.get(key);
                return element == null ? null : element.getObjectValue();
            } catch (Exception e) {
                e.printStackTrace();
                log.error("获取缓存数据失败:{}",e.getMessage());
                return null;
            }
        }
    
        /**
         * 删除缓存数据
         * @param cacheName
         * @param key
         */
        public void delete(String cacheName, String key) {
            try {
                Cache cache = manager.getCache(cacheName);
                cache.remove(key);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("删除缓存数据失败:{}",e.getMessage());
            }
        }
    }

    四、调用

    1、存数据

    EhCacheUtil ehCacheUtil = EhCacheUtil.getInstance();
    ehCacheUtil.put(ehCacheUtil.TAXI_CACHE,ehCacheUtil.GROUP_VEHICLE_TREE_KEY,ztrees);

    2、取数据

    ztrees = (List<Ztree>) ehCacheUtil.get(ehCacheUtil.TAXI_CACHE,ehCacheUtil.GROUP_VEHICLE_TREE_KEY);

    3、删除缓存

    ehCacheUtil.delete(ehCacheUtil.TAXI_CACHE,ehCacheUtil.GROUP_TREE_KEY);
  • 相关阅读:
    如何在Windows下安装sass和compass
    HTTP 请求头中的 X-Forwarded-For
    HTTP 代理原理及实现
    node.js使用经验记录
    完美方案——iOS的WebView自适应内容高度
    购物车商品加减效果
    C++17新特性
    栈实现迷宫求解(c++版)
    二叉树遍历及实现
    经典乱码“烫烫烫”和“屯屯屯”
  • 原文地址:https://www.cnblogs.com/pengjf/p/11090924.html
Copyright © 2011-2022 走看看