sunny123456

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

springboot整合redis实现消息发布和订阅
https://blog.csdn.net/weixin_43587472/article/details/112296403

springboot整合redis实现消息发布和订阅
先了解一下redis消息发布订阅的机制:
发布者将消息发布在一个channel(可认为是频道)上,可以供多个订阅者订阅查看信息,所以说channel是连接发布者和订阅者之间的桥梁。

1.实现一个用于接听消息的实体类


@Component
public class MessageReceiver implements MessageListener {
    @Autowired
    private RedisTemplate redisTemplate;
    private static Logger logger = LoggerFactory.getLogger(MessageReceiver.class);
    @Override
    public void onMessage(Message message, byte[] bytes) {
        RedisSerializer<String> redisSerializer = redisTemplate.getStringSerializer();
        String msg= redisSerializer.deserialize(message.getBody());
        System.out.println("接收到的消息是:"+ msg);
        logger.info("Received <" + msg + ">");
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17

此处可用@Component注解标识 ,也可以在配置文件即@Configration注解文件中用@Bean注入(这个是标准的springboot注入方式)

2.进行redis消息监听器和适配器的配置


package com.remoteTest.cache.config;
import com.remoteTest.cache.bean.Employee;
import com.remoteTest.cache.bean.MessageReceiver;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import java.net.UnknownHostException;
@Configuration
@AutoConfigureAfter({MessageReceiver.class})
public class MyRedisConfig {
    /*
     * Redis消息监听器容器
     * 这个容器加载了RedisConnectionFactory和消息监听器
     * 可以添加多个监听不同话题的redis监听器,只需要把消息监听器和相应的消息订阅处理器绑定,该消息监听器
     * 通过反射技术调用消息订阅处理器的相关方法进行一些业务处理
     */
    @Bean
    public RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory, MessageListenerAdapter adapter) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        //可以添加多个 messageListener
        container.addMessageListener(adapter,new PatternTopic("topic"));
        return container;
    }
    /*
     * 消息监听器适配器,绑定消息处理器,利用反射技术调用消息处理器的业务方法
     * 将MessageReceiver注册为一个消息监听器,可以自定义消息接收的方法(handleMessage)
     * 如果不指定消息接收的方法,消息监听器会默认的寻找MessageReceiver中的onMessage这个方法作为消息接收的方法
     */
    @Bean
    public MessageListenerAdapter adapter(MessageReceiver messageReceiver) {
        return new MessageListenerAdapter(messageReceiver, "onMessage");
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47

container.addMessageListener(adapter,new PatternTopic(“topic”));
adapter()函数返回值是一个MessageListenerAdapter的对象。
new MessageListenerAdapter(messageReceiver, “onMessage”);第一个参数为接受消息的实体类对象(既上面定义的实体类对象,由adapter()作为参数传进来,第二个参数为实体类中定义的接收消息的方法)该语句中的两个参数一个是消息适配器,下面为配置,第二个参数是channel(既为频道),该参数由发布者提供。

3.下面实现发布者

Controller层


package com.remoteTest.cache.Controller;
import com.remoteTest.cache.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RequestMapping("/redis")
@RestController
public class RedisController {
    @Autowired
    RedisTemplate<String,String> redisTemplate;
    @Autowired
    RedisService redisService;
    @RequestMapping("/publish")
    public String sendMessage (String msg) {
        return redisService.sendMessage(msg);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

Service层

package com.remoteTest.cache.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
@Service
public class RedisService {
    @Autowired
    RedisTemplate<String,String> redisTemplate;
    public String sendMessage (String msg) {
        try {
            redisTemplate.convertAndSend("topic", msg);
            System.out.println(msg);
            return "消息发送成功";
        }catch (Exception e) {
            e.printStackTrace();
            return "消息发送失败";
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

redisTemplate.convertAndSend(“topic”,msg)
该方法用于发布消息,内置函数,可以直接调用,其中两个参数第一个是channle(频道,需和订阅者保持一致),第二个参数是发布的消息。

4.redis配置

#redis连接
server.port=8010
spring.redis.host=127.0.0.1
spring.redis.port=6379
  • 1
  • 2
  • 3
  • 4

密码默认为空

5.启动服务来验证

在这里插入图片描述

posted on 2022-03-27 22:27  sunny123456  阅读(818)  评论(0编辑  收藏  举报