二级缓存是多个SqlSession共享的,其作用域是mapper的同一个namespace,不同的sqlSession两次执行相同namespace下的sql语句且向sql中传递参数也相同即最终执行相同的sql语句,第一次执行完毕会将数据库中查询的数据写到缓存(内存),第二次会从缓存中获取数据将不再从数据库查询,从而提高查询效率。Mybatis默认没有开启二级缓存需要在setting全局参数中配置开启二级缓存。

下面是使用Redis来作为Mybatis二级缓存的实例:

主要的三个class:RedisCache,RedisConfig,RedisCacheTransfer。其他的都是一些配置。

RedisCache继承mybatis的Cache接口,用于建立redis与mybatis连接关系
RedisConfig配置redis相关参数,用于建立spring中的redis client与redis服务器建立连接
RedisCacheTransfer获取依赖注入的JedisConnectionFactory类,这个类会在RedisCache中用到,很重要

application.properties

在application.properties文件中配置Redis,Mybatis,开启Mybatis二级缓存等:

#\u914D\u7F6E\u524D\u7AEF\u6A21\u5F0F
#spring.thymeleaf.mode=legacyhtml5
#\u914D\u7F6Ejdbc
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#\u914D\u7F6E\u6570\u636E\u5E93
spring.datasource.url=jdbc:mysql://10.10.10.10:3306/sc?useUnicode=true&characterEncoding=UTF8&useServerPrepStmts=true&prepStmtCacheSqlLimit=256&cachePrepStmts=true&prepStmtCacheSize=256&rewriteBatchedStatements=truespring.datasource.username=root
spring.datasource.password=123456spring.redis.host = 10.10.10.11
spring.redis.password=123456
spring.redis.port=6379
spring.redis.database=0
spring.redis.timeout=0spring.redis.pool.ma-active=8#first.datasource.driver-class-name=com.mysql.jdbc.Driver
#first.datasource.url=jdbc:mysql://192.168.1.163:3306/testdemo1?characterEncoding=UTF-8
#first.datasource.username=root
#first.datasource.password=root
#
#second.datasource.driver-class-name=com.mysql.jdbc.Driver
#second.datasource.url=jdbc:mysql://192.168.1.163:3306/testdemo?characterEncoding=UTF-8
#second.datasource.username=root
#second.datasource.password=root#\u914D\u7F6E\u5C38\u4F53\u7C7B\u6620\u5C04\u8DEF\u5F84
mybatis.typeAliasesPackage=com.cetc.uavsystem.entity
#\u914D\u7F6EMapper\u6587\u4EF6\u6620\u5C04\u8DEF\u5F84
mybatis.mapper-locations=classpath:/mapper/*Mapper.xml
#\u914D\u7F6Emybatis\u914D\u7F6E\u6587\u4EF6
mybatis.config-location=classpath:mybatis-config.xml 

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><artifactId>spring-boot-student-mybatis-redis</artifactId><packaging>jar</packaging><name>spring-boot-student-mybatis-redis</name><description>Mybatis Redis for Spring Boot</description><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-student</artifactId><version>0.0.1-SNAPSHOT</version><relativePath /></parent><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>1.3.0</version></dependency><!--pagehelper --><dependency><groupId>com.github.pagehelper</groupId><artifactId>pagehelper-spring-boot-starter</artifactId><version>1.1.1</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.31</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-ehcache</artifactId><version>1.0.0</version></dependency></dependencies></project>

Redis配置类替换序列化实现方式以及redis获取配置文件 RedisConfig

/*** */
package com.cetc.uavsystem.redis.cache;import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;import redis.clients.jedis.JedisPoolConfig;/*** @author Mickle_zhang*配置文件*/
@Configuration
public class RedisConfig {//    @Value("$spring.redis.pool.maxIdle}")
//  private int maxIdle;
//  @Value("${spring.redis.pool.maxTotal}")
//  private int maxTotal;
//  @Value("${spring.redis.pool.maxWaitMillis}")
//  private long maxWaitMillis;
//  @Value("${spring.redis.pool.minIdle}")
//  private int minIdle;@Beanpublic JedisPoolConfig getRedisConfig(){JedisPoolConfig config = new JedisPoolConfig();
//        config.setMaxIdle(maxIdle);
//        config.setMaxTotal(maxTotal);
//        config.setMaxWaitMillis(maxWaitMillis);
//        config.setMinIdle(minIdle);return config;}@Value("${spring.redis.host}")private String host;@Value("${spring.redis.port}")private int port;@Value("${spring.redis.database}")private int database;@Value("${spring.redis.password}")private String password;@Value("${spring.redis.timeout}")private int timeout;@Bean(name = "jedisConnectionFactory")public JedisConnectionFactory getConnectionFactory(){JedisConnectionFactory factory = new JedisConnectionFactory();JedisPoolConfig config = getRedisConfig();factory.setPoolConfig(config);factory.setHostName(host);factory.setPort(port);factory.setDatabase(database);factory.setPassword(password);factory.setTimeout(timeout);return factory;}@Bean(name = "redisTemplate")public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();redisTemplate.setConnectionFactory(redisConnectionFactory);Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class);ObjectMapper om = new ObjectMapper();om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);  jackson2JsonRedisSerializer.setObjectMapper(om);// 设置值(value)的序列化采用Jackson2JsonRedisSerializer。redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);// 设置键(key)的序列化采用StringRedisSerializer。redisTemplate.setKeySerializer(new StringRedisSerializer());redisTemplate.afterPropertiesSet();return redisTemplate;}
}

