添加依赖
<!--开启 cache 缓存 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!-- ehcache 缓存 -->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
配置文件
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
<!-- 磁盘缓存位置 -->
<diskStore path="java.io.tmpdir/ehcache"/>
<!-- 默认缓存 -->
<defaultCache
eternal="false"
maxElementsInMemory="1000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="0"
timeToLiveSeconds="120"
memoryStoreEvictionPolicy="LRU"/>
</ehcache>
缓存管理类
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;
public class EhcacheManager {
private static final String CACHE_NAME = "keda-cache";
private static Ehcache getEhcache () {
CacheManager cacheManager = CacheManager.getInstance();
return cacheManager.addCacheIfAbsent(CACHE_NAME);
}
public static void put (Object key, Object value) {
Ehcache ehcache = getEhcache();
ehcache.putIfAbsent(new Element(key, value));
}
public static Object get (Object key) {
Ehcache ehcache = getEhcache();
Element element = ehcache.get(key);
if (element != null) {
return element.getObjectValue();
}
return null;
}
}