直接上代码,原来自己看
1、在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/Tmp_EhCache" />
<!-- defaultCache,是默认的缓存策略 -->
<!-- 如果你指定的缓存策略没有找到,那么就用这个默认的缓存策略 -->
<!-- external:缓存对象是否一直存在,如果设置为true的话,那么timeout就没有效果,缓存就会一直存在,一般默认就是false -->
<!-- maxElementsInMemory:内存中可以缓存多少个缓存条目 -->
<!-- overflowToDisk:如果内存不够的时候,是否溢出到磁盘 -->
<!-- diskPersistent:是否启用磁盘持久化的机制,在jvm崩溃的时候和重启之间 -->
<!-- timeToIdleSeconds:对象最大的闲置的时间,如果超出闲置的时间,可能就会过期 单位:秒 当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大-->
<!-- timeToLiveSeconds:对象最多存活的时间 单位:秒 当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是存活时间无穷大-->
<!-- memoryStoreEvictionPolicy:当缓存数量达到了最大的指定条目数的时候,需要采用一定的算法,从缓存中清除一批数据,LRU,最近最少使用算法,最近一段时间内,最少使用的那些数据,就被干掉了 -->
<defaultCache
eternal="false"
maxElementsInMemory="1000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
memoryStoreEvictionPolicy="LRU" />
<!-- 手动指定的缓存策略 -->
<!-- 对不同的数据,缓存策略可以在这里配置多种 -->
<cache
name="institutionNo"
eternal="false"
maxElementsInMemory="1000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
memoryStoreEvictionPolicy="LRU" />
</ehcache>
2、新建EhcacheUtil.java通用方法类
package com.goldpac.ocs.business.merchantservice.config;
import java.net.URL;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
public class EhcacheUtil {
private static final String path = "/ehcache.xml";
private URL url;
private CacheManager manager;
private static EhcacheUtil ehCache;
private EhcacheUtil(String path) {
url = getClass().getResource(path);
manager = CacheManager.create(url);
}
public static EhcacheUtil getInstance() {
if (ehCache== null) {
ehCache= new EhcacheUtil(path);
}
return ehCache;
}
public void put(String cacheName, String key, Object value) {
Cache cache = manager.getCache(cacheName);
Element element = new Element(key, value);
cache.put(element);
}
public Object get(String cacheName, String key) {
Cache cache = manager.getCache(cacheName);
Element element = cache.get(key);
return element == null ? null : element.getObjectValue();
}
public Cache get(String cacheName) {
return manager.getCache(cacheName);
}
public void remove(String cacheName, String key) {
Cache cache = manager.getCache(cacheName);
cache.remove(key);
}
}
3、导入jar包
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-core</artifactId>
<version>2.4.3</version>
<scope>compile</scope>
</dependency>
4、service中调用
//获取缓存数据institutionNo为ehcache.xml中配置的name,no为获取缓存的数据key(我的no为变量)
Object institutionNo = EhcacheUtil.getInstance().get("institutionNo", no);
//添加缓存数据institutionNo为ehcache.xml中配置的name,no为缓存的数据的key,no2为缓存的value(我的no为变量)
EhcacheUtil.getInstance().put("institutionNo", no, no2);
另附一篇cacheable缓存,我的理解是,没有就执行方法并缓存结果,有就直接返回缓存,,
https://blog.csdn.net/zhuyu19911016520/article/details/81946202