springboot+redis配置mybatis二级缓存

springboot+redis配置mybatis二级缓存

每天多学一点点~
闲来无事,研究一下mybatis一二级缓存
话不多说,这就开始吧…

1.mybatis一二级缓存

  1. 一级缓存
    mybatis对缓存提供支持,但是在没有配置的默认情况下,它只开启一级缓存,一级缓存只是相对于同一个SqlSession而言。所以在参数和SQL完全一样的情况下,我们使用同一个SqlSession对象调用一个Mapper方法,往往只执行一次SQL,因为使用SelSession第一次查询后,MyBatis会将其放在缓存中,以后再查询的时候,如果没有声明需要刷新,并且缓存没有超时的情况下,SqlSession都会取出当前缓存的数据,而不会再次发送SQL到数据库。
    简单来说:一级缓存就是sql语句的缓存
    在这里插入图片描述
    博主列了几个一级缓存常问问道的问题。

①、一级缓存的生命周期有多长?
  a、MyBatis在开启一个数据库会话时,会 创建一个新的SqlSession对象,SqlSession对象中会有一个新的Executor对象。Executor对象中持有一个新的PerpetualCache对象;当会话结束时,SqlSession对象及其内部的Executor对象还有PerpetualCache对象也一并释放掉。
  b、如果SqlSession调用了close()方法,会释放掉一级缓存PerpetualCache对象,一级缓存将不可用。
  c、如果SqlSession调用了clearCache(),会清空PerpetualCache对象中的数据,但是该对象仍可使用。
  d、SqlSession中执行了任何一个update操作(update()、delete()、insert()) ,都会清空PerpetualCache对象的数据,但是该对象可以继续使用
②、怎么判断某两次查询是完全相同的查询?
  mybatis认为,对于两次查询,如果以下条件都完全一样,那么就认为它们是完全相同的两次查询。
  a、传入的statementId
  b、查询时要求的结果集中的结果范围
  c、 这次查询所产生的最终要传递给JDBC java.sql.Preparedstatement的Sql语句字符串(boundSql.getSql() )
  d、传递给java.sql.Statement要设置的参数值

  1. 二级缓存
    MyBatis的二级缓存是Application级别的缓存,它可以提高对数据库查询的效率,以提高应用的性能。
    在这里插入图片描述
    SqlSessionFactory层面上的二级缓存默认是不开启的,二级缓存的开席需要进行配置,实现二级缓存的时候,MyBatis要求返回的POJO必须是可序列化的。 也就是要求实现Serializable接口,配置方法很简单,只需要在映射XML文件配置就可以开启缓存了,如果我们配置了二级缓存就意味着:
  • 映射语句文件中的所有select语句将会被缓存。
  • 映射语句文件中的所有insert、update和delete语句会刷新缓存。
  • 缓存会使用默认的Least Recently Used(LRU,最近最少使用的)算法来收回。
  • 根据时间表,比如No Flush Interval,(CNFI没有刷新间隔),缓存不会以任何时间顺序来刷新。
  • 缓存会存储列表集合或对象(无论查询方法返回什么)的1024个引用
  • 缓存会被视为是read/write(可读/可写)的缓存,意味着对象检索不是共享的,而且可以安全的被调用者修改,不干扰其他调用者或线程所做的潜在修改。

简单来说:二级缓存就是xml文件的namespace级别的缓存

2.sprongboot配置mybatis

在这里插入图片描述

#mybatis 配置
mybatis.mapper-locations=classpath:/mapper/*
mybatis.configuration.map-underscore-to-camel-case=true
mybatis.configuration.call-setters-on-nulls= true
# 开启mybatis 开启二级 缓存
mybatis.configuration.cache-enabled=true

3.springboot配置redis

yml配置

# redis设置
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.database=4
spring.redis.password=123456

配置类

@Configuration
public class RedisConfig {

    /**
     *  设置redis的序列化方式
     * @param redisConnectionFactory
     * @return
     */
    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setDefaultSerializer(new Jackson2JsonRedisSerializer<Object>(Object.class));
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }

}

4.redis集成mybatis二级缓存

配置redis二级缓存,只需要实现Cache这个接口就可以,话不多说,上代码。博主这里为了方便直接用redisTemplate;


/**
 * @Auther: 爆裂无球    redis 作为 mybatis的二级缓存
 * @Date: 2019/5/27 14:32
 * @Description:
 */
public class MybatisRedisCache implements Cache {

    private static final Logger logger = LoggerFactory.getLogger(MybatisRedisCache.class);

    // 读写锁
    private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock(true);

    private static RedisTemplate redisTemplate;

//    private RedisTemplate<String, Object> redisTemplate = SpringContextHolder.getBean("redisTemplate");

