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配置文件编写
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) {