Springboot项目中为Mybatis添加ehcache开启二级缓存

一、添加ehcache的依赖jar包

<org.mybatis-ehcache.version>1.0.0</org.mybatis-ehcache.version>
<org.ehcache.version>3.2.0</org.ehcache.version>
<!-- ehcache -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis-ehcache</artifactId>
    <version>${org.mybatis-ehcache.version}</version>
</dependency>
<dependency>
    <groupId>org.ehcache</groupId>
    <artifactId>ehcache</artifactId>
    <version>${org.ehcache.version}</version>
</dependency>
<!-- /ehcache -->

二、添加ehcache配置文件

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">

   <!-- 磁盘缓存位置 -->
   <diskStore path="java.io.tmpdir/ehcache"/>

   <!-- 默认缓存 -->
   <defaultCache
         maxEntriesLocalHeap="10000"
         eternal="false"
         timeToIdleSeconds="120"
         timeToLiveSeconds="120"
         maxEntriesLocalDisk="10000000"
         diskExpiryThreadIntervalSeconds="120"
         memoryStoreEvictionPolicy="LRU">
      <persistence strategy="localTempSwap"/>
   </defaultCache>

   <!--自定义缓存:customCache -->
   <cache name="customCache"
         maxElementsInMemory="1000"
         eternal="false"
         timeToIdleSeconds="5"
         timeToLiveSeconds="5"
         overflowToDisk="false"
         memoryStoreEvictionPolicy="LRU"/>

</ehcache>

三、在application.yml中添加ehcache的配置

在spingboot配置中添加ehcache配置

spring:
  #配置ehcache
  cache:
    type: ehcache
    ehcache:
      config: classpath:/config/ehcache.xml

在mybatis配置中开启二级缓存

mybatis:
  configuration:
    cache-enabled: true #开启应用mybatis二级缓存(mapper-namespace)

四、在mapper.xml文件中配置cache

在mapper namespace=""中添加cache

<!-- 开启mapper的二级缓存, type:指定cache接口的实现类,mybatis默认使用PerpetualCache 要和ehcache整合,需要配置type为ehcache实现cache接口的类型  -->
<cache type="org.mybatis.caches.ehcache.EhcacheCache"></cache>

或者我自定义配置内容

<cache type='org.mybatis.caches.ehcache.EhcacheCache'>
        <propertyname='timeToIdleSeconds'value='3600'/>
        <propertyname='timeToLiveSeconds'value='3600'/>
        <!-- 同ehcache参数maxElementsInMemory-->
        <propertyname='maxEntriesLocalHeap'value='1000'/>
        <!-- 同ehcache参数maxElementsOnDisk -->
        <propertyname='maxEntriesLocalDisk'value='10000000'/>
        <propertyname='memoryStoreEvictionPolicy'value='LRU'/>
</cache>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值