Mybaits-缓存设置

  1. 一级缓存:
    Mybatis 的一级缓存存在于 SqlSession 的声明周期中, 在同一个 SqlSession 中查询时, Mybatis 会把执行的方法和参数通过算法生成缓存的键值, 将键值和查询结果存入一个 Map 对象中. 如果同一个 SqlSession 中执行的方法和参数完全一致, 那么通过算法会生成相同的键值, 当 Map 缓存对象中已经存在该键值时, 则会返回缓存中的对象.

    @Test
    public void testCache() {
        SqlSession sqlSession = getSqlSession();
        User user = null;
        try {
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            user = userMapper.selectById(1);
            // 注意这里并没有更新数据库
            user.setUsername("New Name");
            
            User user1 = userMapper.selectById(1);
            // user1 的 username 和 "New Name" 相等
            Assert.assertEquals("New Name", user1.getUsername());
            // user1 和 user 是同一个对象, user1 是从缓存中获取的
            Assert.assertEquals(user, user1);
        } finally {
            sqlSession.close();
        }
        
        sqlSession = getSqlSession();
        try {
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            User user2 = userMapper.selectById(1);
            // 由于之前的 SqlSession 关闭了, 所以之前的缓存不存在了, 所以这里获取的数据相当于又是从数据库查询出的
            Assert.assertNotEquals("New Name", user2.getUsername());
            // 执行删除操作
            userMapper.deleteById(2);
            User user3 = userMapper.selectById(1);
            // 由于执行了删除操作, 清空了缓存, user3 又是从数据库中查询出来的, 因此 user2 和 user3 不是同一个实例
            Assert.assertNotEquals(user2, user3);
        }
    }
    

    若想要每次都从数据库获取对象, 需要在 mapper.xml 中进行配置.

     ```
     <!--这里增加 flushCache 为 true 的配置-->
     <select id="selectById" flushCache="true" resultMap="userMap">
         SELECT *
           FROM user
          WHERE id = #{id} 
     </select>
     ```
    
  2. 二级缓存:
    二级缓存可以理解为存在于 SqlSessionFactory 的生命周期中. Mybaits 的全局配置 settings 中有一个参数 cacheEnabled, 这个参数是二级缓存的全局开关, 默认值 true. Mybatis 的二级缓存是和命名空间绑定的, 即二级缓存需要配置在 Mapper.xml 映射文件中.

    • Mapper.xml 中配置二级缓存

      <mapper namespace="study.mapper.UserMapper">
          <cache/>
      </mapper>
      

      默认配置的缓存效果:

      • 映射文件中的所有 SELECT 语句将会被缓存
      • 映射语句文件中的所有 INSERT, UPDATE, DELETE 语句会刷新缓存
      • 缓存会使用 Least Recently Used 算法来回收
      • 根据时间表(no Flush Interval 没有刷新间隔), 缓存不会以任何时间顺序来刷新
      • 缓存会存储集合或对象的 1024 个引用
      • 缓存会被视为 read/write 的, 意味着对象检索不是共享的, 而且可以安全地被调用者修改, 而不受其它调用者或线程所做的潜在修改
        cache 可以配置的属性:
      • eviction(收回策略)
        • LRU(最近最少使用的): 移除最长时间不被使用的对象
        • FIFO(先进先出): 按对象进入缓存的顺序来移除它们
        • SOFT(软引用): 移除基于垃圾回收器状态和软引用规则的对象
        • WEAK(弱引用):更积极地移除基于来及收集器状态和弱引用规则的对象
      • flushInterval(刷新间隔): 可以被设置为任意的正整数, 它代表一个合理的毫秒形式的时间段
      • size: 可以设置为任意的正整数, 它表示要记住缓存的对象数目和运行环境的可用内存资源数目
      • readOnly: 只读. 只读的缓存会给所有调用者返回缓存对象的相同实例; 可读写的缓存会通过序列化返回缓存对象的拷贝
    • Mapper 接口中配置二级缓存
      使用注解方式时, 如果想对注解方法启用二级缓存, 还需要在 Mapper 接口中进行配置; 如果 Mapper 接口也存在对应的 xml 映射文件, 两者同时开启缓存时, 还需要特殊配置.

      • 当只使用注解方式配置二级缓存时, 需要增加如下配置:
      @CacheNamespace
      public interface UserMapper {
          
      }
      
      • 当同时使用注解方式和 xml 映射文件时, 应该使用参照缓存:
      @CacheNamespaceRef(UserMapper.class)
      public interface UserMapper {
          
      }
      
    • 二级缓存使用:
      当配置为可读写的缓存时, 使用 SerializedCache 序列化缓存来实现可读写缓存类, 并通过序列化和反序列化来保证通过缓存获取数据, 得到的是一个新的实例. 这要求所有被序列化的对象必须实现 Serializable 接口.

      public void testCache() {
          SqlSession sqlSession = getSqlSession();
          User user = null;
          try {
              UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
              user = userMapper.selectById(1);
              // 注意这里并没有更新数据库
              user.setUsername("New Name");
              // 这里由于 sqlSession 还没有关闭, 所以这里使用的是一级缓存
              User user1 = userMapper.selectById(1);
              Assert.assertEquals("New Name", user1.getUsername());
              Assert.assertEquals(user, user1);
          } finally {
              // 在关闭 sqlSession 的时候, 会将对象缓存到二级缓存之中了
              sqlSession.close();
          }
          
          sqlSession = getSqlSession();
          try {
              UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
              user1 = userMapper.selectById(1);
              // 由于从二级缓存中获取对象, 所以即使之前没有更新数据库, 这里 user1 的 username 仍然为 New Name
              Assert.assertEquals("New Name", user1.getUsername());
              // 由于二级缓存是通过反序列化生成新的对象, 所以这两个对象不是同一个实例
              Assert.assertEquals(user, user1);
          } finally {
              sqlSession.close();
          }
      }
      
    • 集成 EhCache 缓存:
      添加 Maven 依赖

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

      src/main/resources 目录下增加 ehcache.xml 文件

      <?xml version="1.0" encoding="UTF-8"?>
      <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:noNamespaceSchemaLocation="ehcache.xsd"
          updateCheck="false" monitoring="autodetect"
          dynamicaConfig="true">
          <diskStore path="D:/cache"/>
          <defaultCache
              maxElementsInMemory="3000"
              eternal="false"
              copyOnRead="true"
              copyOnWrite="true"
              timeToIdleSeconds="3600"
              timeToLiveSeconds="3600"
              overflowToDisk="true"
              diskPersistent="true"/>
      </ehcache>
      

      copyOnRead 含义是, 判断从缓存中读取数据时是返回对象的引用还是复制一个对象返回. 若为 false, 即返回数据的引用; 若为 true, 即每次读取缓存时都会复制一个新的实例.

      copyOnWrite 含义是, 判断写入缓存时是直接缓存对象的引用还是复制一个对象缓存.

      在 mapper.xml 中配置:

      <mapper namespace="study.mapper.UserMapper">
          <cache type="org.mybatis.caches.ehcache.EhcacheCache"/>
      </mapper>
      
    • 集成 Redis 缓存
      在 pom.xml 中添加依赖

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

      在 src/main/resources 目录下增加 redis.properties 文件

      host=localhost
      port=6379
      connectionTimeout=5000
      soTimeout=5000
      password=123456
      database=0
      clientName=test
      

      在 mapper.xml 中配置:

      <mapper namespace="study.mapper.UserMapper">
          <cache type="org.mybatis.caches.redis.RedisCache"/>
      </mapper>
      

      使用 redis 缓存可以将分布式应用连接到同一个缓存服务器, 实现分布式应用间的缓存共享.

  3. 脏数据的产生和避免:
    当一个 mapper 文件中的 SQL 语句涉及到关联表查询时, 设计这些表的增, 删, 改操作通常不在一个映射文件中, 它们的命名空间不同, 因此当有数据变化时, 多表查询的缓存未必会被清空, 这种情况下就会产生脏数据.

    <select id="selectUserAndRoleById" resultType="study.User">
        SELECT u.id
               u.username
               r.id AS "role.id"
               r.name AS "role.name"
          FROM user u
               INNER JOIN user_role
                       ON user_role.user_id = u.id
               INNER JOIN role r
                       ON r.id = user_role.role_id
         WHERE u.id = #{id}
    </select>
    
    @Test
    public void testCache() {
        SqlSession sqlSession = getSqlSession();
        try {
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            User user = userMapper.selectUserAndRoleById(1);
        } finally {
            sqlSession.close();
        }
        sqlSession = getSqlSession();
        try {
            RoleMapper roleMapper = sqlSession.getMapper(RoleMapper.class);
            Role role = roleMapper.selectById(1);
            role.setName("脏数据");
            roleMapper.updateById(role);
            // 提交修改
            sqlSession.commit();
        } finally {
            sqlSession.commit();
        }
        
        sqlSession = getSqlSession();
        try {
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
            RoleMapper roleMapper = sqlSession.getMapper(RoleMapper.class);
            User user = userMapper.selectUserAndRoleById(1);
            Role role = roleMapper.selectById(2);
            Role roleInUser = user.getRole();
            // 注意这里role.getName() 和 roleInUser.getName() 的值不相等, role 的 name 已经被修改了, 但是 roleInUser 的 name 仍然为之前未修改的值, 这就出现了脏数据
            Assert.assertNotEquals(role.getName(), roleInUser.getName());
        } finally {
            sqlSession.close();
        }
    }
    

    可以让几个会关联的 ER 表同时使用同一个二级缓存. 修改 UserMapper.xml 配置

    <mapper namespace="study.mapper.UserMapper">
        <cache-ref name="study.mapper.RoleMapper"/>
    </mapper>
    
  4. 参考:
    [1] : MyBatis从入门到精通

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值