一、理论基础
二、实战代码
2.1 配置项
redis:
host: 127.0.0.1
port: 6379
password: 123456
pool:
max-total: 10
# 连接池最大阻塞等待时间(使用负值表示没有限制)
max-wait: 3000
# 连接池中的最大空闲连接
max-idle: 5
# 连接池中的最小空闲连接
min-idle: 2
# 超时时间(毫秒)
timeout: 10000
2.2 配置文件
/**
* Redis配置
* @author smile
*/
@Configuration
public class RedisConfig {
@Value("${redis.host}")
private String host;
@Value("${redis.port}")
private int port;
@Value("${redis.password}")
private String password;
@Value("${redis.pool.max-total}")
private int maxTotal;
@Value("${redis.pool.max-wait}")
private int maxWait;
@Value("${redis.pool.max-idle}")
private int maxIdle;
@Value("${redis.pool.min-idle}")
private int minIdle;
@Bean(name = "db0RedisTemplate")
public RedisTemplate<String, Object> db0RedisTemplate() {
return getRedisTemplate(db0Factory());
}
@Bean(name = "db1RedisTemplate")
public RedisTemplate<String, Object> db1RedisTemplate() {
return getRedisTemplate(db1Factory());
}
@Bean
@Primary
public LettuceConnectionFactory db0Factory(){
return new LettuceConnectionFactory(getRedisConfig(0), getClientConfig());
}
@Bean
public LettuceConnectionFactory db1Factory(){
return new LettuceConnectionFactory(getRedisConfig(1), getClientConfig());
}
private RedisStandaloneConfiguration getRedisConfig(int dbNo) {
RedisStandaloneConfiguration config = new RedisStandaloneConfiguration();
config.setHostName(host);
config.setPort(port);
config.setPassword(password);
config.setDatabase(dbNo);
return config;
}
private LettuceClientConfiguration getClientConfig() {
GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
poolConfig.setMaxTotal(maxTotal);
poolConfig.setMaxIdle(maxIdle);
poolConfig.setMinIdle(minIdle);
poolConfig.setMaxWaitMillis(maxWait);
return LettucePoolingClientConfiguration.builder().poolConfig(poolConfig).build();
}
public RedisTemplate<String, Object> getRedisTemplate(LettuceConnectionFactory factory) {
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(String.class);
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.setConnectionFactory(factory);
return redisTemplate;
}
public StringRedisTemplate getStringRedisTemplate(LettuceConnectionFactory factory) {
StringRedisTemplate redisTemplate = new StringRedisTemplate();
redisTemplate.setConnectionFactory(factory);
return redisTemplate;
}
}
2.3 应用示例
/**
* @author smile
*/
@RestController
public class MainController {
@Autowired
private RedisTemplate<String, Object> db0RedisTemplate;
@Autowired
private RedisTemplate<String, Object> db1RedisTemplate;
@GetMapping("test")
public String testMultiDbOperation() {
db0RedisTemplate.opsForValue().set("db0_test", "test db0");
db1RedisTemplate.opsForValue().set("db1_test", "test db1");
return "success";
}
}
2.4 源码地址
https://github.com/lysmile/spring-boot-demo/tree/master/spring-boot-redis-multi-db-demo