SpringBoot整合EhCache
序言
本文主要简单介绍再SpringBoot下如何集成EhCache,EhCache一种缓存技术,个人认为用在小型项目中及其方便,提高系统的读取性能,但是不适用大型项目,大型项目还是应该考虑Redis作为缓存技术。
整合步骤
1.引入依赖
<!--缓存支持启动器-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!--Ehcache缓存坐标-->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.10.6</version>
</dependency>
2.再resource根目录下建立配置文件chcache.xml
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
<diskStore path="java.io.tmpdir"/>
<!--defaultCache:echcache的默认缓存策略 -->
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
maxElementsOnDisk="10000000"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
<persistence strategy="localTempSwap"/>
</defaultCache>
<!--
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="user"
maxElementsInMemory="100"
eternal="false"
timeToIdleSeconds="5400"
timeToLiveSeconds="5400"
maxElementsOnDisk="100"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
<persistence strategy="localTempSwap"/>
</cache>
</ehcache>
3.在application.properties中添加配置
#配置Ehcache文件
spring.cache.ehcache.config=classpath:ehcache.xml
4.在项目启动类上添加注解开启缓存技术
@EnableCaching//开启缓存技术
使用
1.在需要缓存的数据上添加注解@Cacheable
@Cacheable中的值表示以哪种缓存策略来进行缓存,缓存策略在配置文件中可以自定义若不定义则使用默认缓存策略
使用缓存后,会将方法的返回值直接放在缓存内,下次访问时则直接从缓存中取出。
@RequestMapping("/select")
@ResponseBody
@Cacheable(value = "user")
//对当前查询的对象做缓存处理,缓存对象需要实现Serializable接口
//当前方法的返回值会被放入到缓存中
public User selectUser(int id){
return userService.SelectUser(id);
}
2.清除缓存
需要注意的是,开启缓存后若数据库数据更新,系统依然会从缓存中取出数据,此时缓存内的数据没有更改,则无法看到数据更新。因此需要在更新数据时将缓存情况
当注解参数加上allEntries为true时,意思是说这个清除缓存是清除当前value值空间下的所有缓存数据。
@RequestMapping("/add")
@ResponseBody
@CacheEvict(value = "user",allEntries = true)
//清空基于什么缓存策略的缓存
public String addUser(User user){
this.userService.addUser(user);
return "OK!";
}