初识ehcache

一、用途:不用每次都从数据库查,查询一次后放入到缓存,之后相同的查询走缓存。对应一些经常查询的方法,可以设置缓存

二、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(这篇文章来解答)

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值