1. 配置环境
Redis 4 安装教程自行google
Spring 5.0.9
Mybatis 3.4.6
2. 依赖
注意:
- 默认你配置好了SSM的依赖环境,我只说在SSM配好过后怎么把redis加进去
- 我用的依赖是如下的版本,基本都没有最新jar包的教程,网上的老教程千奇百怪,真的是痛心。
- 如果你不是用的spring-data-redis的2.X的版本你可以不用看了,看了也没用。
</properties>
<jedis.version>2.9.0</jedis.version>
<redis.version>2.1.0.RELEASE</redis.version>
</properties>
<!--Redis支持-->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>${jedis.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>${redis.version}</version>
</dependency>
3.配置
首先是redisConfig.java,哇,这个是真的一个巨坑,改动贼多。老教程根本无法使用。作为一个新手瑟瑟发抖。不多说了,先贴代码,再解释
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.*;
import org.springframework.data.redis.connection.jedis.JedisClientConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
@Configuration
@PropertySource("classpath:config/redis.properties")
@EnableCaching
public class RedisConfig {
@Value("${redis.maxTotal}")
private int maxTotal;
@Value("${redis.maxIdle}")
private int maxIdle;
@Value("${redis.maxWaitMillis}")
private long maxWaitMillis;
@Value("${redis.testOnBorrow}")
private boolean testOnBorrow;
@Value("${redis.host}")
private String host;
@Value("${redis.port}")
private int port;
@Value("${redis.timeout}")
private int timeout;
@Value("${redis.password}")
private String password;
@Value("${redis.database}")
private int database;
@Value("${redis.minEvictableIdleTimeMillis}")
private int minEvictableIdleTimeMillis;
@Value("${redis.softMinEvictableIdleTimeMillis}")
private int softMinEvictableIdleTimeMillis;
@Value("${redis.timeBetweenEvictionRunsMillis}")
private int timeBetweenEvictionRunsMillis;
@Value("${redis.numTestsPerEvictionRun}")
private int numTestsPerEvictionRun;
@Value("${redis.blockWhenExhausted}")
private boolean blockWhenExhausted;
@Value("${redis.testWhileIdle}")
private boolean testWhileIdle;
@Bean
public JedisPoolConfig poolConfig() {
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxTotal(maxTotal);
poolConfig.setMaxIdle(maxIdle);
poolConfig.setMaxWaitMillis(maxWaitMillis);
poolConfig.setTestOnBorrow(testOnBorrow);
poolConfig.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
poolConfig.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
poolConfig.setSoftMinEvictableIdleTimeMillis(softMinEvictableIdleTimeMillis);
poolConfig.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
poolConfig.setNumTestsPerEvictionRun(numTestsPerEvictionRun);
poolConfig.setBlockWhenExhausted(blockWhenExhausted);
poolConfig.setTestWhileIdle(testWhileIdle);
return poolConfig;
}
//这个是个巨坑
@Bean
public JedisConnectionFactory jedisConnectionFactory(JedisPoolConfig jedisPoolConfig) {
RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration();
configuration.setHostName(host);
configuration.setPort(port);
//如果没有密码可以不设置,要注意密码要用RedisPassword类
configuration.setPassword(RedisPassword.of(password));
configuration.setDatabase(database);
//获得默认的连接池构造
//JedisConnectionFactory对于Standalone模式的没有(RedisStandaloneConfiguration,JedisPoolConfig)的构造函数,
//所以用JedisClientConfiguration接口的builder方法实例化一个构造器,还得类型转换
JedisClientConfiguration.JedisPoolingClientConfigurationBuilder jpcf =
(JedisClientConfiguration.JedisPoolingClientConfigurationBuilder) JedisClientConfiguration.builder();
//修改我们的连接池配置
jpcf.poolConfig(jedisPoolConfig);
//通过构造器来构造jedis客户端配置
JedisClientConfiguration jedisClientConfiguration = jpcf.build();
return new JedisConnectionFactory(configuration, jedisClientConfiguration);
}
@Bean
public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
//序列化
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
redisTemplate.setHashValueSerializer(new JdkSerializationRedisSerializer());
return redisTemplate;
}
@Bean
public RedisCacheManager cacheManager(JedisConnectionFactory jedisConnectionFactory) {
//这里是个坑,老方法已经过时了,用下面方法替代
return RedisCacheManager.create(jedisConnectionFactory);
}
}
讲讲那个巨坑JedisConnectionFactory
- 以前的版本是没有利用RedisStandaloneConfiguration来配置的,我看了几个教程的结果,应该是2.X的版本加进来的。贼难受。
- 有的教程的JedisConnectionFactory是没有把jedisPoolConfig加进去的。结合几个老教程和Spring boot我个人觉得是应该吧jedisPoolConfig的配置加载进去不然应该不能工作。所以我就找了很多教程,发现其中有个教程就用了现在代码中的方法加了进去
- password需要用到RedisPassword.of(password)做下转换
redis.properties配置文件如下
##########################
## redis缓存配置
##########################
# redis主机IP
redis.host=127.0.0.1
# redis端口
redis.port=6379
# 链接超时
redis.timeout=2000
# 密码 如果你没有设置密码 这个配置可以不设置
redis.password=XXXXX
# 指定redis数据库
redis.database=0
##########################
## redis连接池配置
##########################
# 最大连接数
redis.maxTotal=30
# 最大空闲连接数
redis.maxIdle=10
# 获取链接最大等待毫秒
redis.maxWaitMillis=1000
# 获取链接时检查有效性
redis.testOnBorrow=true
# 在空闲时监测有效性
redis.testWhileIdle=true
# 链接耗尽时是否阻塞
redis.blockWhenExhausted=true
# 每次释放链接的最大数目
redis.numTestsPerEvictionRun=1024
# 释放链接的扫描间隔(毫秒)
redis.timeBetweenEvictionRunsMillis=30000
# 最小空闲时间
redis.minEvictableIdleTimeMillis=1800000
# 链接空闲多久后释放
redis.softMinEvictableIdleTimeMillis=10000
在RootConfig.java(根据你的项目来)中加入下列代码,导入RedisConfig.java(我数据库的使用的Druid如果没有分开 Druid是可以不要的)
@Import({DruidDataSourceConfig.class, RedisConfig.class})
随后 定义一个RedisCache类实现Cache接口
import org.apache.ibatis.cache.Cache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.jedis.JedisConnection;
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;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
public final class RedisCache implements Cache {
private static JedisConnectionFactory redisConnectionFactory;
private final String id;
public static void setJedisConnectionFactory(JedisConnectionFactory jedisConnectionFactory) {
RedisCache.redisConnectionFactory = jedisConnectionFactory;
}
/**
* The {@code ReadWriteLock}.
*/
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 = redisConnectionFactory.getConnection();
connection.flushDb();
connection.flushAll();
} catch (JedisConnectionException 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 = redisConnectionFactory.getConnection();
RedisSerializer<Object> serializer = new JdkSerializationRedisSerializer();
result = serializer.deserialize(connection.get(serializer.serialize(key)));
} 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 = redisConnectionFactory.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 {
connection = redisConnectionFactory.getConnection();
RedisSerializer<Object> serializer = new JdkSerializationRedisSerializer();
connection.set(serializer.serialize(key), serializer.serialize(value));
} 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 = redisConnectionFactory.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;
}
}
用另外一个类 注入jedisConnectionFactory
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.stereotype.Component;
@Component
public class RedisCacheTransfer {
@Autowired
public void setJedisConnectionFactory(JedisConnectionFactory jedisConnectionFactory) {
RedisCache.setJedisConnectionFactory(jedisConnectionFactory);
}
}
然后你需要在mybatis中开启cache
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 配置全局属性 -->
<settings>
<!--<!– 使用jdbc的getGeneratedKeys获取数据库自增主键值 –>-->
<!--<setting name="useGeneratedKeys" value="true" />-->
<!--允许cache-->
<setting name="cacheEnabled" value="true"/>
<!-- 使用列标签替换列名 默认:true -->
<setting name="useColumnLabel" value="true"/>
<!-- 开启驼峰命名转换:Table{create_time} -> Entity{createTime} -->
<setting name="mapUnderscoreToCamelCase" value="true"/>
<!-- 打印查询语句 -->
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
</configuration>
这个是我的配置文件,可以不同,根据你的需要来,你只需添加 允许cache的那一条就可以了。
另外如果你没有配置文件 可在配置数据库中加上
public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) throws IOException {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
sqlSessionFactoryBean.setDataSource(dataSource);
sqlSessionFactoryBean.setConfigLocation(resolver.getResource(CONFIG_LOCATION));
sqlSessionFactoryBean.setMapperLocations(resolver.getResources(MAPPER_LOCATION));
sqlSessionFactoryBean.setTypeAliasesPackage("io.ilss.entity");
return sqlSessionFactoryBean;
}
当中的resolver是加载配置文件和Mapper的xml文件用的。其中的两个常量(我定义在Constants中)是下面的
/**
* 数据库相关
*/
public static String CONFIG_LOCATION = "classpath:config/mybatis_config.xml";
public static String MAPPER_LOCATION = "classpath:mappers/*.xml";
最后你只需要在你想用cache的表的Mapper的xml文件的头上加上如下配置就OK了
<mapper namespace="com.example.dao.UserDao">
<!--缓存设置-->
<cache type="io.ilss.commons.RedisCache"/>
.....其他省略,自行配置
如果是用纯dao层注解的,加上相关的cache注解就好了。
接下来,你就可以去测试操作相对应表数据了。
你会看到如下类似日志
Cache Hit Ratio [XXXXXXX.XXXXDao]: 0.3333333333333333