EhCache是一个比较成熟的Java缓存框架,在springboot 的底层中已经封装了该框架,Springboot对ehcache的使用非常支持,所以在Springboot中只需做些配置就可使用,且使用方式也简易。
一、创建项目并导入依赖
//ehcache
compile group: 'org.springframework.boot', name: 'spring-boot-starter-cache', version: '2.0.6.RELEASE'
compile group: 'net.sf.ehcache', name: 'ehcache', version: '2.5.2'
二、相关配置和代码
1、application.properties 添加配置信息。
# 配置ehcache缓存
spring.cache.type=ehcache
# 指定ehcache配置文件路径
spring.cache.ehcache.config=classpath:/ehcache.xml
2、在启动类上添加@EnableCaching 注解表示启用cache
@EnableCaching
3、ehcache.xml ehcache详细配置。
<?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">
<defaultCache maxElementsInMemory="1000"
overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="3600"
timeToLiveSeconds="3600" memoryStoreEvictionPolicy="LRU"/>
<!--
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:内存数量最大时是否清除。
-->
<cache name="5s" maxElementsInMemory="100"
overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="5" timeToLiveSeconds="5"
memoryStoreEvictionPolicy="LRU"/>
</ehcache>
4、CacheUtils 工具类简单存取数据(手动存取数据的方式),要注意这里应用Cache 包的位置,搞清楚CacheManager和EhCacheCacheManager 的关系,把配置注入的CacheManager转换成EhCacheCacheManager 这一步很关键,否则怎么取值都是null。
import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.context.annotation.Configuration;
@Configuration
public class CacheUtils {
private static CacheManager manager;
@Autowired
public void setManager(CacheManager manager) {
CacheUtils.manager = manager;
}
public static Object get(String cacheName, Object key) {
Element e= cache(cacheName).get(key);
if(e!=null){
return e.getObjectValue();
}
return null;
}
public static void put(String cacheName, Object key, Object value, Integer ttl, Integer tti) {
Element e = new Element(key, value);
//不设置则使用xml配置
if (ttl != null)
e.setTimeToLive(ttl);
if (tti != null)
e.setTimeToIdle(tti);
cache(cacheName).put(e);
}
private static Cache cache(String cacheName) {
net.sf.ehcache.CacheManager cacheManager = ((EhCacheCacheManager) manager).getCacheManager();
if (!cacheManager.cacheExists(cacheName))
cacheManager.addCache(cacheName);
return cacheManager.getCache(cacheName);
}
}
三、使用方式
存取数据的方式两种:
1、手动存取,上面CacheUtils工具类就是手动存取的方式
//存入
CacheUtils.put("token_config","access_token",token,null,null);
//取出
Object obj = CacheUtils.get("token_config","access_token");
2、还有一种方式就是使用 注解的方式
@Cacheable(value="users", key="#id")
public User find(Integer id) {
return null;
}
当id一样的时候不会执行方法内部,只会从缓存中读取方法的已经存入值。
以上就是对ehcache简单集成,当然实际过程中使用Redis 作为缓存还是比较多了,因为我这里是独立项目还用不到redis,所以就是使用了ehcache。