거의 참고 글 복붙이지만 자료 조사 과정에서 깔끔하고 제대로 설명된 내용이 이 것 말고는 없었기에 기록용으로 작성한다.
Spring Boot에서 Redis를 연결할 때 보통은 Lettuce를 사용한다.
Spring Boot에서 Lettuce를 사용하는 방법은 자료가 많이 있다.
하지만 그냥 사용하면 로컬에만 연결될 뿐이다.
Redis를 Cache로 사용할 경우에는 로컬로 연결하겠지만 내가 원하는 사용 방법은 Message Broker로 사용하는 것이다.
실제 운영환경에서는 Redis를 Message Broker로 사용할 경우 다른 서버와의 통신 등의 용도로 사용하기 때문에 로컬에 있지 않고 원격 서버에 Redis가 구동된다.
Redis Pub / Sub을 위해서 RedisConfig
를 구성할 때 내용은 대략 이렇다. (자세한 설명은 생략)
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
@Slf4j
@Configuration
public class RedisConfig {
@Bean
public RedisConnectionFactory getRedisConnectionFactory() {
return new LettuceConnectionFactory();
}
@Bean
RedisMessageListenerContainer getRedisMessageListenerContainer() {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(getRedisConnectionFactory());
container.addMessageListener(getMessageListenerAdapter(), topic());
return container;
}
@Bean
MessageListenerAdapter getMessageListenerAdapter() {
return new MessageListenerAdapter(new RedisMessageStringSubscriber());
}
@Bean
ChannelTopic topic() {
return new ChannelTopic("test001");
}
}
여기서 눈여겨 봐야할 부분은 getRedisConnectionFactory
함수이다.
이 함수에서 그냥 new LettuceConnectionFactory()
를 return하면 로컬에 연결된다. 보통의 글들은 이 내용까지만 있다.
원격 서버에 연결 또는 아무튼 Redis 연결 정보를 직접 정하고 싶을 때에는 RedisStandaloneConfiguration
을 만들어서 LettuceConnectionFactory
생성자에 넣어줘야한다.
우선 @Value
Annotation을 사용해서 설정 파일의 내용을 불러와준다.
import org.springframework.beans.factory.annotation.Value;
...
...
public class RedisConfigA {
@Value("${spring.data.redis.host}")
private String host;
@Value("${spring.data.redis.port}")
private int port;
@Value("${spring.data.redis.password:#{null}}")
private String password;
...
}
그 다음에는 RedisStandaloneConfiguration
을 생성해서 LettuceConnectionFactory
생성자에 넣어준다.
public RedisConnectionFactory getRedisConnectionFactory() {
RedisStandaloneConfiguration config = new RedisStandaloneConfiguration(host, port);
if (password != null) {
config.setPassword(password);
}
return new LettuceConnectionFactory(config);
}