一、用途:不用每次都从数据库查,查询一次后放入到缓存,之后相同的查询走缓存。对应一些经常查询的方法,可以设置缓存
二、springboot下怎么用?
- 引入相关jar包
<!--开启 cache 缓存-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<!-- ehcache 缓存 -->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
- 在resources下创建ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
updateCheck="false">
<defaultCache
eternal="false"
maxElementsInMemory="1000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="0"
timeToLiveSeconds="600"
memoryStoreEvictionPolicy="LRU" />
<!--配置缓存-->
<cache
name="cache1"
eternal="false"
maxElementsInMemory="100"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="0"
timeToLiveSeconds="300"
memoryStoreEvictionPolicy="LRU" />
</ehcache>
- 启动类上注入@EnableCaching注解
@EnableCaching
@SpringBootApplication
@MapperScan(basePackages = {"com.jiuba.shop.mapper","com.jiuba.shop.dic.mapper"})
public class GoodsApplication {
public static void main(String[] args) {
SpringApplication.run(GoodsApplication.class, args);
}
}
- 使用@Cacheable注解 放到方法上
- 其中value的值对应ehcache.xml中的name,key作为缓存中的key
@Cacheable(value = "cache1",key = "'dicCode'+#dicCode")
public ResultVO getEnumByDicCode(String dicCode) {
log.info("缓存中不存在,从数据库查……");
List<Enum> dicEnum = enumMapper.getEnumByDicCode(dicCode);
if (dicEnum == null){
return ResultVO.fail();
}
return ResultVO.success(dicEnum);
}
如果数据库变了的话,那么查询会先走一遍数据库,之后自动缓存
三、理论支持
@Cacheable 参数详解
在支持Spring Cache的环境下,对于使用@Cacheable标注的方法,Spring在每次执行前都会检查
Cache中是否存在相同key的缓存元素,如果存在就不再执行该方法,而是直接从缓存中获取结果进行返回,
否则才会执行并将返回结果存入指定的缓存中。@CachePut也可以声明一个方法支持缓存功能。
与@Cacheable不同的是使用@CachePut标注的方法在执行前不会去检查缓存中是否存在之前执行过的结果,
而是每次都会执行该方法,并将执行结果以键值对的形式存入指定的缓存中。
看完这里,不知道你有没有和我同样的疑问:“@CachePut每次都要去执行方法,那么缓存的意义何在?
”
@Cacheable与@CachePut注解联合使用才有意义!!!!!
https://blog.youkuaiyun.com/qq_38483435/article/details/105730125(这篇文章来解答)