MyBatis的二级缓存整合redis
# MyBatis 自带的二级缓存存在的问题
在前面我们使用 @CacheNamespace
实现了 430.MyBatis的二级缓存 ,这个底层使用 HashMap
来实现。在 单机环境 下没有问题,但是在 分布式环境 下就不行了。
# MyBatis 二级缓存在分布式环境下的问题解决
为了解决这个问题,可以使用 分布式缓存 保存 MyBatis 二级缓存的数据。
# 怎么自定义 MyBatis 的二级缓存
可以在 @CacheNamespace
上面加上 implementation , 例如,默认的缓存可以写成:
@CacheNamespace(implementation = PerpetualCache.class)
1
# 使用 redis 作为 MyBatis 的二级缓存
使用 redis 作为 MyBatis 二级缓存的步骤如下:
导入 mybatis-redis 的 pom 包
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-redis</artifactId>
<version>1.0.0-beta2</version>
</dependency>
1
2
3
4
5
2
3
4
5
修改,IUserMapper ,加上相关注解
@CacheNamespace(implementation = RedisCache.class)
public interface IUserMapper {
1
2
2
resource
根目录 加上 redis.properties
配置文件
host=localhost
port=6379
password=
database=0
1
2
3
4
2
3
4
特别提醒:这里的 配置 不要写错了。
注意: 查询方法 也得地加上 @Options(useCache = true)
注解
@Options(useCache = true)
@Select("select * from user where id=#{id}")
User findUserById(Integer id);
1
2
3
2
3
测试:
@Test
public void secondLevelCache() {
SqlSession sqlSession1 = sqlSessionFactory.openSession();
SqlSession sqlSession2 = sqlSessionFactory.openSession();
IUserMapper userMapper1 = sqlSession1.getMapper(IUserMapper.class);
IUserMapper userMapper2 = sqlSession2.getMapper(IUserMapper.class);
User user1 = userMapper1.findUserById(1);
// 清空一级缓存
sqlSession1.close();
User user2 = userMapper2.findUserById(1);
System.out.println(user1 == user2);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
结果:
Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@6b81ce95]
==> Preparing: select * from user where id=?
==> Parameters: 1(Integer)
<== Columns: id, username, password, birthday
<== Row: 1, lisi, 123, 2019-12-12
<== Total: 1
Resetting autocommit to true on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@6b81ce95]
Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@6b81ce95]
Returned connection 1803669141 to pool.
Cache Hit Ratio [com.terwergreen.mapper.IUserMapper]: 0.5
false
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
查看 redis 缓存
编辑 (opens new window)
上次更新: 2023/02/22, 13:47:25
- 01
- 解决css部分border被圆角切掉之后圆角的边框消失问题03-18
- 02
- 使用TypeScript开发一个自定义的Node-js前端开发脚手架03-08
- 03
- Github-Actions使用release-please实现自动发版03-06