mybatis整合ehcache做三级缓存
为什么要使用第三级缓存
mybatis二级缓存对细粒度的数据级别的缓存实现不好,对同时缓存较多条数据的缓存,比如如下需求:
对商品信息进行缓存,由于商品信息查询访问量大,且要求用户每次都能查询最新的商品信息,此时如果使用mybatis的二级缓存就无法实现---当一个商品变化时只刷新该商品的缓存信息而不刷新其他商品的信息。
因为mybatis的二级缓存区域以mapper为单位划分,当一个商品信息变化会将所有商品信息的缓存数据全部清空。
解决此类问题需要在业务层根据需求对数据进行针对性的缓存,即需要使用三级缓存。
原生mybatis整合ehcache做三级缓存
引入mybatis官方提供的依赖mybatis-ehcache
<!-- mybatis-ehcache用的是1.1.0版本-->
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.1.0</version>
</dependency>
<!-- 这里原生mybatis用的是2.1.3版本 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
在springboot项目的yml配置文件里配置mybatis
要开启mybatis.configuration.cache-enabled=true
mybatis:
type-aliases-package: com.example.demo.orm.po
mapper-locations: classpath:mappers/*Mapper.xml
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
map-underscore-to-camel-case: true
# 开启全局缓存(mybatis二级缓存),默认不会开启,需要程序员配置开启
cache-enabled: true
在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">
<!--
diskStore:为缓存路径,ehcache分为内存和磁盘两级,此属性定义磁盘的缓存位置。参数解释如下:
user.home – 用户主目录
user.dir – 用户当前工作目录
java.io.tmpdir – 默认临时文件路径 win7里是 C:\Users\Administrator\AppData\Local\Temp 目录
-->
<diskStore path="java.io.tmpdir/Tmp_EhCache"/>
<!--
defaultCache:默认缓存策略,当ehcache找不到定义的缓存时,则使用这个缓存策略。只能定义一个。
-->
<!--
name:缓存名称。
maxElementsInMemory:缓存最大数目
maxElementsOnDisk:硬盘最大缓存个数。
eternal:对象是否永久有效,一但设置了,timeout将不起作用。
overflowToDisk:是否保存到磁盘,当系统当机时
timeToIdleSeconds:设置对象在失效前的允许闲置时间(单位:秒)。仅当eternal=false对象不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大。
timeToLiveSeconds:设置对象在失效前允许存活时间(单位:秒)。最大时间介于创建时间和失效时间之间。仅当eternal=false对象不是永久有效时使用,默认是0.,也就是对象存活时间无穷大。
diskPersistent:是否缓存虚拟机重启期数据 Whether the disk store persists between restarts of the Virtual Machine. The default value is false.
diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区。
diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒。
memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用)。
clearOnFlush:内存数量最大时是否清除。
memoryStoreEvictionPolicy:可选策略有:LRU(最近最少使用,默认策略)、FIFO(先进先出)、LFU(最少访问次数)。
FIFO,first in first out,这个是大家最熟的,先进先出。
LFU, Less Frequently Used,就是上面例子中使用的策略,直白一点就是讲一直以来最少被使用的。如上面所讲,缓存的元素有一个hit属性,hit值最小的将会被清出缓存。
LRU,Least Recently Used,最近最少使用的,缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存。
-->
<defaultCache
eternal="false"
maxElementsInMemory="10000"
overflowToDisk="true"
diskPersistent="true"
timeToIdleSeconds="1800"
timeToLiveSeconds="259200"
memoryStoreEvictionPolicy="LRU"/>
</ehcache>
在需要使用ehcache缓存的mapper.xml里配置cache标签
如:在AccountMapper.xml里配置
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.demo.orm.dao.AccountMapper">
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
<!-- ehcache 用作mybatis的三级缓存时
,只会对select语句进行缓存,每次遇到其他语句如insert,update,delete则会清空缓存
即:新插入的数据,或修改的数据,只有当立即select时,会缓存到Ehcache中。
select 结果缓存到Ehcache后,再次查询相同数据时,会命中Ehcache缓存;
Ehcache默认配置是LRU, 缓存的内容是 最近最少使用的 ,
缓存的元素有一个时间戳,当缓存容量满了,而又需要腾出地方来缓存新的元素的时候,
那么现有缓存元素中时间戳离当前时间最远的元素将被清出缓存
-->
<resultMap id="BaseResultMap"
type="com.example.demo.orm.po.Account">
<id column="id" jdbcType="BIGINT" property="id"/>
<result column="username" jdbcType="VARCHAR" property="username"/>
<result column="password_ciper" jdbcType="VARCHAR" property="passwordCiper"/>
</resultMap>
<select id="findOneById" resultMap="BaseResultMap">
select * from t_account where id = #{id}
</select>
<select id="selectUserList"
parameterType="com.example.demo.orm.po.Account"
resultMap="BaseResultMap">
select * from t_account
<where>
<if test="id != null">
and id = #{id}
</if>
<if test="username != null and username != '' ">
and username = #{username}
</if>
<if test="passwordCiper != null and passwordCiper != '' ">
and password_ciper = #{passwordCiper}
</if>
</where>
</select>
<insert id="insertOne"
useGeneratedKeys="true"
keyProperty="id"
parameterType="com.example.demo.orm.po.Account">
insert into t_account(username,password_ciper)
values (#{username},#{passwordCiper})
</insert>
</mapper>
测试Ehcache缓存效果
@Test
void test81902(){
//连续执行2次相同的select操作
System.out.println(accountMapper.findOneById(17));
System.out.println(accountMapper.findOneById(17));
}
2023-06-19 19:51:41.924 INFO 6356 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2023-06-19 19:51:42.186 INFO 6356 --- [ main] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
JDBC Connection [HikariProxyConnection@1502971166 wrapping com.mysql.cj.jdbc.ConnectionImpl@48a2db72] will not be managed by Spring
==> Preparing: select * from t_account where id = ?
==> Parameters: 17(Integer)
<== Columns: id, username, password, password_ciper
<== Row: 17, ert, sgvf23t, 1a9777393e7fda54
<== Total: 1
2023-06-19 19:51:42.452 INFO 6356 --- [ main] c.e.demo.plugin.EncryptDecryptUtil : passwordCiper字段需要解密,1a9777393e7fda54解密后的值是sgvf23t
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@518ddd3b]
Account(id=17, username=ert, password=sgvf23t, passwordCiper=sgvf23t)
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@72443081] was not registered for synchronization because synchronization is not active
Cache Hit Ratio [com.example.demo.orm.dao.AccountMapper]: 0.5
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@72443081]
Account(id=17, username=ert, password=sgvf23t, passwordCiper=sgvf23t)
Cache Hit Ratio [com.example.demo.orm.dao.AccountMapper]: 0.5
意思是缓存命中了AccountMapper,命中率0.5