I have simple Redis
client based on Spring
below. As default it connects to local host, but I need to set different host and port.
I suppose I can do it in function below:
@Bean
RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,MessageListenerAdapter listenerAdapter) {
//LettuceConnectionFactory(connectionFactory);
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.addMessageListener(listenerAdapter, new PatternTopic("chat"));
return container;
}
I found that I class name of connectionFactory
is LettuceConnectionFactory
and it has private field client
that contains connection information.
What is correct way to change default connection parameters in RedisConnectionFactory
?
Whole code:
@SpringBootApplication
public class MessagingRedisApplication {
private static final Logger lg = LoggerFactory.getLogger(MessagingRedisApplication.class);
@Bean
RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,MessageListenerAdapter listenerAdapter) {
LettuceConnectionFactory(connectionFactory)
lg.info( connectionFactory.toString() );
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.addMessageListener(listenerAdapter, new PatternTopic("chat"));
return container;
}
@Bean
MessageListenerAdapter listenerAdapter(Receiver receiver) {
return new MessageListenerAdapter(receiver, "receiveMessage");
}
@Bean
Receiver receiver() {
return new Receiver();
}
@Bean
StringRedisTemplate template(RedisConnectionFactory connectionFactory) {
return new StringRedisTemplate(connectionFactory);
}
public static void main(String[] args) throws InterruptedException {
ApplicationContext ctx = SpringApplication.run(MessagingRedisApplication.class, args);
StringRedisTemplate template = ctx.getBean(StringRedisTemplate.class);
Receiver receiver = ctx.getBean(Receiver.class);
while (receiver.getCount() == 0) {
lg.info("Sending message...");
template.convertAndSend("chat", "Hello from Redis!");
Thread.sleep(500L);
}
System.exit(0);
}
}
2
Answers
You should use default spring provided properties to configure your redis connections. For host and port, the followging properties should be enough.
Then the
connectionfactory
bean will created with the given host and port. The whole set of properties are available here. Search withspring.redis.
If you want to configure host name programatically instead of using
spring.redis
properties you can create your ownRedisConnectionFactory
and passRedisConfiguration
to it’s constructor :In this case I assume you are using single node instance so
RedisStandaloneConfiguration
is used.