版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/luo4105/article/details/78984195
ehcache是java内存缓存框架,没有ehcache服务,只需要在java程序中加载jar就可以了。
mvn地址
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-core</artifactId>
<version>2.6.0</version>
</dependency>
这里使用xml配置的方式整合ehcache。jar包会自动扫描class根文件夹下的ehcache.xml文件读取配置,在mvn项目中就是resource根目录。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" updateCheck="false">
<diskStore path="java.io.tmpdir"/>
<!-- 默认缓存配置 -->
<defaultCache maxElementsInMemory="1000" eternal="false" timeToIdleSeconds="0" timeToLiveSeconds="600"
overflowToDisk="false"
diskPersistent="false" memoryStoreEvictionPolicy="LRU"/>
<!--
自定义,service缓存配置
eternal: 缓存是否永远不销毁
maxElementsInMemory: 缓存可以存储的总记录量
overflowToDisk: 当缓存中的数据达到最大值时,是否把缓存数据写入磁盘
diskPersistent: 是否启用强制命令将缓存出入磁盘
timeToIdleSeconds: 当缓存闲置时间超过该值,则缓存自动销毁,如果该值是0就意味着元素可以停顿无穷长的时间
timeToLiveSeconds: 缓存数据的生存时间,也就是一个元素从构建到消亡的最大时间间隔值, 这只能在元素不是永久驻留时有效,如果该值是0就意味着元素可以停顿无穷长的时间
memoryStoreEvictionPolicy: 缓存满了之后的淘汰算法
-->
<cache name="serviceCache"
eternal="false"
maxElementsInMemory="1000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="0"
timeToLiveSeconds="3600"
memoryStoreEvictionPolicy="LRU"/>
</ehcache>
创建Cache管理对象并使用
CacheManager cacheManager = new CacheManager();
Ehcache fileCache = cacheManager.getCache("serviceCache");
fileCache.put(new Element("key", "value"));
Element el = fileCache.get("key");
System.out.println(el.getObjectValue());
这是一个简单的工具类,包含着插入元素和读取元素操作。
public class EncacheTemplete {
private static CacheManager cacheManager;
private static Ehcache fileCache;
static {
cacheManager = new CacheManager();
fileCache = cacheManager.getCache("serviceCache");
}
public static <T> void put(String key, T value) {
fileCache.put(new Element(key, value));
}
@SuppressWarnings("unchecked")
public static <T> T get(String key) {
Element el = fileCache.get(key);
if (el == null) {
System.out.println("not found key: " + key);
return null;
}
T t = (T) el.getObjectValue();
return t;
}
/**
* 根据key删除缓存
*/
public static boolean remove(String key) {
System.out.println("remove key:" + key);
return fileCache.remove(key);
}
/**
* 关闭cacheManager 对象
*/
public static void shutdown() {
cacheManager.shutdown();
}
}