    private String id;

    public MybatisRedisCache(final String id) {
        if (id == null) {
            throw new IllegalArgumentException("Cache instances require an ID");
        }
        logger.info("Redis Cache id " + id);
        this.id = id;
    }

    @Override
    public String getId() {
        return this.id;
    }

    @Override
    public void putObject(Object key, Object value) {
        if (value != null) {
            // 向Redis中添加数据,有效时间是2天
            redisTemplate.opsForValue().set(key.toString(), value, 2, TimeUnit.DAYS);
        }
    }

    @Override
    public Object getObject(Object key) {
        try {
            if (key != null) {
                Object obj = redisTemplate.opsForValue().get(key.toString());
                return obj;
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return null;
    }

    @Override
    public Object removeObject(Object key) {
        try {
            if (key != null) {
                redisTemplate.delete(key.toString());
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return null;
    }

    @Override
    public void clear() {
        logger.info("清空缓存");
        try {
            Set<String> keys = redisTemplate.keys("*:" + this.id + "*");
            if (!CollectionUtils.isEmpty(keys)) {
                redisTemplate.delete(keys);
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }

    @Override
    public int getSize() {
        Long size = (Long) redisTemplate.execute(new RedisCallback<Long>() {
            @Override
            public Long doInRedis(RedisConnection connection) throws DataAccessException {
                return connection.dbSize();
            }
        });
        return size.intValue();
    }

    @Override
    public ReadWriteLock getReadWriteLock() {
        return this.readWriteLock;
    }

    public static void setRedisConnectionFactory(RedisTemplate redisTemplate) {
        MybatisRedisCache.redisTemplate = redisTemplate;
    }

在spring启动的时候,将redisTemplate注入到MybatisRedisCache类中


/**
 * @Auther: 爆裂无球   将redisTemplate注入
 * @Date: 2019/5/27 15:04
 * @Description:
 */
@Component
public class RedisCacheTransfer {


    @Autowired
    public void setJedisConnectionFactory(RedisTemplate redisTemplate) {
        MybatisRedisCache.setRedisConnectionFactory(redisTemplate);
    }




}

5.测试

  1. 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.yltx.app.dao.Userdao">
    <!--cache标签内属性:-->

    <!--eviction:定义缓存移除机制(算法),默认为LRU(最近最少使用),它会清除最少使用的数据,还有一种FIFO(先进先出),它会清除最先进来的数据。-->

    <!--flushInterval:定义缓存刷新周期,单位为毫秒。-->

    <!--size:标识缓存cache中容纳的最大元素,默认为1024。-->

    <!--readOnly:默认为false,可配置为true缓存只读。-->

    <cache type="com.yltx.app.redis.MybatisRedisCache">
        <property name="eviction" value="LRU" />
        <property name="flushInterval" value="6000000" />
        <property name="size" value="1024" />
        <property name="readOnly" value="false" />
    </cache>

    <resultMap id="BaseResultMap" type="com.yltx.app.bean.User" >


        <id column="id" property="id" jdbcType="VARCHAR" />
        <result column="username" property="username" jdbcType="VARCHAR" />
        <result column="sex" property="sex" jdbcType="VARCHAR" />

    </resultMap>

    <select id="getAll" resultMap="BaseResultMap" useCache="true">
        select * from user
    </select>

    <select id="getAll2" resultMap="BaseResultMap" useCache="true">
        select id from user
    </select>

</mapper>
  1. mapper写法
/**
 * @Auther: 爆裂无球          @CacheNamespace            主要用于mybatis二级缓存,但是要注意:配置文件和接口注释是不能够配合使用的。只能通过全注解的方式或者全部通过xml配置文件的方式使用
 * @Date: 2019/4/26 10:11
 * @Description:
 */
@CacheNamespace(implementation = MybatisRedisCache.class)
public interface Userdao {




    @Insert("insert into user (id,username,sex) values (#{id},#{username},#{sex})")
    int insert(User user);


    @Select("   select * from user ")
    List<User> getAll();

    @Select("   select id from user ")
    List<String> getAll2();
}

注:若xml中写了cache标签,则mapper中不要加@CacheNamespace注解,不然会冲突的;两者取其一

  1. 验证
    在这里插入图片描述

如图,第一次查询的时候打印除了sql语句,其他四次走了缓存;Cache Hit Ratio是缓存命中率;再点一次,就全部是1了。因为此时已经在redis中产生了缓存;
在这里插入图片描述
在这里插入图片描述

此时,若在 其中插入一条修改语句(增删改),则会清空一次缓存,再重新放入;目的:为了数据的一致性;
在这里插入图片描述

6.结语

世上无难事,只怕有心人,每天积累一点点,fighting!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值