简体   繁体   中英

Redis Pub/Sub with Java spring

I Create Redis Pub/Sub with single Topic and single listener with Java like thank:

That is my Beans within MvcConfigurer:

@Bean
    MessageListenerAdapter messageListener() {
        return new MessageListenerAdapter(redisMsgHandler);
    }

    @Bean
    public RedisMessageListenerContainer redisMessageListenerContainer() {
        RedisMessageListenerContainer mlc = new RedisMessageListenerContainer();
        mlc.setConnectionFactory(lettuceConnectionFactory());
        mlc.addMessageListener(messageListener(), topic());
        return mlc;
    }

    @Bean
    ChannelTopic topic() {
        return new ChannelTopic("pubsub:queue");
    }

That's where i'm receiving Message, please not this RedisMsghandler class is used to MvcConfigurer

public class RedisMsgHandler implements MessageListener {

    @Override
    public void onMessage(Message message, byte[] bytes) {
   //impl goes here
    }
} 

my main goal is to create more than one topic and more than one listener like RedisMsgHandler, please let me know how to do it.

I don't feel comfortable to create lots of classes which are implemented on MessageListener and lots of beans for each Topic

manged to fix it like that:

@Bean
public RedisMessageListenerContainer redisMessageListenerContainer() {
    RedisMessageListenerContainer mlc = new RedisMessageListenerContainer();

    mlc.setConnectionFactory(lettuceConnectionFactory());
    mlc.addMessageListener(new MessageListenerAdapter(redisMsgHandler), 
                           new ChannelTopic("pubsub:queue");


    mlc.addMessageListener(new MessageListenerAdapter(redisMsgHandlerAnother), 
                           new ChannelTopic("pubsub:Otherqueue");

    return mlc;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM