Java Springboot 项目引入Ehcache内置缓存并操作其中数据的详细方法
·
引入依赖
在pom.xml中添加依赖项
<!-- Ehcache缓存管理器 -->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.10.6</version>
</dependency>
创建样例配置文件
在resources中创建一个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">
<!-- 磁盘缓存位置 -->
<diskStore path="./db/ehcache"/>
<!-- 缓存配置
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
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
maxElementsOnDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
<persistence strategy="localTempSwap"/>
</defaultCache>
<!-- 临时cache -->
<cache name="temp_cache"
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="1800"
timeToLiveSeconds="1800"
maxElementsOnDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
<persistence strategy="localTempSwap"/>
</cache>
<!-- 持久化cache -->
<!-- <cache name="eternal_cache"-->
<!-- maxElementsInMemory="10000"-->
<!-- eternal="true"-->
<!-- timeToIdleSeconds="120"-->
<!-- timeToLiveSeconds="120"-->
<!-- overflowToDisk="true"-->
<!-- diskPersistent="true"-->
<!-- diskExpiryThreadIntervalSeconds="10">-->
<!-- </cache>-->
</ehcache>
创建常数类
创建一个名为Ehcache2Config常数类,可以内容可修改,用以程序临时定义一些缓存集合对象的配置项默认值
/**
* Ehcache2Config
*
* @author mzp
* @version 1.0
* @since 2025/9/9
*/
public interface Ehcache2Config {
/**
* 内存中最大的缓存对象数量
*/
int MAX_ELEMENTS_IN_MEMORY = 5000;
/**
* 是否把溢出数据持久化到硬盘
*/
boolean OVER_FLOW_TO_DISK = true;
/**
* 是否永久存活
*/
boolean ETERNAL = false;
/**
* 缓存空闲多久后失效/秒
*/
int TIME_TO_IDLE_SECONDS = 600;
/**
* 缓存最多存活时间/秒
*/
int TIME_TO_LIVE_SECONDS = 1800;
/**
* 是否需要持久化到硬盘
*/
boolean DISK_PERSISTENT = false;
/**
* 缓存策略
*/
String MEMORY_STORE_EVICTION_POLICY = "LFU";
/**
* 默认的cacheName
*/
String DEFAULT_CACHE = "cache";
}
创建操作类
创建一个名为Ehcache2Cache的操作类,包含创建,查询,删除等方法
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import net.sf.ehcache.config.CacheConfiguration;
import org.springframework.data.util.Pair;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
/**
* Ehcache2Cache
* ehcache操作类
* @author mzp
* @version 1.0
* @since 2025/9/9
*/
public class Ehcache2Cache implements Ehcache2Config {
private static CacheManager cacheManager = null;
private static Cache cache = null;
static {
initCacheManager();
initCache();
}
/**
* 初始化缓存管理容器
*/
public static CacheManager initCacheManager() {
try {
if (cacheManager == null) {
cacheManager = CacheManager.getInstance();
}
} catch (RuntimeException e) {
e.printStackTrace();
}
return cacheManager;
}
/**
* 初始化缓存管理容器
*
* @param path ehcache.xml存放的路徑
*/
public static CacheManager initCacheManager(String path) {
try {
if (cacheManager == null) {
CacheManager.getInstance();
cacheManager = CacheManager.create(path);
}
} catch (RuntimeException e) {
e.printStackTrace();
}
return cacheManager;
}
/**
* 初始化cache
*/
public static Cache initCache() {
return initCache(DEFAULT_CACHE);
}
/**
* 获取cache
*/
public static Cache initCache(String cacheName) {
checkCacheManager();
if (null == cacheManager.getCache(cacheName)) {
cacheManager.addCache(cacheName);
}
cache = cacheManager.getCache(cacheName);
return cache;
}
/**
* 添加缓存
*
* @param key 关键字
* @param value 值
*/
public static void put(Object key, Object value) {
checkCache();
// 创建Element,然后放入Cache对象中
Element element = new Element(key, value);
cache.put(element);
}
/**
* 获取cache
*
* @param key 关键字
* @return value
*/
public static Object get(Object key) {
checkCache();
Element element = cache.get(key);
if (null == element) {
return null;
}
return element.getObjectValue();
}
/**
* 初始化缓存
*
* @param cacheName 缓存名称
* @param maxElementsInMemory 元素最大数量
* @param overflowToDisk 是否持久化到硬盘
* @param eternal 是否永远存活
* @param timeToLiveSeconds 缓存存活时间
* @param timeToIdleSeconds 缓存的间隔时间
* @return cache 缓存
* @throws RuntimeException e
*/
public static Cache initCache(String cacheName, int maxElementsInMemory,
boolean overflowToDisk, boolean eternal,
long timeToLiveSeconds, long timeToIdleSeconds)
throws RuntimeException {
try {
Cache myCache = cacheManager.getCache(cacheName);
if (myCache != null) {
CacheConfiguration config = cache.getCacheConfiguration();
config.setTimeToLiveSeconds(timeToLiveSeconds);
config.setMaxEntriesLocalHeap(maxElementsInMemory);
config.setOverflowToDisk(overflowToDisk);
config.setEternal(eternal);
config.setTimeToIdleSeconds(timeToIdleSeconds);
}
if (myCache == null) {
Cache memoryOnlyCache = new Cache(cacheName, maxElementsInMemory,
overflowToDisk, eternal, timeToLiveSeconds, timeToIdleSeconds);
cacheManager.addCache(memoryOnlyCache);
myCache = cacheManager.getCache(cacheName);
}
return myCache;
} catch (RuntimeException e) {
throw new RuntimeException("init cache " + cacheName + " failed!!!");
}
}
/**
* 初始化cache
*
* @param cacheName cache的名字
* @param timeToLiveSeconds 有效时间
* @return cache 缓存
* @throws RuntimeException e
*/
public static Cache initCache(String cacheName, long timeToLiveSeconds) throws RuntimeException {
return initCache(cacheName, MAX_ELEMENTS_IN_MEMORY, OVER_FLOW_TO_DISK,
ETERNAL, timeToLiveSeconds, TIME_TO_IDLE_SECONDS);
}
/**
* 初始化Cache
*
* @param cacheName cache容器名
* @return cache容器
* @throws RuntimeException e
*/
public static Cache initMyCache(String cacheName) throws RuntimeException {
return initCache(cacheName, TIME_TO_LIVE_SECONDS);
}
/**
* 修改缓存容器配置
*
* @param cacheName 缓存名
* @param timeToLiveSeconds 有效时间
* @param maxElementsInMemory 最大数量
* @throws RuntimeException e
*/
public static boolean modifyCache(String cacheName, long timeToLiveSeconds, int maxElementsInMemory) throws RuntimeException {
try {
if (cacheName != null && !"".equals(cacheName)
&& timeToLiveSeconds != 0L && maxElementsInMemory != 0) {
Cache myCache = cacheManager.getCache(cacheName);
CacheConfiguration config = myCache.getCacheConfiguration();
config.setTimeToLiveSeconds(timeToLiveSeconds);
config.setMaxEntriesLocalHeap(maxElementsInMemory);
return true;
} else {
return false;
}
} catch (RuntimeException e) {
throw new RuntimeException("modify cache " + cacheName + " failed!!!");
}
}
/**
* 向指定容器中设置值
*
* @param cacheName 容器名
* @param key 键
* @param value 值
* @return 返回真
* @throws RuntimeException e
*/
public static boolean setValue(String cacheName, String key, Object value) throws RuntimeException {
try {
Cache myCache = cacheManager.getCache(cacheName);
if (myCache == null) {
myCache = initCache(cacheName);
}
myCache.put(new Element(key, value));
return true;
} catch (RuntimeException e) {
throw new RuntimeException("set cache " + cacheName + " failed!!!");
}
}
/**
* 向指定容器中设置值
*
* @param cacheName 容器名
* @param key 键
* @param value 值
* @param timeToLiveSeconds 存活时间
* @return 真
* @throws RuntimeException e
*/
public static boolean setValue(String cacheName, String key, Object value, Integer timeToLiveSeconds) throws RuntimeException {
try {
Cache myCache = cacheManager.getCache(cacheName);
if (myCache == null) {
initCache(cacheName, timeToLiveSeconds);
myCache = cacheManager.getCache(cacheName);
}
myCache.put(new Element(key, value, timeToLiveSeconds, timeToLiveSeconds));
return true;
} catch (RuntimeException e) {
throw new RuntimeException("set cache " + cacheName + " failed!!!");
}
}
/**
* 从ehcache的指定容器中取值
*
* @param key 键
* @return 返回Object类型的值
* @throws RuntimeException e
*/
public static Object getValue(String cacheName, String key) throws RuntimeException {
try {
Cache myCache = cacheManager.getCache(cacheName);
if (myCache == null) {
myCache = initMyCache(cacheName);
}
Element element = myCache.get(key);
return element == null ? null : element.getObjectValue();
} catch (RuntimeException e) {
throw new RuntimeException("get cache " + cacheName + " value failed!!!");
}
}
/**
* 从ehcache的指定容器中取值,并获取标识位,标识是否缓存中存在这个Key
* 该设计是为了避免空值时出现缓存穿透的可能
*
* @param key 键
* @return 返回Object类型的值
* @throws RuntimeException e
*/
public static Pair<Boolean, Optional<?>> getValueWithState(String cacheName, String key) throws RuntimeException {
try {
Cache myCache = cacheManager.getCache(cacheName);
if (myCache == null) {
myCache = initMyCache(cacheName);
}
Element element = myCache.get(key);
boolean cacheContainsKey = element != null;
Object value = cacheContainsKey ? element.getObjectValue() : null;
return Pair.of(cacheContainsKey, Optional.ofNullable(value));
} catch (RuntimeException e) {
throw new RuntimeException("get cache " + cacheName + " value failed!!!");
}
}
/**
* 删除指定的ehcache容器
*
* @param cacheName cacheName
* @return 真
* @throws RuntimeException e
*/
public static boolean removeCache(String cacheName) throws RuntimeException {
try {
cacheManager.removeCache(cacheName);
return true;
} catch (RuntimeException e) {
throw new RuntimeException("remove cache " + cacheName + " failed!!!");
}
}
/**
* 删除所有的ehcache容器
*
* @return 返回真
* @throws RuntimeException e
*/
public static boolean removeAllCache() throws RuntimeException {
try {
cacheManager.removeAllCaches();
return true;
} catch (RuntimeException e) {
throw new RuntimeException("remove cache failed!!!");
}
}
/**
* 删除ehcache容器中的元素
*
* @param cacheName 容器名
* @return 真
* @throws RuntimeException e
*/
public static boolean removeALLElement(String cacheName) throws RuntimeException {
try {
Cache myCache = cacheManager.getCache(cacheName);
myCache.removeAll();
return true;
} catch (RuntimeException e) {
throw new RuntimeException("remove cache " + cacheName + " failed!!!");
}
}
/**
* 删除ehcache容器中的元素
*
* @param cacheName 容器名
* @param key 键
* @return 真
* @throws RuntimeException e
*/
public static boolean removeElement(String cacheName, String key) throws RuntimeException {
try {
Cache myCache = cacheManager.getCache(cacheName);
myCache.remove(key);
return true;
} catch (RuntimeException e) {
throw new RuntimeException("remove cache " + cacheName + " failed!!!");
}
}
// /**
// * 删除指定容器中的所有元素
// *
// * @param cacheName 容器名
// * @param key 键
// * @return 真
// * @throws RuntimeException e
// */
// public static boolean removeAllElement(String cacheName, String key) throws RuntimeException {
// try {
// Cache myCache = cacheManager.getCache(cacheName);
// myCache.removeAll();
// return true;
// } catch (RuntimeException e) {
// throw new RuntimeException("remove cache failed!!!");
// }
// }
/**
* 释放CacheManage
*/
public static void shutdown() {
cacheManager.shutdown();
}
/**
* 移除默认cache
*/
public static void removeCache() {
checkCacheManager();
if (null != cache) {
cacheManager.removeCache(DEFAULT_CACHE);
}
cache = null;
}
/**
* 移除默认cache中的key
*
* @param key key
*/
public static void remove(String key) {
checkCache();
cache.remove(key);
}
/**
* 移除默认cache所有Element
*/
public static void removeAllKey() {
checkCache();
cache.removeAll();
}
/**
* 获取所有的cache名称
*
* @return String[]
*/
public static String[] getAllCaches() {
checkCacheManager();
return cacheManager.getCacheNames();
}
/**
* 获取Cache所有的Keys
*
* @return List
*/
public static List<?> getKeys() {
checkCache();
return cache.getKeys();
}
/**
* 获取Cache所有的Keys
*
* @return List
*/
public static List<?> getKeys(String cacheName) {
try {
Cache myCache = cacheManager.getCache(cacheName);
if (myCache == null) {
return new ArrayList<>();
}
return myCache.getKeys();
} catch (RuntimeException e) {
throw new RuntimeException("get cache " + cacheName + " value failed!!!");
}
}
/**
* 判断缓存是否存在该Key
*
* @param cacheName 缓存名称
* @param key key
* @return true存在
*/
public static boolean containsKey(String cacheName, String key) {
try {
Cache myCache = cacheManager.getCache(cacheName);
if (myCache == null) {
return false;
}
Element element = myCache.get(key);
return element != null;
} catch (RuntimeException e) {
throw new RuntimeException("get cache " + cacheName + " value failed!!!");
}
}
/**
* 检测cacheManager
*/
private static void checkCacheManager() {
if (null == cacheManager) {
throw new IllegalArgumentException("调用前请先初始化CacheManager值:initCacheManager");
}
}
/**
* 检测cache
*/
private static void checkCache() {
if (null == cache) {
throw new IllegalArgumentException("调用前请先初始化Cache值:initCache(参数)");
}
}
/**
* 输出cache信息
*/
public static void showCache() {
String[] cacheNames = cacheManager.getCacheNames();
System.out.println("缓存的key cacheNames length := "
+ cacheNames.length + " 具体详细列表如下:");
for (String cacheName : cacheNames) {
System.out.println("cacheName := " + cacheName);
Cache cache = cacheManager.getCache(cacheName);
List<?> cacheKeys = cache.getKeys();
for (Object key : cacheKeys) {
System.out.println(key + " = " + cache.get(key));
}
}
}
}
调用方法
//添加新的缓存集合
String cacheName = "TestCache_1";
Ehcache2Cache.initCache(cacheName);
//清除缓存集合
Ehcache2Cache.removeALLElement(cacheName)
//获取缓存集合中所有键值对
List<String> keysList = (List<String>)Ehcache2Cache.getKeys(cacheName);
//从缓存集合中删除某一个键值对
Ehcache2Cache.removeElement(cacheName, key);
更多推荐



所有评论(0)