Spring容器获取Bean工具类SpringContextHolder

通过Spring Aware(容器感知)来获取到ApplicationContext,然后根据ApplicationContext获取容器中的Bean。

/*** */
package com.cetc.uavsystem.redis.cache;import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;/*** @author Mickle_zhang**/
@Component
public class SpringContextHolder implements ApplicationContextAware{private static ApplicationContext applicationContext;/*** 实现ApplicationContextAware接口的context注入函数, 将其存入静态变量.*/public void setApplicationContext(ApplicationContext applicationContext) {SpringContextHolder.applicationContext = applicationContext; // NOSONAR}/*** 取得存储在静态变量中的ApplicationContext.*/public static ApplicationContext getApplicationContext() {checkApplicationContext();return applicationContext;}/*** 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.*/@SuppressWarnings("unchecked")public static <T> T getBean(String name) {checkApplicationContext();return (T) applicationContext.getBean(name);}/*** 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.*/@SuppressWarnings("unchecked")public static <T> T getBean(Class<T> clazz) {checkApplicationContext();return (T) applicationContext.getBeansOfType(clazz);}/*** 清除applicationContext静态变量.*/public static void cleanApplicationContext() {applicationContext = null;}private static void checkApplicationContext() {if (applicationContext == null) {throw new IllegalStateException("applicaitonContext未注入,请在applicationContext.xml中定义SpringContextHolder");}}
}

自定的Mybatis缓存RedisCache

自定义缓存需要实现Mybatis的Cache接口,我这里将使用Redis来作为缓存的容器。

package com.cetc.uavsystem.redis.cache;import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;import org.apache.ibatis.cache.Cache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;import redis.clients.jedis.exceptions.JedisConnectionException;/*** * @author Mickle_zhang* redis 做二级缓存*/
public class RedisCache implements Cache {private static final Logger logger = LoggerFactory.getLogger(RedisCache.class);private static JedisConnectionFactory jedisConnectionFactory;private final String id;private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();public RedisCache(final String id) {if (id == null) {throw new IllegalArgumentException("Cache instances require an ID");}this.id = id;}@Overridepublic void clear() {RedisConnection connection = null;try {connection = jedisConnectionFactory.getConnection();RedisSerializer<Object> serializer = new JdkSerializationRedisSerializer();
//            connection.flushDb();
//            connection.flushAll();Long length = connection.lLen(serializer.serialize(id));if (0 == length) {return;}List<byte[]> keys = connection.lRange(serializer.serialize(id),0,length-1);for (byte[] key :keys) {connection.expireAt(key,0);System.out.println("删除缓存:"+serializer.deserialize(key).toString());}connection.expireAt(serializer.serialize(id),0);keys.clear();} catch (Exception e) {e.printStackTrace();} finally {if (connection != null) {connection.close();}}}@Overridepublic String getId() {return this.id;}@Overridepublic Object getObject(Object key) {Object result = null;RedisConnection connection = null;try {connection = jedisConnectionFactory.getConnection();RedisSerializer<Object> serializer = new JdkSerializationRedisSerializer();result = serializer.deserialize(connection.get(serializer.serialize(key)));logger.info("redis取数据");} catch (JedisConnectionException e) {e.printStackTrace();} finally {if (connection != null) {connection.close();}}return result;}@Overridepublic ReadWriteLock getReadWriteLock() {return this.readWriteLock;}@Overridepublic int getSize() {int result = 0;RedisConnection connection = null;try {connection = jedisConnectionFactory.getConnection();result = Integer.valueOf(connection.dbSize().toString());} catch (JedisConnectionException e) {e.printStackTrace();} finally {if (connection != null) {connection.close();}}return result;}@Overridepublic void putObject(Object key, Object value) {RedisConnection connection = null;try{
// 现在将namespace做一张单独的表即com.cetc.uavsystem.dao.Idt_user_tableDao,clear方法就寻找该list connection = jedisConnectionFactory.getConnection();RedisSerializer<Object> serializer = new JdkSerializationRedisSerializer();connection.set(serializer.serialize(key),serializer.serialize(value));// 将key保存到redis.list中connection.lPush(serializer.serialize(id), serializer.serialize(key));logger.info("redis存数据");} catch (JedisConnectionException e) {e.printStackTrace();} finally {if (connection != null) {connection.close();}}}@Overridepublic Object removeObject(Object key) {RedisConnection connection = null;Object result = null;try {connection = jedisConnectionFactory.getConnection();RedisSerializer<Object> serializer = new JdkSerializationRedisSerializer();result = connection.expire(serializer.serialize(key), 0);} catch (JedisConnectionException e) {e.printStackTrace();} finally {if (connection != null) {connection.close();}}return result;}public static void setJedisConnectionFactory(JedisConnectionFactory jedisConnectionFactory) {RedisCache.jedisConnectionFactory = jedisConnectionFactory;}}

RedisCacheTransfer

/*** */
package com.cetc.uavsystem.redis.cache;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.stereotype.Component;/*** @author Mickle_zhang**/
@Component
public class RedisCacheTransfer {@Autowiredpublic void setJedisConnectionFactory(JedisConnectionFactory jedisConnectionFactory) {RedisCache.setJedisConnectionFactory(jedisConnectionFactory);}
}

Mapper文件

<?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.cetc.uavsystem.dao.Idt_user_tableDao"><!-- 开启本mapper的namespace下的二级缓存 -->
<cache  type="com.cetc.uavsystem.redis.cache.RedisCache"><property name="eviction" value="LRU" /><property name="flushInterval" value="6000000" /><property name="size" value="1024" /><property name="readOnly" value="false" /></cache><!-- useCache是否开启二级缓存,flushCache为是否刷新二级缓存 --><select id="get" resultMap="Idt_user_table" parameterType="Integer" useCache="true"  flushCache="true">select * from idt_user_table where user_id=#{nUser_id}</select><select id="getAll" resultMap="Idt_user_table" useCache="true"  flushCache="false">select * from idt_user_table</select>
</mapper >

如果还是不明白,可参照demo

地址:https://github.com/yxyyzyf/shaungseqiu

基于spring cloud,功能完善中

关于Spring Boot + Mybatis + Redis二级缓存整合详解相关推荐

