【案例】SpringBoot使用Redis发布订阅

【案例】SpringBoot使用Redis发布订阅

第一种方式

  1. 步骤

    1. 配置监听消息类
    2. 添加监听容器
    3. 订阅频道
    4. 向频道发布消息
  2. 消息监听

    1. @Component
      public class RedisListener implements MessageListener {
      
          @Resource
          private RedisTemplate<String,Object> redisTemplate;
          @Override
          public void onMessage(Message message, byte[] pattern) {
      
              // 获取消息
              byte[] messageBody = message.getBody();
              // 使用值序列化器转换
              Object msg = redisTemplate.getValueSerializer().deserialize(messageBody);
              // 获取监听的频道
              byte[] channelByte = message.getChannel();
              // 使用字符串序列化器转换
              Object channel = redisTemplate.getStringSerializer().deserialize(channelByte);
              // 渠道名称转换
              String patternStr = new String(pattern);
              System.out.println(patternStr);
              System.out.println("---频道---: " + channel);
              System.out.println("---消息内容---: " + msg);
          }
      }
      
  3. 创建监听配置类

    1. 订阅多个频道使用通配符 *

    2. package com.mucd.config;
      
      import com.mucd.service.RedisListener;
      import org.springframework.context.annotation.Bean;
      import org.springframework.context.annotation.Configuration;
      import org.springframework.data.redis.connection.RedisConnectionFactory;
      import org.springframework.data.redis.listener.PatternTopic;
      import org.springframework.data.redis.listener.RedisMessageListenerContainer;
      
      /**
       * @author mucd
       */
      @Configuration
      public class RedisConfiguration {
      
          @Bean
          public RedisMessageListenerContainer container(RedisConnectionFactory factory, RedisListener listener) {
              RedisMessageListenerContainer container = new RedisMessageListenerContainer();
              container.setConnectionFactory(factory);
              //订阅频道redis.news 和 redis.life  这个container 可以添加多个 messageListener
              container.addMessageListener(listener, patternTopic());
              return container;
          }
      
          /**
           * 订阅多个topic
           * @return new PatternTopic
           */
          @Bean
          public PatternTopic patternTopic(){
              return new PatternTopic("redis.*");
          }
      
      }
      
      
    3. 如果只订阅个别频道使用下面的方式

    4. package com.mucd.config;
      
      import com.mucd.service.RedisListener;
      import org.springframework.context.annotation.Bean;
      import org.springframework.context.annotation.Configuration;
      import org.springframework.data.redis.connection.RedisConnectionFactory;
      import org.springframework.data.redis.listener.PatternTopic;
      import org.springframework.data.redis.listener.RedisMessageListenerContainer;
      
      /**
       * @author mucd
       */
      @Configuration
      public class RedisConfiguration {
      
          @Bean
          public RedisMessageListenerContainer container(RedisConnectionFactory factory, RedisListener listener) {
              RedisMessageListenerContainer container = new RedisMessageListenerContainer();
              container.setConnectionFactory(factory);
              //container可以添加多个订阅频道
              container.addMessageListener(listener,new ChannelTopic("topic"));
              container.addMessageListener(listener,new ChannelTopic("topic02"));
              return container;
          }
      }
      
      
  4. 测试

    1. @Resource
      private RedisTemplate<String, Object> redisTemplate;
      
      @RequestMapping("/send")
      public void test01() {
          redisTemplate.convertAndSend("redis.username", "redis发布的第一条消息");
          redisTemplate.convertAndSend("redis.life", "redis发布的第一条消息");
          log.info("执行完成!");
      }
      

2022/07/21

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以回答这个问题。以下是一个简单的 Spring Boot 实现 Redis 发布订阅的例子: 1. 首先,在 pom.xml 文件中添加 RedisSpring Data Redis 的依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 2. 在 application.properties 文件中配置 Redis 的连接信息: ``` spring.redis.host=127...1 spring.redis.port=6379 ``` 3. 创建一个 Redis 发布者: ``` @Component public class RedisPublisher { @Autowired private RedisTemplate<String, Object> redisTemplate; public void publish(String channel, Object message) { redisTemplate.convertAndSend(channel, message); } } ``` 4. 创建一个 Redis 订阅者: ``` @Component public class RedisSubscriber { @Autowired private MessageListenerAdapter messageListenerAdapter; @PostConstruct public void init() { redisTemplate.execute((RedisCallback<Void>) connection -> { connection.subscribe(messageListenerAdapter, "channel"); return null; }); } @PreDestroy public void destroy() { redisTemplate.execute((RedisCallback<Void>) connection -> { connection.unsubscribe(); return null; }); } } ``` 5. 创建一个消息监听器: ``` @Component public class MessageListenerAdapter extends org.springframework.data.redis.listener.adapter.MessageListenerAdapter { @Override public void onMessage(Message message, byte[] pattern) { String channel = new String(message.getChannel()); String messageBody = new String(message.getBody()); System.out.println("Received message: " + messageBody + " from channel: " + channel); } } ``` 6. 在需要发布消息的地方调用 RedisPublisher 的 publish 方法: ``` @Autowired private RedisPublisher redisPublisher; redisPublisher.publish("channel", "Hello, Redis!"); ``` 这样,当有消息发布到 "channel" 频道时,RedisSubscriber 中的 MessageListenerAdapter 就会收到消息并打印出来。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值