Redis实现消息的发布/订阅

时间:2023-12-19 14:07:32

利用spring-boot结合redis进行消息的发布与订阅:

  发布:

  class Publish {

    private static String topicName = “Topic:chat”;

    @Bean

    RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory, MessageListenerAdapter messageListenerAdapter ) {

      RedisMessageListenerContainer  redisMessageListenerContainer  = new RedisMessageListenerContainer ();

      redisMessageListenerContainer.setConnectionFactory(connectionFactory);

      redisMessageListenerContainer.addMessageListenerAdapter(messageListenerAdapter ,new PatternTopic(topicName ));

      return  redisMessageListenerContainer;

    }

    @Bean

    MessageListenerAdapter messageListenerAdapter(Receiver recevier){

      return new MessageListenerAdapter (recevier,"receiveMessage");

    }

    @Bean

    Receiver recevier(@Value("Receiver-1") String name) {

      return new Receiver(name);

    }

    public static main(String[] args) {

      ApplicationContext ctx = SpringApplication.run(Publish .class,args);

      StringRedisTemple stringRedisTemple = ctx.getBean(StringRedisTemple.class);

      stringRedisTemple.convertAndSend(topicName ,"HAHAHAHAHAHA");

    }

  }

订阅:

  class Receiver {

    private String name;

    @Autowired

    public Receiver(String name) {

      this.name = name;

    }

    public void receiveMessage(String message) {

      System.ount.println(name + message);

    }

  }