  1. Java Web现代化开发:Spring Boot + Mybatis + Redis二级缓存

    背景 Spring-Boot因其提供了各种开箱即用的插件,使得它成为了当今最为主流的Java Web开发框架之一.Mybatis是一个十分轻量好用的ORM框架.Redis是当今十分主流的分布式key- ...

  2. 【MyBatis】MyBatis 二级缓存全详解

    1.概述 转载:MyBatis 二级缓存全详解 上一篇文章中我们介绍到了 MyBatis 一级缓存其实就是 SqlSession 级别的缓存,什么是 SqlSession 级别的缓存呢?一级缓存的本质 ...

  3. Spring Boot 使用 HikariCP 连接池配置详解

    Spring Boot 使用 HikariCP 连接池配置详解 HikariCP 是一个高性能的 JDBC 连接池组件. Spring Boot 2.x 将其作为默认的连接池组件,项目中添加 spri ...

  4. mysql二级缓存redis_SpringBoot+Mybatis+redis(二级缓存)搭建

    刚刚开始接触Spring Boot,因为极简单的配置开发,搭建一个通用的Spring Boot+Mybaitis+redis的开发框架. 一.用maven构建项目,pom.xml文件如下: org.s ...

  5. Spring Boot 集成 Redis 实现缓存机制

