springboot整合ehcache

springboot整合ehcache

工具类实现缓存

1. jar包导入

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

<dependency>
  <groupId>net.sf.ehcache</groupId>
  <artifactId>ehcache</artifactId>
</dependency>

2. 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="myCache"
          maxEntriesLocalHeap="10000"
          eternal="false"
          timeToIdleSeconds="0"
          timeToLiveSeconds="5"
          overflowToDisk="false"
          statistics="true">
   </cache>

</ehcache>

3. 工具类编写

package com.example.ehcachedemo.util;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ClassUtils;

/**
* @title: EhCacheUtil
* @Author bao
* @description
* @Date: 2021/12/1414:03
*/
public class EhCacheUtil {

   private static final Logger log = LoggerFactory.getLogger(EhCacheUtil.class)

   private CacheManager manager;
   private static EhCacheUtil ehCache;

   public static final String MY_CACHE = "myCache";


   /**
    * 获得缓存配置管理
    * @param inputStream
    */
   private EhCacheUtil(InputStream inputStream) {
       try {
           manager = CacheManager.create(inputStream);
      } catch (Exception e) {
           e.printStackTrace();
           log.error("获取配置文件错误:{}",e.getMessage());
      }
  }

   /**
    * 初始化缓存管理类
    * @return
    */
   public static EhCacheUtil getInstance() {
       try {
           //打包部署必须通过流的方式获取配置文件
           ClassPathResource classPathResource = new ClassPathResource("config/ehcache.xml");
           InputStream inputStream = classPathResource.getInputStream();
           if (ehCache== null) {
               ehCache= new EhCacheUtil(inputStream);
          }
      } 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 boolean put(String cacheName, String key, Object value) {
       try {
           Cache cache = manager.getCache(cacheName);
           Element element = new Element(key, value);
           cache.put(element);
           return true;
      } catch (Exception e) {
           e.printStackTrace();
           log.error("添加缓存失败:{}",e.getMessage());
           return false;
      }
  }

   /**
    * 获取缓存数据
    * @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 boolean delete(String cacheName, String key) {
       try {
           Cache cache = manager.getCache(cacheName);
           cache.remove(key);
           return true;
      } catch (Exception e) {
           e.printStackTrace();
           log.error("删除缓存数据失败:{}",e.getMessage());
           return false;
      }
  }

   /**
    * 删除所有缓存数据
    * @param cacheName
    */
   public void delete(String cacheName) {
       try {
           Cache cache = manager.getCache(cacheName);
           cache.removeAll();
      } catch (Exception e) {
           e.printStackTrace();
           log.error("删除缓存数据失败:{}",e.getMessage());
      }
  }


   public static void main(String[] args) {
       EhCacheUtil ehCacheUtil = EhCacheUtil.getInstance();
       ehCacheUtil.put(EhCacheUtil.MY_CACHE,"name","zhangsan");

       String name = (String) ehCacheUtil.get(EhCacheUtil.MY_CACHE, "name");
       System.out.println(name);
  }

}

注解实现

1. 导入依赖 ,编写xml文件,

与工具类实现相同

2. yaml文件配置

spring:
cache:
  ehcache:
    config: ehcache.xml

3.注解实现

/**
* @title: CacheDao
* @Author bao
* @description
* @Date: 2021/12/179:30
*/
@Repository
@CacheConfig
public class CacheDao {

   /**
    * 获取缓存信息
    * @param id
    * @return
    */
   @Cacheable(value = "myCache", key = "#id")
   public Map<String, Object> getCache(String id){
       return new HashMap<>();
  }


   /**
    * 添加修改缓存信息
    * @param id
    * @return
    */
   @CachePut(value = "myCache", key = "#id")
   public Map<String, Object> putCache(String id){
       Map<String, Object> map = new HashMap<>();
       String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
       map.put("name", "李四");
       map.put("date", format);
       return map;
  }


   /**
    * 删除缓存信息
    * allEntries:非必需,默认为false。当为true时,会移除所有数据
    * @param id
    */
   @CacheEvict(value = "myCache", key = "#id")
   public void deleteCache(String id){
       return;
  }

}

4. 测试

    @Autowired
  CacheDao cacheDao;

  @Test
  public void contextLoad() {
     Map<String, Object> map = cacheDao.putCache("1");
     System.out.println(map);

//   cacheDao.deleteCache("1");
     try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

     Map<String, Object> map2 = cacheDao.putCache("1");
     System.out.println(map2);

     try {
        Thread.sleep(5000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }


     Map<String, Object> map1 = cacheDao.getCache("1");
     System.out.println(map1);

  }

 

posted @   念星河  阅读(601)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示