spring boot 整合ehcache
EHCache是来自sourceforge(http://ehcache.sourceforge.net/) 的开源项目,也是纯Java实现的简单、快速的Cache组件。
EHCache支持内存和磁盘的缓存,支持LRU、LFU和FIFO多种淘汰算法,支持分 布式的Cache,可以作为Hibernate的缓存插件。同时它也能提供基于Filter的Cache,该Filter可以缓存响应的内容并采用 Gzip压缩提高响应速度。
1、添加pom依赖
例:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
<version>${spring-boot.version}</version>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>${ehcache.version}</version>
</dependency>
2、添加配置文件ehcache.xml
(1)配置文件默认读取classpath*:ehcache.xml或classpath*:config/ehcache.xml,可通过application.properties/application.yml中spring.cache.ehcache.config作为key指定配置文件位置。
(2)参数说明:
maxElementsInMemory:缓存最大个数。
eternal:对象是否永久有效,一但设置了,timeout将不起作用。
timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。
timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。
overflowToDisk:当内存中对象数量达到maxElementsInMemory时,Ehcache将会对象写到磁盘中。 diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。
maxElementsOnDisk:硬盘最大缓存个数。
diskPersistent:是否缓存虚拟机重启期数据。
diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。
memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。
clearOnFlush:内存数量最大时是否清除。
(3)示例:
<?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" />
<!-- 默认缓存 -->
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
maxElementsOnDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
<persistence strategy="localTempSwap" />
</defaultCache>
<!-- 测试 -->
<cache name="test"
eternal="false"
timeToIdleSeconds="2400"
timeToLiveSeconds="2400"
maxEntriesLocalHeap="10000"
maxEntriesLocalDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
overflowToDisk="false"
memoryStoreEvictionPolicy="LRU">
</cache>
</ehcache>
3、缓存使用
(1)标签:
1)@CacheConfig(cacheNames = {"test"}) 设置ehcache的名称,这个名称是2中配置的cache.name。
2)@CachePut("key=cache_key"):方法注解,该注解会执行方法内代码并将返回结果按照规则缓存起来(插入数据、更新数据等)。
3)@Cacheable("key=cache_key"):方法注解,改注解会优先查找缓存,如无缓存会执行方法内代码(查询数据)。
4)@CacheEvict("key=cache_key"):主要针对方法配置,能够根据一定的条件对缓存进行清空。适用于删除(删除数据)。
注:key为指定缓存的key,如不指定默认空串(建议都指定),可使用#指定方法参数值及参数属性值
(2)示例:
@Controller
@RequestMapping("test/ehcaches")
@Slf4j
@CacheConfig(cacheNames = "test")
public class EhcacheTestController {
@PostMapping()
@ResponseBody
@CachePut(key = "#kvEntity.key") // 根据kvEntity.key作为缓存key,如果查询缓存为key值的数据直接返回缓存信息
public Object addCache(@RequestBody KvEntity kvEntity) {
log.info("EhcacheTestController putCache 【{}】", kvEntity);
return BasResp.success(kvEntity);
}
@PutMapping("/{key}")
@ResponseBody
@CachePut(key = "#key") // 更新key对应的缓存
public Object updateCache(@PathVariable String key, @RequestParam String value) {
return BasResp.success(new KvEntity(key, value));
}
@DeleteMapping("/{key}")
@ResponseBody
@CacheEvict(key = "#key") // 删除key对应的缓存
public Object deleteCache(@PathVariable String key) {
return BasResp.success(new KvEntity("empty-key", "empty-value"));
}
@GetMapping("/{key}")
@ResponseBody
@Cacheable(key = "#key") // 查询key对应的缓存
public Object getCache(@PathVariable String key) {
return BasResp.success(new KvEntity("empty-key", "empty-value"));
}
@GetMapping("/constants")
@ResponseBody
@Cacheable
public Object getConstantCache() {
return BasResp.success(kvEntityList());
}
@PostMapping("/constants")
@ResponseBody
@CachePut
public Object addConstantCache() {
return BasResp.success(kvEntityList());
}
private List<KvEntity> kvEntityList() {
log.info("EhcacheTestController kvEntityList recache ...");
return new ArrayList<KvEntity>() {{
add(new KvEntity("k1", "v1"));
add(new KvEntity("k2", "v2"));
add(new KvEntity("k3", "v3"));
add(new KvEntity("k4", "v4"));
add(new KvEntity("k5", "v5"));
}};
}
}
转一篇ehcache、memcache、redis三大缓存比较
https://www.cnblogs.com/qlqwjy/p/7788912.html

浙公网安备 33010602011771号