一级和二级两层缓存
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>