三级缓存(Mybatis)

Mybatis:

一级缓存:session级别

一级缓存是MyBatis的核心缓存,是SqlSession级别的,这意味着只要在同一个SqlSession中,相同的查询就会从缓存中取得结果,例如:

SqlSession session = factory.openSession();
UserMapper mapper = session.getMapper(UserMapper.class);
User user1 = mapper.selectById(1);
User user2 = mapper.selectById(1);
System.out.println(user1 == user2);

二级缓存:mapper级别

二级缓存是Mapper级的缓存,默认是不开启的,需要手动开启二级缓存,实现二级缓存的时候,MyBatis要求返回的POJO必须是可序列化的。在mybatis-configuration.xml 加入配置,就会全局开启二级缓存:

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

或者在mapper.xml中添加此配置,MyBatis就会在这个namespace下启用二级缓存。这种缓存对于同一个namespace下的所有SqlSession都是有效的:

<cache/>

springboot配置开启二级缓存:

mybatis:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.example.demo.entity
  configuration:
    cache-enabled: true

二级缓存的测试代码如下:

SqlSession session1 = factory.openSession();
UserMapper mapper1 = session1.getMapper(UserMapper.class);
User user1 = mapper1.selectById(1);
session1.close();

SqlSession session2 = factory.openSession();
UserMapper mapper2 = session2.getMapper(UserMapper.class);
User user2 = mapper2.selectById(1);
session2.close();

System.out.println(user1 == user2);

虽然是两个SqlSession,但是由于启用了二级缓存,所以相同的查询只执行了一次。

三级缓存:全局级别

三级缓存是全局缓存,对所有的mapper都有效。MyBatis并未直接提供接口支持全局缓存,但是可以通过整合Ehcache,Redis等工具来实现。比如下面这样接入ehcache。首先,我们需要在项目的配置文件中引入相关的依赖。在Maven项目中,我们可以使用以下代码来引入依赖:

<dependency>
    <groupId>org.mybatis.caches</groupId>
    <artifactId>mybatis-ehcache</artifactId>
    <version>1.2.1</version>
</dependency>
<dependency>
    <groupId>org.ehcache</groupId>
    <artifactId>ehcache</artifactId>
    <version>3.8.1</version>
</dependency>

然后,我们需要在Mybatis的配置文件中进行相关的配置。需要配置ehcache的缓存管理器:

<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>

总结:

通过MyBatis的三级缓存,可以大大提高我们对数据库的查询效率,但是也需要注意,缓存也可能会导致脏读、幻读等问题,这些都需要在实际开发中去考虑和权衡。

MyBatis 的一级缓存 二级缓存 都不建议使用,它们只适用于单体项目,现在基本都是分布式或者微服务框架,使用的话会存在数据不一致问题。

posted @ 2024-07-29 14:22  轻寒  阅读(2)  评论(0编辑  收藏  举报