Ehcache是三方独立的缓存技术,boot对Ehcache的支持也是比较友好的,那么我们如何在我们的项目中使用了?
1.配置的4个步骤
1.1 添加依赖
boot本身提供了一个缓存的启动器,但是,该启动器只是支持缓存,并没有提供缓存技术支持,所以,我们还需要额外的引入缓存的坐标
1)缓存启动器
<!-- Spring Boot 缓存支持启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
2)Ehcache坐标
<!-- Ehcache 坐标 -->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
添加好之后,可以看到依赖库中出现了Ehcache的jar
1.2 创建Ehcache配置文件
文件名: ehcache.xml
位置: src/main/resources/ehcache.xml
在Ehcache的jar包下,有一个名为ehcache-failsafe.xml的文件,该文件提供了配置模板,如图:
将该文件内容复制到我们自己的配置文件中,做一些基本的修改即可 。
配置如下:
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">
<diskStore path="java.io.tmpdir"/>
<!--defaultCache:echcache的默认缓存策略 -->
<defaultCache
maxElementsInMemory="10000" <!-- 最大缓存对象个数 -->
eternal="false" <!-- 是否做持久化处理 -->
timeToIdleSeconds="120" <!--访问缓存中对象的时间间隔,单位是秒,意思是超过了配置的时间,ehcache就将该对象删除 -->
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>
在模板文件中,提供了一个<defaultCache>配置,该配置就是echcache的默认缓存策略,也就是说在使用ehcache 的时候,没有指定缓存策略,将以<defaultCache>默认缓存策略做为设定。
当然,默认的缓存策略往往无法满足我们的 需求,所以,通常情况下,我们可以使用cache来配置自定义缓存策略。我们可以指定多个cache来定义我们的缓存策略,但是,需要注意,每一个cache的name属性值必须唯一。
1.3 指定ehcache.xml文件位置
我们需要告知boot,ehcache.xml配置文件的位置,我们可以通过在application.xml中配置该路径,例如:
1.4 开启缓存策略
在启动类上加上注解@EnableCaching,如图:
2. 使用缓存方法
2.1 标注缓存方法
在需要添加缓存的方法上加上注解@Cacheable并给上缓存策略
注意:
1. 如果这里不指定缓存策略,那么执行默认缓存策略
2. @Cacheable注解的含义是对当前查询返回的对象做缓存处理,这里当前对象就是返回值List<User>对象
运行程序,发现Junit执行成功,但是,程序运行出错,如图:
根据错误信息,可以知道提示我们要将User做序列化处理。因为Ehcache支持磁盘缓存的,也就是说,可以对缓存对象做一个磁盘文件的存储,因为是磁盘文件的存储,所以要求存储对象必须实现可序列化接口。
2.2 让缓存对象实现可序列化接口
然后,运行程序,正常运行。
3. 使用Ehcache缓存技术常用的两个注解
3.1 @Cacheable
@Cacheable 作用: 把方法的返回值添加到 Ehcache 中做缓存
value 属性: 指定一个 Ehcache 配置文件中的缓存策略, 如果木有给定 value, 那么则表示使用默认的缓存策略
@Cacheable 注解还有一个属性key,用于给存储的值起个名称。 在查询时如果有名称相同的, 那么则知己从缓存中将数据返回。
例如:
@Cacheable(value="users",key="#pageable")
public Page<Users> findUserByPage(Pageable pageable) {
return this.usersRepository.findAll(pageable);
}
这里我们指定缓存的key为pageable分页对象,当分页对象再缓存中存在的时候,就查缓存,否则查数据库
3.2 @CacheEvict
@CacheEvict 作用: 清除缓存
我们生成缓存信息之后,当执行增删改操作的时候,同时也需要删除掉缓存信息,这时候,就可以时候@CacheEvict注解了,例如:
@CacheEvict(value="users",allEntries=true)
public void saveUsers(Users users) {
this.usersRepository.save(users);
}
该注解也有一个value属性,值也为缓存策略,如上例,表示为清除缓存中以 users 缓存策略缓存的对象
注意:要清空缓存,除了需要value属性还需要allEntries属性配套使用。