二级缓存是多个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=true
spring.datasource.username=root
spring.datasource.password=123456
spring.redis.host = 10.10.10.11
spring.redis.password=123456
spring.redis.port=6379
spring.redis.database=0
spring.redis.timeout=0
spring.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;
@Bean
public 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;
}
@Override
public 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();
}
}
}
@Override
public String getId() {
return this.id;
}
@Override
public 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;
}
@Override
public ReadWriteLock getReadWriteLock() {
return this.readWriteLock;
}
@Override
public 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;
}
@Override
public 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();
}
}
}
@Override
public 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 {
@Autowired
public 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,功能完善中