项目需要把自建redis迁移到云服务,因为无法做到业务无感迁移,所以业务迁移时,部分数据需要双读,因此需要支持多Redis数据源
支持多Redis数据源
- 配置信息
application.yml
spring:
redis:
host: localhost
port: 6379
second-redis:
host: localhost
port: 16379
- 配置主数据源
@Primary
@Bean
public LettuceConnectionFactory primaryLettuceConnectionFactory(@Value("${spring.redis.host}") String host,
@Value("${spring.redis.port}") int port,
@Value("${spring.redis.password:}") String password) {
RedisStandaloneConfiguration config = new RedisStandaloneConfiguration(host, port);
if (StringUtils.hasLength(password)) {
config.setPassword(password);
}
return new LettuceConnectionFactory(config);
}
@Bean
public StringRedisTemplate stringRedisTemplate(LettuceConnectionFactory primaryLettuceConnectionFactory) {
return new StringRedisTemplate(primaryLettuceConnectionFactory);
}
- 配置备数据源
@Bean
public StringRedisTemplate secondStringRedisTemplate(@Qualifier("secondLettuceConnectionFactory") LettuceConnectionFactory secondLettuceConnectionFactory) {
return new StringRedisTemplate(secondLettuceConnectionFactory);
}
@Bean
public LettuceConnectionFactory secondLettuceConnectionFactory(@Value("${spring.second-redis.host}") String host,
@Value("${spring.second-redis.port}") int port,
@Value("${spring.second-redis.password:}") String password) {
RedisStandaloneConfiguration config = new RedisStandaloneConfiguration(host, port);
if (StringUtils.hasLength(password)) {
config.setPassword(password);
}
return new LettuceConnectionFactory(config);
}
- 测试效果
@Slf4j
@SpringBootApplication
public class MredisApplication implements ApplicationRunner {
public static void main(String[] args) {
SpringApplication.run(MredisApplication.class, args);
}
@Resource
private StringRedisTemplate stringRedisTemplate;
@Resource
private StringRedisTemplate secondStringRedisTemplate;
@Override
public void run(ApplicationArguments args) throws Exception {
String name = stringRedisTemplate.opsForValue().get("name");
log.info("name: {}", name);
name = secondStringRedisTemplate.opsForValue().get("name");
log.info("second name: {}", name);
}
}
输出日志信息:
代码语言:javascript复制2021-08-19 14:52:12.770 INFO 91290 --- [ main] com.tenmao.mredis.MredisApplication : name: null
2021-08-19 14:52:12.779 INFO 91290 --- [ main] com.tenmao.mredis.MredisApplication : second name: tim2
可以看到已经读取到了不同的redis数据