单数据源版
1.引入依赖
<!--Web组件-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--Redis-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!--Redis连接池-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.9.0</version>
</dependency>
2.yml文件增加配置
#Spring配 置
spring:
#Redis配置
redis:
host: 8.142.132.135
port: 6379
password:
database: 0
jedis:
pool:
max-active: 150
max-wait: 100
max-idle: 100
min-idle: 50
timeout: 5000ms
- max-active:最大激活连接数
- max-wait:连接最大等待时间
- max-idle:最大空闲连接数量
- min-idle:最小空闲连接数
3.增加配置类
```java import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
/**
- @author 冯铁城 [17615007230@163.com]
- @date 2022-05-06 16:18:18
@describe: Redis配置类 */ @Configuration public class RedisConfig {
@Bean @ConditionalOnMissingBean(name = “redisTemplate”) public RedisTemplate
redisTemplate(RedisConnectionFactory redisConnectionFactory) { //1.创建序列化类
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
jackson2JsonRedisSerializer.setObjectMapper(om);
//2.设置序列化规则
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
template.setKeySerializer(jackson2JsonRedisSerializer);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.setHashKeySerializer(jackson2JsonRedisSerializer);
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
//3.返回模板
return template;
4.编写单元测试验证
```java import org.junit.Assert; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.redis.core.RedisTemplate;
@SpringBootTest class RedistryApplicationTests {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Test
void testRedis() {
redisTemplate.opsForValue().set("key", "value");
Object key = redisTemplate.opsForValue().get("key");
Assert.assertNotNull(key);
Assert.assertEquals("value", key);
}
}
<a name="EH8UY"></a>
## 多数据源版
<a name="TTfJR"></a>
### 1.引入依赖
```xml
<!--Web组件-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--Redis-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!--Redis连接池-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.9.0</version>
</dependency>
2.yml文件增加配置
#配置Redis数据源(支持多数据源)
redis:
#默认Redis连接
default-redis:
host: 8.142.132.135
port: 6379
password:
database: 0
timeout: 6000
max-active: 150
max-wait: 100
max-idle: 100
min-idle: 50
#其他Redis连接
other-redis:
host: 8.142.132.135
port: 6379
password:
database: 1
timeout: 6000
max-active: 150
max-wait: 100
max-idle: 100
min-idle: 50
3.添加Redis配置接口
/**
* @author 冯铁城 [fengtiecheng@cyou-inc.com]
* @date 2022-01-07 16:53:28
* @describe:
*/
public interface RedisConfig {
/**
* 获取主机信息
*
* @return
*/
String getHost();
/**
* 获取端口
*
* @return
*/
int getPort();
/**
* 获取密码
*
* @return
*/
String getPassword();
/**
* 获取数据库信息
*
* @return
*/
int getDatabase();
/**
* 获取连接超时时间
*
* @return
*/
long getTimeOut();
/**
* 获取最大激活连接数
*
* @return
*/
int getMaxActive();
/**
* 获取最大等待时间
*
* @return
*/
int getMaxWait();
/**
* 获取最大等待连接中的数量
*
* @return
*/
int getMaxIdle();
/**
* 获取最小等待连接中的数量
*
* @return
*/
int getMinIdle();
}
4.添加Redis配置实现类
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @author 冯铁城 [fengtiecheng@cyou-inc.com]
* @date 2022-01-07 16:59:24
* @describe: 平台默认Redis配置
*/
@Component
@ConfigurationProperties(prefix = "redis.default-redis")
@Setter
public class DefaultRedisConfig implements RedisConfig {
/**
* 主机信息
*/
private String host;
/**
* 端口
*/
private int port;
/**
* 密码
*/
private String password;
/**
* 数据库
*/
private int database;
/**
* 连接超时时间
*/
private long timeOut;
/**
* 最大激活连接数
*/
private int maxActive;
/**
* 最大等待时间
*/
private int maxWait;
/**
* 最大等待连接中的数量
*/
private int maxIdle;
/**
* 最小等待连接中的数量
*/
private int minIdle;
@Override
public String getHost() {
return this.host;
}
@Override
public int getPort() {
return this.port;
}
@Override
public String getPassword() {
return this.password;
}
@Override
public int getDatabase() {
return this.database;
}
@Override
public long getTimeOut() {
return this.timeOut;
}
@Override
public int getMaxActive() {
return this.maxActive;
}
@Override
public int getMaxWait() {
return this.maxWait;
}
@Override
public int getMaxIdle() {
return this.maxIdle;
}
@Override
public int getMinIdle() {
return this.minIdle;
}
}
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @author 冯铁城 [fengtiecheng@cyou-inc.com]
* @date 2022-01-07 16:59:24
* @describe: 其他Redis配置
*/
@Component
@ConfigurationProperties(prefix = "redis.other-redis")
@Setter
public class OtherRedisConfig implements RedisConfig {
/**
* 主机信息
*/
private String host;
/**
* 端口
*/
private int port;
/**
* 密码
*/
private String password;
/**
* 数据库
*/
private int database;
/**
* 连接超时时间
*/
private long timeOut;
/**
* 最大激活连接数
*/
private int maxActive;
/**
* 最大等待时间
*/
private int maxWait;
/**
* 最大等待连接中的数量
*/
private int maxIdle;
/**
* 最小等待连接中的数量
*/
private int minIdle;
@Override
public String getHost() {
return this.host;
}
@Override
public int getPort() {
return this.port;
}
@Override
public String getPassword() {
return this.password;
}
@Override
public int getDatabase() {
return this.database;
}
@Override
public long getTimeOut() {
return this.timeOut;
}
@Override
public int getMaxActive() {
return this.maxActive;
}
@Override
public int getMaxWait() {
return this.maxWait;
}
@Override
public int getMaxIdle() {
return this.maxIdle;
}
@Override
public int getMinIdle() {
return this.minIdle;
}
}
5.添加Redis连接生成工厂
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.time.Duration;
/**
* @author 冯铁城 [fengtiecheng@cyou-inc.com]
* @date 2022-01-07 17:33:43
* @describe: 多数据源Redis工厂
*/
@Configuration
public class RedisTemplateConstructor {
@Autowired
@Qualifier("defaultRedisConfig")
private RedisConfig defaultRedisConfig;
@Autowired
@Qualifier("otherRedisConfig")
private RedisConfig otherRedisConfig;
/**
* 创建默认RedisTemplate
*
* @return 默认RedisTemplate
*/
@Bean(name = "defaultRedis")
@Primary
public RedisTemplate<String, Object> defaultRedisTemplate() {
//1.创建连接工厂
LettuceConnectionFactory connectionFactory = this.lettuceConnectionFactory(defaultRedisConfig);
//2.创建RedisTemplate返回
return this.createRedisTemplate(connectionFactory);
}
/**
* 创建其他RedisTemplate
*
* @return 默认RedisTemplate
*/
@Bean(name = "otherRedis")
public RedisTemplate<String, Object> otherRedisTemplate() {
//1.创建连接工厂
LettuceConnectionFactory connectionFactory = this.lettuceConnectionFactory(otherRedisConfig);
//2.创建RedisTemplate返回
return this.createRedisTemplate(connectionFactory);
}
/**
* 创建lettuce连接池工厂
*
* @param redisConfig Redis配置
* @return lettuce 连接池工厂
*/
private LettuceConnectionFactory lettuceConnectionFactory(RedisConfig redisConfig) {
//1.线程池设置
GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
poolConfig.setMaxTotal(redisConfig.getMaxActive());
poolConfig.setMaxWaitMillis(redisConfig.getMaxWait());
poolConfig.setMaxIdle(redisConfig.getMaxIdle());
poolConfig.setMinIdle(redisConfig.getMinIdle());
//2.线程池客户端设置
LettuceClientConfiguration clientConfiguration = LettucePoolingClientConfiguration
.builder()
.commandTimeout(Duration.ofSeconds(redisConfig.getTimeOut()))
.poolConfig(poolConfig)
.build();
//3.Redis基础设置
RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration();
configuration.setHostName(redisConfig.getHost());
configuration.setDatabase(redisConfig.getDatabase());
configuration.setPassword(redisConfig.getPassword());
configuration.setPort(redisConfig.getPort());
//4.返回连接池工厂
LettuceConnectionFactory lettuceConnectionFactory = new LettuceConnectionFactory(configuration, clientConfiguration);
lettuceConnectionFactory.setShareNativeConnection(true);
lettuceConnectionFactory.afterPropertiesSet();
return lettuceConnectionFactory;
}
/**
* 创建RedisTemplate并设置序列化规则
*
* @param redisConnectionFactory redis连接池
*/
private RedisTemplate<String, Object> createRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
//1.创建Redis连接模板
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
//2.设置连接工厂
redisTemplate.setConnectionFactory(redisConnectionFactory);
//3.设置keyValue序列化规则
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new StringRedisSerializer());
//4.创建Hash序列化规则
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
jackson2JsonRedisSerializer.setObjectMapper(om);
//5.设置HashKeyValue序列化规则
redisTemplate.setHashKeySerializer(jackson2JsonRedisSerializer);
redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
//6.返回
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
}
6.编写单元测试验证
import org.junit.Assert;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
@SpringBootTest
class RedistryApplicationTests {
@Autowired
@Qualifier("defaultRedis")
private RedisTemplate<String, Object> defaultRedis;
@Autowired
@Qualifier("otherRedis")
private RedisTemplate<String, Object> otherRedis;
@Test
void testRedis() {
defaultRedis.opsForValue().set("defaultKey", "defaultValue");
Object defaultKey = defaultRedis.opsForValue().get("defaultKey");
Assert.assertNotNull(defaultKey);
Assert.assertEquals("defaultValue", defaultKey);
otherRedis.opsForValue().set("otherKey", "otherValue");
Object otherKey = otherRedis.opsForValue().get("otherKey");
Assert.assertNotNull(otherKey);
Assert.assertEquals("otherValue", otherKey);
}
}