How do I configure additional MessageListener to the RedisMessageListenerContainer provided by Spring Session?

时间:2016-07-11 19:33:31

标签: spring-boot redis publish-subscribe spring-session

I had a working Redis pub sub configuration as explained on the spring boot redis pub sub guide.

Here is the bean configuration for the RedisMessageListenerContainer

@Bean
RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
        MessageListenerAdapter listenerAdapter) {

    RedisMessageListenerContainer container = new RedisMessageListenerContainer();
    container.setConnectionFactory(connectionFactory);
    container.addMessageListener(listenerAdapter, new ChannelTopic("broadcast"));
    return container;
}

Now I wanted to utilize spring session backed by redis. So, I added a configuration class as this.

@EnableRedisHttpSession
public class HttpSessionConfig {

}

Now, because RedisHttpSessionConfig already defines a RedisMessageListenerContainer , I am getting this exception on start.

Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [org.springframework.data.redis.listener.RedisMessageListenerContainer] is defined: expected single matching bean but found 2: container,redisMessageListenerContainer

To get around that, I comment out the RedisMessageListenerContainer defined in my ApplicationConfig so that there is only one container bean but the problem then is

How do I configure my listener to add to the existing container provided by redisMessageListenerContainer?

Ok I was able to get around the problem by removing the RedisMessageListenerContainer bean, and injecting it as a method parameter in my MessageListenerAdaper bean configuration like so.

@Bean
MessageListenerAdapter listenerAdapter(RedisMessageListenerContainer container, PushNotificationsService receiver) {

    MessageListenerAdapter listenerAdapter = new MessageListenerAdapter(receiver, "receiveMessage");
    listenerAdapter.setSerializer(new Jackson2JsonRedisSerializer<NotificationMessage>(NotificationMessage.class));
    container.addMessageListener(listenerAdapter, new ChannelTopic("broadcast"));
    return listenerAdapter;
}

But this does not seem a clean solution, as I am decorating the RedisMessageListenerContainer bean from inside the MessageListenerAdaper bean. Any better ideas?

1 个答案:

答案 0 :(得分:-1)

您可以通过命名RedisMessageListenerContainer bean RedisHttpSessionConfiguration来覆盖Spring Session RedisMessageListenerContainer提供的redisMessageListenerContainer bean。

当然,在这种情况下,您还需要使用bean手动配置所需的message listeners,并在必要时还应用RedisHttpSessionConfiguration#redisMessageListenerContainer的其他部分。