    本文章牵涉到的技术点比较多:spring Data JPA.Redis.Spring MVC,Spirng Cache,所以在看这篇文章的时候,需要对以上这些技术点有一定的了解或者也可以先看看这篇文章 ...

  6. mybatis一级缓存和二级缓存使用详解

    文章目录 一.概念说明 1.一级缓存 2.二级缓存 3.比较 二.mybatis缓存的生命周期 三.一级缓存的使用 四.二级缓存的使用 五.自定义二级缓存 六.mybatis缓存.spring缓存和r ...

  7. Spring Boot 2 + Redis 对象缓存

    依赖配置 <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http:/ ...

  8. Spring Boot集成Redis实现缓存

    前言 在此章,我们将 SpringBoot 集成 Redis缓存,Redis是一个开源的,基于内存的数据结构存储,可以用作数据库.缓存和消息代理,在本章仅讲解缓存集成.一键获取源码地址 准备工作 当前 ...

  9. mybatis 二级缓存失效_MyBatis 二级缓存全详解

    我们在上一篇文章 ( https://mp.weixin.qq.com/s/4Puee_pPCNArkgnFaYlIjg ) 介绍了 MyBatis 的一级缓存的作用,如何开启,一级缓存的本质是什么, ...

最新文章

  1. 人工智能应该如何监管——智库研究员乔舒亚·纽提出算法责任原则
  2. C++ 的复制构造函数
  3. 从音乐到全“声”态,腾讯音乐发展的“中国范本”
  4. ZEN CART 在LINUX系统下设置邮箱方法---用GMAIL设置,方法选择SMTPAUTH
  5. php用空格分隔的字符串对比,探讨各种PHP字符串函数的总结分析
  6. Oracle教程之SGA_MAX_SIZE参数
  7. shell的执行顺序问题
  8. 罗永浩将举办「老人与海」发布会;微软疑似遭遇大范围全球宕机;Python 3.9 首个测试版发布 | 极客头条...
  9. 2017linux版本号,Linux基本命令 2017-11-27
  10. Drupal 紧急修复已遭利用的严重 0day
  11. 关于IMX6Dl 芯片使用硬编解码的问题记录
  12. 飞思卡尔全国总决赛智能车决赛赛道分析
  13. python统计文章中高频词汇并生成词云
  14. 怎么查询Mysql数据库的版本号?(2种常用的方法)
  15. Http协议之Referer
  16. 计算机异常断电后无法启动,电脑突然断电后开不了机怎么办
  17. 《好玩游戏物品清单》实现
  18. 神经网络入门书籍推荐,神经网络基础书籍
  19. 智能控制matlab程序,智能算法的Matlab仿真程序及教程
  20. 刚高考完有些迷茫不知道做些什么?谈一谈我的看法

热门文章

  1. 易到用车上线“易到巴士” 推班车业务
  2. 设计师经常用双显卡交火来实现更高的性能
  3. 计算机基础知识大眼睛,大眼睛的说说 描写大眼睛的句子
  4. 恐惧和勇敢,其实并不是对立的
  5. 嵌入式软件设计(ucos iii使用)
  6. python程序设计题答案_Python程序设计课后习题答案
  7. 东北大学数据科学基础(MATLAB)-笔记
  8. 纺织浆料消泡剂的价值主要体现在消泡的功能上
  9. 利用Python统计excel表格
  10. (转)只有做到这三点,你的产品才可能成功