Mybatis缓存机制

本文介绍了MyBatis的一级和二级缓存机制,并详细解释了如何全局、按namespace及statement级别开启二级缓存。此外,还介绍了如何利用redis与ehcache实现分布式缓存,并提供了配置示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一级和二级两层缓存

    Mybatis使用SqlSession级别的缓存为一级缓存,在同一个SqlSession中执行相同的sql会尝试命中缓存,SqlSession执行commit操作后会清空缓存。一级缓存默认开启。

    Mapper级别的缓存为二级缓存,可为多个SqlSession提供缓存数据,作用域是namespace。SqlSession执行同namespace下的相同SQL且传入的参数相同会命中缓存。SqlSession执行commit操作,会清空对应namespace下的缓存。二级缓存默认不开启。

 

开启二级缓存的方式

全局开启

<setting name="cacheEnabled" value="true" />

 

namespace开启

<cache eviction="FIFO" flushInterval="60000" size="512" readOnly="true" />

 

statement开启

<select id="findById" resultMap="userMap" useCache="false" />

<insert id="save" flushCache="true" />

 

分布式缓存

介绍

    结合redis、ehcache等实现。redis相关处于beta阶段,不建议用于线上服务。

ehcache : http://www.mybatis.org/ehcache-cache/index.html

redis : http://www.mybatis.org/redis-cache/

 

使用概述

  • 引入相关依赖,mybatis-redis | mybatis-ehcache。PS:redis cache尚无正式版本,不推荐用于生产环境。
<dependencies>
  ...
  <dependency>
    <groupId>org.mybatis.caches</groupId>
    <artifactId>mybatis-ehcache</artifactId>
    <version>1.1.0</version>
  </dependency>
  ...
</dependencies>
<dependencies>
  ...
  <dependency>
    <groupId>org.mybatis.caches</groupId>
    <artifactId>mybatis-redis</artifactId>
    <version>1.0.0-beta2</version>
  </dependency>
  ...
</dependencies>
  • 指定cache type.Ehcache包含两类cache类型
<mapper namespace="org.acme.FooMapper">
  <cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
  ...
</mapper>
<mapper namespace="org.acme.FooMapper">
  <cache type="org.mybatis.caches.ehcache.EhBlockingCache"/>
  ...
</mapper>

 

<mapper namespace="org.acme.FooMapper">
  <cache type="org.mybatis.caches.redis.RedisCache" />
  ...
</mapper>
  • 执行参数配置。ehache读取classpatch下的ehcache.xml进行配置。redis读取classpath下的redis.properties进行属性配置。此外ehcache支持xml级别的配置;
<mapper namespace="org.acme.FooMapper">
  <cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
    <property name="timeToIdleSeconds" value="3600"/><!--1 hour-->
    <property name="timeToLiveSeconds" value="3600"/><!--1 hour-->
    <property name="maxEntriesLocalHeap" value="1000"/>
    <property name="maxEntriesLocalDisk" value="10000000"/>
    <property name="memoryStoreEvictionPolicy" value="LRU"/>
  </cache>
  ...
</mapper>

 

转载于:https://my.oschina.net/SEyanlei/blog/908639

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值