Ehcache缓存配置及使用

Ehcache缓存配置及使用
一、Pom.xml添加依赖
Pom.xml添加如下依赖:

<!--开启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>

二、添加ehcache.xml配置文件
配置在与application.yml同级目录下,文件内容如下:

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">

    <diskStore path="java.io.tmpdir"/>

    <!--defaultCache:echcache的默认缓存策略  -->
    <!--
        name:cache唯一标识
        eternal:缓存是否永久有效
        maxElementsInMemory:内存中最大缓存对象数
        overflowToDisk(true,false):缓存对象达到最大数后,将缓存写到硬盘中
        diskPersistent:硬盘持久化
        timeToIdleSeconds:缓存清除时间
        timeToLiveSeconds:缓存存活时间
        diskExpiryThreadIntervalSeconds:磁盘缓存的清理线程运行间隔
        memoryStoreEvictionPolicy:缓存清空策略
        1.FIFO:first in first out 先进先出
        2.LFU: Less Frequently Used 一直以来最少被使用的
        3.LRU:Least Recently Used  最近最少使用的
        persistence strategy 如果内存满了,溢出到硬盘
    -->
    <defaultCache
            maxElementsInMemory="10000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            maxElementsOnDisk="10000000"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU">
        <persistence strategy="localTempSwap"/>
    </defaultCache>
    <cache name="queryPage"
           maxElementsInMemory="10000"
           eternal="false"
           timeToIdleSeconds="120"
           timeToLiveSeconds="120"
           maxElementsOnDisk="10000000"
           diskExpiryThreadIntervalSeconds="120"
           memoryStoreEvictionPolicy="LRU">
        <persistence strategy="localTempSwap"/>
    </cache>
</ehcache>

三、添加application.yml配置
application.yml添加如下内容:

#  ehcache作为缓存
  cache:
    type: ehcache
    ehcache:
      config: classpath:ehcache.xml

四、DemoApplication添加注解
添加@EnableCaching,开启缓存
在这里插入图片描述

五、缓存使用
注意:返回的实体类需要做序列化,否则查询缓存的时候会报错,实体类User实现Serializable接口
在这里插入图片描述

具体使用:
@Cacheable : Spring在每次执行前都会检查Cache中是否存在相同key的缓存元素,如果存在就不再执行该方法,而是直接从缓存中获取结果进行返回,否则才会执行并将返回结果存入指定的缓存中。
@CacheEvict : 清除缓存,调用方法后从缓存中删除对应key的数据。
@CachePut : @CachePut也可以声明一个方法支持缓存功能。使用@CachePut标注的方法在执行前不会去检查缓存中是否存在之前执行过的结果,而是每次都会执行该方法,并将执行结果以键值对的形式存入指定的缓存中。
这三个方法中都有两个主要的属性:value 指的是 ehcache.xml 中的缓存策略空间;key 指的是缓存的标识,同时可以用 # 来引用参数。

例子:
在这里插入图片描述

六、从缓存查询和不从缓存查询比对
在这里插入图片描述

后面对每页的查询都是直接从缓存读取,可以看到没有查询语句打印在控制台,时间为0ms或者1ms,从数据库查询则需要耗费更多的时间,日志文件中记录了查询的时间。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值