MyBatis的二級緩存整合redis

MyBatis 自帶的二級緩存存在的問題

在前面我們使用 @CacheNamespace​ 實現了 430.MyBatis的二級緩存 ,這個底層使用 HashMap​ 來實現。在 單機環境 下沒有問題,但是在 分佈式環境 下就不行了。

MyBatis 二級緩存在分佈式環境下的問題解決

爲了解決這個問題,可以使用 分佈式緩存 保存 MyBatis 二級緩存的數據。

怎麼自定義 MyBatis 的二級緩存

可以在 @CacheNamespace​ 上面加上 implementation , 例如,默認的緩存可以寫成:

@CacheNamespace(implementation = PerpetualCache.class)

使用 redis 作爲 MyBatis 的二級緩存

使用 redis 作爲 MyBatis 二級緩存的步驟如下:

導入 mybatis-redis 的 pom 包

<dependency>
    <groupId>org.mybatis.caches</groupId>
    <artifactId>mybatis-redis</artifactId>
    <version>1.0.0-beta2</version>
</dependency>

修改,IUserMapper ​,加上相關注解

請參考:https://github.com/terwer/senior-java-engineer-road/blob/main/p7-skill/framework/mybatis/mybatis-annotation/src/main/java/com/terwergreen/mapper/IUserMapper.java#L25

@CacheNamespace(implementation = RedisCache.class)
public interface IUserMapper {

resource根目錄 ​加上 redis.properties​ 配置文件

host=localhost
port=6379
password=
database=0

特別提醒:這裏的 配置 不要寫錯了。

注意: 查詢方法 ​也得地加上 @Options(useCache = true)​ 註解

@Options(useCache = true)
@Select("select * from user where id=#{id}")
User findUserById(Integer id);

測試:

請參考:https://github.com/terwer/senior-java-engineer-road/blob/main/p7-skill/framework/mybatis/mybatis-annotation/src/test/java/com/terwergreen/mapper/SecondCacheTest.java#L30

@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);
}

結果:

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

查看 redis 緩存

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章