레디스에서 여러 database를 사용하는 경우
설정 파일
@Configuration
public class RedisConfig {
@Value("${spring.data.redis.host}")
private String host;
@Value("${spring.data.redis.port}")
private int port;
public RedisConnectionFactory redisConnectionFactory(int dbIndex) {
final RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
redisStandaloneConfiguration.setHostName(host);
redisStandaloneConfiguration.setPort(port);
redisStandaloneConfiguration.setDatabase(dbIndex);
return new LettuceConnectionFactory(redisStandaloneConfiguration);
}
}
- 해당 dbIndex를 파라미터로 받아서 실제 구현체에서 이를 넣어서 사용할 수 있게 한다.
@Primary
@Configuration
public class MatchScheduleRedisConfig extends RedisConfig {
@Bean
@Primary
public RedisConnectionFactory matchScheduleRedisConnectionFactory() {
return redisConnectionFactory(0);
}
}
@Configuration
public class NewRedisConfig extends RedisConfig {
@Bean
public RedisConnectionFactory newsRedisConnectionFactory() {
return redisConnectionFactory(2);
}
@Bean
@Qualifier("newsRedisTemplate")
public RedisTemplate<?, ?> newsRedisTemplate(ObjectMapper objectMapper) {
RedisTemplate<?, ?> template = new RedisTemplate<>();
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer(objectMapper));
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer(objectMapper));
template.setConnectionFactory(newsRedisConnectionFactory());
return template;
}
}
- @Qualifier()를 사용해서 빈 이름을 지정해준다.
사용법
@RestController
@Slf4j
public class LeagueRestController {
private final RedisTemplate<String, String> matchRankingRedisTemplate;
private final ObjectMapper objectMapper;
public LeagueRestController(@Qualifier("matchRankingRedisTemplate") RedisTemplate<String, String> matchRankingRedisTemplate,
ObjectMapper objectMapper) {
this.matchRankingRedisTemplate = matchRankingRedisTemplate;
this.objectMapper = objectMapper;
}
}