ehcache与spring整合
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
<version>2.3.2.RELEASE</version>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.10.2</version>
</dependency>
ehcache.xml(详情见ehcache学习(一))
链接: 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">
<!-- 磁盘缓存位置 -->
<diskStore path="java.io.tmpdir/ehcache"/>
<!-- 默认缓存 -->
<defaultCache
maxEntriesLocalHeap="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
maxEntriesLocalDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
<persistence strategy="localTempSwap"/>
</defaultCache>
<cache name="productCache"
eternal="false"
timeToIdleSeconds="2400"
timeToLiveSeconds="2400"
maxEntriesLocalHeap="10000"
maxEntriesLocalDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
overflowToDisk="false"
memoryStoreEvictionPolicy="LRU"/>
</ehcache>
application.yml
spring:
cache:
ehcache:
config: classpath:ehcache.xml
在启动类上打上注解
@EnableCaching
在需要的使用缓存的地方打上@CacheConfig注解
@CacheConfig(cacheName="productCache")
缓存策略
value:缓存位置名称,不能为空,如果使用EHCache,就是ehcache.xml中声明的cache的name
key:缓存的key,默认为空,既表示使用方法的参数类型及参数值作为key,支持SpEL
condition:触发条件,只有满足条件的情况才会加入缓存,默认为空,既表示全部都加入缓存,支持SpEL,例如:
allEntries:CacheEvict参数,true表示清除value中的全部缓存,默认为false
@cache相当于save()操作
@cachePut相当于update()操作,只要它标示的方法被调用,那么都会缓存,而@cache先看是否有缓存,在选择是否执行方法
@Cacheable:负责将方法的返回值加入到缓存中
@CacheEvict:负责清除缓存
@CachEvict(value="testcache" condition="#userName.length()>2")