1.添加 pom.xml 依赖
<!-- caching --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-cache</artifactId></dependency><dependency><groupId>net.sf.ehcache</groupId><artifactId>ehcache</artifactId></dependency>
2.配置属性
spring.cache.type=ehcachespring.cache.ehcache.config=classpath:config/ehcache.xml
3.ehcache.xml
<!--diskStore path:用来配置磁盘缓存使用的物理路径name: 缓存名称,cache的唯一标识(ehcache会把这个cache放到HashMap里)eternal="false" 元素是否永恒,如果是就永不过期(必须设置)maxElementsOnDisk====磁盘缓存中最多可以存放的元素数量,0表示无穷大maxElementsInMemory="1000" 内存缓存中最多可以存放的元素数量(必须设置)timeToIdleSeconds="0" 导致元素过期的访问间隔(秒为单位). 0表示可以永远空闲,默认为0timeToLiveSeconds="600" 元素在缓存里存在的时间(秒为单位). 0 表示永远存在不过期overflowToDisk="false" 当缓存达到maxElementsInMemory值是,是否允许溢出到磁盘(必须设置)diskPersistent="false" 磁盘缓存在VM重新启动时是否保持(默认为false)diskExpiryThreadIntervalSeconds="100" 磁盘失效线程运行时间间隔,默认是120秒memoryStoreEvictionPolicy="LFU" 内存存储与释放策略.当达到maxElementsInMemory时共有三种策略,分别为LRU(最近最少使用)、LFU(最常用的)、FIFO(先进先出)默认使用"最近使用"策略-->
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ehcache.xsd"><cache name="roncooCache" eternal="false" maxEntriesLocalHeap="0" timeToIdleSeconds="200"></cache><!-- eternal:true表示对象永不过期,此时会忽略timeToIdleSeconds和timeToLiveSeconds属性,默认为false --><!-- maxEntriesLocalHeap:堆内存中最大缓存对象数,0没有限制 --><!-- timeToIdleSeconds: 设定允许对象处于空闲状态的最长时间,以秒为单位。当对象自从最近一次被访问后,如果处于空闲状态的时间超过了timeToIdleSeconds属性值,这个对象就会过期,EHCache将把它从缓存中清空。只有当eternal属性为false,该属性才有效。如果该属性值为0,则表示对象可以无限期地处于空闲状态 --></ehcache>
4.启用注解
在 Spring Boot 的启动类(Application)中增加如下注解:
@EnableCaching:启用缓存注解
5.实现例子
public interface UserLogCache {/*** 查询** @param id* @return*/RoncooUserLog selectById(Integer id);/*** 更新** @param roncooUserLog* @return*/RoncooUserLog updateById(RoncooUserLog roncooUserLog);/*** 删除** @param id* @return*/String deleteById(Integer id);}@CacheConfig(cacheNames = "userCache")@Repositorypublic class UserLogCacheImpl implements UserLogCache {@Autowiredprivate RoncooUserLogDao roncooUserLogDao;@Cacheable(key = "#p0")@Overridepublic RoncooUserLog selectById(Integer id) {System.out.println("查询功能,缓存找不到,直接读库, id=" + id);return roncooUserLogDao.findOne(id);}@CachePut(key = "#p0")@Overridepublic RoncooUserLog updateById(RoncooUserLog roncooUserLog) {System.out.println("更新功能,更新缓存,直接写库, id=" + roncooUserLog);return roncooUserLogDao.save(roncooUserLog);}@CacheEvict(key = "#p0")@Overridepublic String deleteById(Integer id) {System.out.println("删除功能,删除缓存,直接写库, id=" + id);return "清空缓存成功";}}
6.注解说明
- @CacheConfig:缓存配置;
- @Cacheable:应用到读取数据的方法上,即可缓存的方法,如查找方法:先从缓存中读取,如果没有再调用方法获取数据,然后把数据添加到缓存中,适用于查找;
- @CachePut:主要针对方法配置,能够根据方法的请求参数对其结果进行缓存,和 @Cacheable 不同的是,它每次都会触发真实方法的调用,适用于更新和插入;
- @CacheEvict:主要针对方法配置,能够根据一定的条件对缓存进行清空,适用于删除;
