1.spring-boot中整合ehcase缓存
引入依赖,ehcase,spring-boot对缓存的支持,和测试的依赖支持
<!-- springBoot junit的启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<!-- Spring Boot缓存支持启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!-- Ehcache坐标 -->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
2.添加ehcache.xml文件,在classPath目录 文件的内容参考ehcache的jar包中的配置
注意name属性很重要,不能重复
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/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="users"
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
maxElementsOnDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
<persistence strategy="localTempSwap"/>
</cache>
</ehcache>
3.spring-boot全局配置文件中配置cache配置文件的路径
spring.cache.ehcache.config=ehcache.xml
4.启动类上开启缓存
5.业务代码使用缓存机制 在方法上添加@Cacheable(value="users")
value的值是ehcache.xml文件中配置的name,没有value就用默认的缓存配置。
框架根据方法的参数做为一个key的一部分,返回值作为value。缓存好
如果返回值的对象没有实现序列号接口,需要实现下。
@Cacheable() 两个参数 value 使用缓存策略 key="#" 把什么作为缓存的key
@CacheEvict (value="users", allEntries=true) 清除缓存,一般有数据库操作后清除缓存。