RabbitMQ交换机与Springboot整合的简单实现

RabbitMQ-交换机

1、交换机是干什么的?消息(Message)由Client发送,RabbitMQ接收到消息之后通过交换机转发到对应的队列上面。Worker会从队列中获取未被读取的数据处理。

1、交换机的种类RabbitMQ包含四种不同的交换机类型:

Direct exchange:直连交换机,转发消息到routigKey指定的队列 Fanout exchange:扇形交换机,转发消息到所有绑定队列(速度最快) Topic exchange:主题交换机,按规则转发消息(最灵活) Headers exchange:首部交换机 (不常用)

1、Direct exchange(直连交换机)

直连交换机是一种带路由功能的交换机,根据消息携带的路由键将消息投递给对应队列。一个队列通过routing_key(路由键)与一个交换机绑定,当消息被发送的时候,需要指定一个routing_key,这个消息被送达交换机的时候,就会被交换机送到指定的队列里面去。类似一对一的关系!

1.1 Springboot的简单实现

创建2个springboot项目,一个 rabbitmq-provider (生产者),一个rabbitmq-consumer(消费者)。

1、首先创建 rabbitmq-provider

pom.xml添加依赖:

<!--rabbitmq-->  <dependency>         <groupId>org.springframework.boot</groupId>         <artifactId>spring-boot-starter-amqp</artifactId>     </dependency>

配置application.yml:

server:  port: 8090spring:  application:    name: rabbitmq-provider  rabbitmq:    host: 192.168.152.173    port: 5672     #注意15672是web页面端口,消息发送端口为5672    username: guest    password: guest

编写配置文件

@Configurationpublic class DirectRabbitConfig {    /**     * 创建消息队列 起名:TestDirectQueue     * durable:是否持久化,默认是false,持久化队列:会被存储在磁盘上,当消息代理重启时仍然存在,暂存队列:当前连接有效     * exclusive:默认也是false,只能被当前创建的连接使用,而且当连接关闭后队列即被删除。此参考优先级高于durable     * autoDelete:是否自动删除,当没有生产者或者消费者使用此队列,该队列会自动删除。     * 一般设置一下队列的持久化就好,其余两个就是默认false     * @return new Queue(name,durable,exclusive,autoDelete)     */    @Bean    public Queue TestDirectQueue() {        return new Queue("TestDirectQueue",true);    }    /**     * Direct交换机 起名:TestDirectExchange     */    @Bean    DirectExchange TestDirectExchange() {        return new DirectExchange("TestDirectExchange",true,false);    }    /**     * 绑定      * 将队列和交换机绑定, 并设置用于匹配键(路由键):TestDirectRouting     */    @Bean    Binding bindingDirect() {        return BindingBuilder.bind(TestDirectQueue()).to(TestDirectExchange()).with("TestDirectRouting");    }   }

编写controller层

@RestController@RequestMapping("/rabbit")public class SendMessageController {    @Autowired    private RabbitTemplate rabbitTemplate;  //使用RabbitTemplate,这提供了接收/发送等等方法    @RequestMapping("/send")    public String sendDirectMessage() {        String messageId = String.valueOf(UUID.randomUUID());        String messageData = "League of Legends never dies!";        String createTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));        Map<String,Object> map=new HashMap<>();        map.put("messageId",messageId);        map.put("messageData",messageData);        map.put("createTime",createTime);        //将消息携带绑定键值:TestDirectRouting 发送到交换机TestDirectExchange        rabbitTemplate.convertAndSend("TestDirectExchange", "TestDirectRouting", map);        return "ok";    }}

把rabbitmq-provider项目运行,调用下接口:

因为我们目前还没弄消费者 rabbitmq-consumer,消息没有被消费的,我们去rabbitMq管理页面看看,是否推送成功:

消息已经推送到rabbitMq服务器上面了。

2、创建rabbitmq-consumer项目:pom.xml和application.yml跟上边一样(把端口号和应用名换了即可)

创建消息接收监听类,DirectReceiver01.java:

@Component@RabbitListener(queues = "TestDirectQueue")//监听的队列名称 TestDirectQueuepublic class DirectReceiver01 {    @RabbitHandler    public void process(Map testMessage) {        System.out.println("DirectReceiver01消费者收到的消息: " + testMessage.toString());    }}

启动消费者项目:运行结果如下

两个消息直接被消费了。然后可以再继续调用rabbitmq-provider项目的推送消息接口,可以看到消费者即时消费消息!

扩展直连交换机既然是一对一,那如果咱们配置多台监听绑定到同一个直连交互的同一个队列,会怎么样?直接复制两份DirectReceiver.java,改下打印内容!

重新启动项目!在生产者多发送几次消息。运行结果如下:

可以看到是实现了轮询的方式对消息进行消费,而且不存在重复消费。

2、Topic Exchange(主题交换机)

直连交换机的routing_key方案非常简单,但是它是一对一的关系,那么我们需要一对多呢?希望一条消息发送给多个队列。所以RabbitMQ提供了一种主题交换机,发送到主题交换机上的消息需要携带指定规则的routing_key,主题交换机会根据这个规则将数据发送到对应的(多个)队列上。

主题交换机的routing_key需要有一定的规则,交换机和队列的binding_key需要采用 *.# 的格式,每个部分用.分开,其中:*表示一个单词#表示任意数量(零个或多个)单词。(例如:topic.man)

1、在rabbitmq-provider项目里面创建TopicRabbitConfig.java:

@Configurationpublic class TopicRabbitConfig {    //绑定键      public final static String man = "topic.man";      public final static String woman = "topic.woman";      @Bean      public Queue firstQueue() {          return new Queue(TopicRabbitConfig.man);      }      @Bean      public Queue secondQueue() {          return new Queue(TopicRabbitConfig.woman);      }      @Bean      TopicExchange exchange() {          return new TopicExchange("topicExchange");      }      //将firstQueue和topicExchange绑定,而且绑定的键值为topic.man      //这样只要是消息携带的路由键是topic.man,才会分发到该队列      @Bean      Binding bindingExchangeMessage() {          return BindingBuilder.bind(firstQueue()).to(exchange()).with(man);      }      //将secondQueue和topicExchange绑定,而且绑定的键值为用上通配路由键规则topic.#      // 这样只要是消息携带的路由键是以topic.开头,都会分发到该队列      @Bean      Binding bindingExchangeMessage2() {          return BindingBuilder.bind(secondQueue()).to(exchange()).with("topic.#");      }}

编写controller层

@RequestMapping("rabbit")@RestControllerpublic class TopicSendController {    @Autowired    private RabbitTemplate template;    @GetMapping("/sendTopicMessage1")    public String sendTopicMessage1() {        String messageId = String.valueOf(UUID.randomUUID());        String messageData = "message: M A N ";        String createTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));        Map<String, Object> manMap = new HashMap<>();        manMap.put("messageId", messageId);        manMap.put("messageData", messageData);        manMap.put("createTime", createTime);        template.convertAndSend("topicExchange", "topic.man", manMap);        return "ok";    }    @GetMapping("/sendTopicMessage2")    public String sendTopicMessage2() {        String messageId = String.valueOf(UUID.randomUUID());        String messageData = "message: woman is all ";        String createTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));        Map<String, Object> womanMap = new HashMap<>();        womanMap.put("messageId", messageId);        womanMap.put("messageData", messageData);        womanMap.put("createTime", createTime);        template.convertAndSend("topicExchange", "topic.woman", womanMap);        return "ok";    }}

不要急着去运行,先去编写消费者,创建两个接口

TopicManReceiver :

@Component@RabbitListener(queues = "topic.man")public class TopicManReceiver {    @RabbitHandler    public void process(Map testMessage) {        System.out.println("TopicManReceiver消费者收到消息  : " + testMessage.toString());    }}

TopicWoManReceiver :

@Component@RabbitListener(queues = "topic.woman")public class TopicWoManReceiver {    @RabbitHandler    public void process(Map testMessage) {        System.out.println("TopicWoManReceiver消费者收到消息  : " + testMessage.toString());    }}

然后把rabbitmq-provider,rabbitmq-consumer两个项目都跑起来,先调用/sendTopicMessage1 接口:

然后看消费者rabbitmq-consumer的控制台输出情况:TopicManReceiver监听队列1,绑定键为:topic.manTopicTotalReceiver监听队列2,绑定键为:topic.#而当前推送的消息,携带的路由键为:topic.man

所以可以看到两个监听消费者receiver都成功消费到了消息,因为这两个recevier监听的队列的绑定键都能与这条消息携带的路由键匹配上。

用/sendTopicMessage2接口:

然后看消费者rabbitmq-consumer的控制台输出情况:TopicManReceiver监听队列1,绑定键为:topic.manTopicTotalReceiver监听队列2,绑定键为:topic.#而当前推送的消息,携带的路由键为:topic.woman

所以可以看到两个监听消费者,只有TopicWoManReceiver 成功消费到了消息,

3、Fanout exchange(扇形交换机)

扇形交换机是最基本的交换机类型,它做的事情很简单–广播信息。Fanout交换机会把接收到的消息全部转发到绑定的队列上。因为广播不需要“思考”,所以Fanout交换机是四种交换机中速度最快的。

同样地,先在rabbitmq-provider项目上创建FanoutRabbitConfig.java:

@Configurationpublic class FanoutRabbitConfig {    /**     * 创建三个队列 :fanout.A   fanout.B  fanout.C     * 将三个队列都绑定在交换机 fanoutExchange 上     * 因为是扇型交换机, 路由键无需配置,配置也不起作用     */    @Bean    public Queue queueA() {        return new Queue("fanout.A");    }    @Bean    public Queue queueB() {        return new Queue("fanout.B");    }    @Bean    public Queue queueC() {        return new Queue("fanout.C");    }    @Bean    FanoutExchange fanoutExchange() {        return new FanoutExchange("fanoutExchange");    }    @Bean    Binding bindingExchangeA() {        return BindingBuilder.bind(queueA()).to(fanoutExchange());    }    @Bean    Binding bindingExchangeB() {        return BindingBuilder.bind(queueB()).to(fanoutExchange());    }    @Bean    Binding bindingExchangeC() {        return BindingBuilder.bind(queueC()).to(fanoutExchange());    }}

编写controller层:

@RestController@RequestMapping("rabbit")public class FanoutController {    @Autowired    private RabbitTemplate template;    @GetMapping("/sendFanoutMessage")    public String sendFanoutMessage() {        String messageId = String.valueOf(UUID.randomUUID());        String messageData = "message: testFanoutMessage ";        String createTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));        Map<String, Object> map = new HashMap<>();        map.put("messageId", messageId);        map.put("messageData", messageData);        map.put("createTime", createTime);        template.convertAndSend("fanoutExchange", null, map);        return "ok";    }}

接着在rabbitmq-consumer项目里加上消息消费类,

FanoutReceiverA:

@Component@RabbitListener(queues = "fanout.A")public class FanoutReceiverA {    @RabbitHandler    public void process(Map testMessage) {        System.out.println("FanoutReceiverC消费者收到消息  : " +testMessage.toString());    }}

FanoutReceiverB

@Component@RabbitListener(queues = "fanout.B")public class FanoutReceiverB{    @RabbitHandler    public void process(Map testMessage) {        System.out.println("FanoutReceiverC消费者收到消息  : " +testMessage.toString());    }}

FanoutReceiverC :

@Component@RabbitListener(queues = "fanout.C")public class FanoutReceiverC {    @RabbitHandler    public void process(Map testMessage) {        System.out.println("FanoutReceiverC消费者收到消息  : " +testMessage.toString());    }}

最后将rabbitmq-provider和rabbitmq-consumer项目都跑起来,调用下接口/sendFanoutMessage,运行结果如下:

可以看到只要发送到 fanoutExchange 这个扇型交换机的消息, 三个队列都绑定这个交换机,所以三个消息接收类都监听到了这条消息。

4、消息确认(发送确认与接收确认) 4.1发送确认

在rabbitmq-provider项目中编写配置文件:

server:  port: 8090spring:  application:    name: rabbitmq-consumer  rabbitmq:    host: 192.168.152.173    port: 5672    username: guest    password: guest    #确认消息已发送到交换机(Exchange)    publisher-confirm-type: correlated    #确认消息已发送到队列(Queue)    publisher-returns: true

配置相关的消息确认回调函数,RabbitConfig.java:

/** * 配置相关的消息确认回调函数 */@Configurationpublic class RabbitConfig {    @Bean    public RabbitTemplate createRabbitTemplate(ConnectionFactory connectionFactory) {        RabbitTemplate rabbitTemplate = new RabbitTemplate();        rabbitTemplate.setConnectionFactory(connectionFactory);        //设置开启Mandatory,才能触发回调函数,无论消息推送结果怎么样都强制调用回调函数        rabbitTemplate.setMandatory(true);        //确认回调        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {            @Override            public void confirm(CorrelationData correlationData, boolean condition, String cause) {                System.out.println("ConfirmCallback:     " + "相关数据:" + correlationData);                System.out.println("ConfirmCallback:     " + "确认情况:" + condition);                System.out.println("ConfirmCallback:     " + "原因:" + cause);            }        });        //设置返回消息的回调        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {            @Override            public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {                System.out.println("ReturnCallback:     " + "消息:" + message);                System.out.println("ReturnCallback:     " + "回应码:" + replyCode);                System.out.println("ReturnCallback:     " + "回应信息:" + replyText);                System.out.println("ReturnCallback:     " + "交换机:" + exchange);                System.out.println("ReturnCallback:     " + "路由键:" + routingKey);            }        });        return rabbitTemplate;    }}

ConfirmCallbackConfirmCallback是一个回调接口,就是只确认是否正确到达 Exchange 中。ReturnCallback通过实现 ReturnCallback 接口,启动消息失败返回,此接口是在交换器路由不到队列时触发回调,该方法可以不使用,因为交换器和队列是在代码里绑定的,如果存在绑定队列失败,那就是你代码写错了。

从总体的情况分析,推送消息存在四种情况:

1、消息推送到server,但是在server里找不到交换机2、消息推送到server,找到交换机了,但是没找到队列3、消息推送到sever,交换机和队列啥都没找到4、消息推送成功

1、消息推送到server,但是在server里找不到交换机写个测试接口,把消息推送到名为‘non-existent-exchange’的交换机上(这个交换机是没有创建没有配置的):

 @GetMapping("/TestMessageAck")    public String TestMessageAck() {        String messageId = String.valueOf(UUID.randomUUID());        String messageData = "message: non-existent-exchange test message ";        String createTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));        Map<String, Object> map = new HashMap<>();        map.put("messageId", messageId);        map.put("messageData", messageData);        map.put("createTime", createTime);        //non-existent-exchange这个交换机没有创建和配置        template.convertAndSend("non-existent-exchange", "TestDirectRouting", map);        return "ok";    }

调用接口,查看rabbitmq-provuder项目的控制台输出情况

因为这个交换机没有创建,消息不能到达到达 Exchange 中。所以会触发ConfirmCallback这个回调函数

结论: 只会触发ConfirmCallback。

2、消息推送到server,找到交换机了,但是没找到队列新增一个交换机,但是不给这个交换机绑定队列,在DirectRabitConfig里面新增一个直连交换机,不做任何绑定配置操作:

 @Bean    DirectExchange lonelyDirectExchange() {        return new DirectExchange("lonelyDirectExchange");    }

同样编写测试接口

 @GetMapping("/TestMessageAck2")    public String TestMessageAck2() {        String messageId = String.valueOf(UUID.randomUUID());        String messageData = "message: lonelyDirectExchange test message ";        String createTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));        Map<String, Object> map = new HashMap<>();        map.put("messageId", messageId);        map.put("messageData", messageData);        map.put("createTime", createTime);        rabbitTemplate.convertAndSend("lonelyDirectExchange", "TestDirectRouting", map);        return "ok";    }

调用方法,查看运行结果:

可以看到两个回调函数都被调用了;这种情况下,消息是推送成功到服务器了的,所以ConfirmCallback对消息确认情况是true;而在RetrunCallback回调函数的打印参数里面可以看到,消息是推送到了交换机成功了,但是在路由分发给队列的时候,找不到队列,所以报了错误 NO_ROUTE。结论: 两个回调函数都会触发!

3、消息推送到sever,交换机和队列啥都没找到结论: 触发的是 ConfirmCallback 回调函数。

4、消息推送成功结论: 触发的是 ConfirmCallback 回调函数。

总结: ConfirmCallback回调函数总是会被触发,确认情况true和false是有没有找到交换机,false的话打印原因。ReturnCallback是交换机路由不到队列是回调,也就是你交换机没有绑定队列,这个回调函数可以不写,绑定失败的话就好好看看代码哪里写错了吧。

以上是生产者推送消息的消息确认 回调函数的使用介绍!

4.2 接受确认

消费者确认发生在监听队列的消费者处理业务失败,如,发生了异常,不符合要求的数据……,这些场景我们就需要手动处理,比如重新发送或者丢弃。

消息确认模式有:

AcknowledgeMode.NONE:自动确认 AcknowledgeMode.AUTO:根据情况确认 AcknowledgeMode.MANUAL:手动确认

参考:https://blog.csdn.net/qq_35387940/article/details/100514134

4.1.1 自动确认

修改消费者配置文件

rabbitmq:  host: 192.168.152.173  port: 5672  username: guest  password: guest  listener:    direct:      acknowledge-mode: auto   # manual:手动

在消费者项目里,新建MessageListenerConfig.java上添加代码相关的配置代码:

package com.zsn.demo.config;import com.zsn.demo.resceiver.MyAckReceiver;import org.springframework.amqp.core.AcknowledgeMode;import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;/** * @author: zhouzhou * @date:2021/7/22 9:49 */@Configurationpublic class MessageListenerConfig {    @Autowired    private CachingConnectionFactory connectionFactory;    @Autowired    private MyAckReceiver myAckReceiver;//消息接收处理类    @Bean    public SimpleMessageListenerContainer simpleMessageListenerContainer() {        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory);        container.setConcurrentConsumers(1);        container.setMaxConcurrentConsumers(1);        container.setAcknowledgeMode(AcknowledgeMode.MANUAL); // RabbitMQ默认是自动确认,这里改为手动确认消息        //设置一个队列        container.setQueueNames("TestDirectQueue");        //如果同时设置多个如下: 前提是队列都是必须已经创建存在的        //  container.setQueueNames("TestDirectQueue","TestDirectQueue2","TestDirectQueue3");        //另一种设置队列的方法,如果使用这种情况,那么要设置多个,就使用addQueues        //container.setQueues(new Queue("TestDirectQueue",true));        //container.addQueues(new Queue("TestDirectQueue2",true));        //container.addQueues(new Queue("TestDirectQueue3",true));        container.setMessageListener(myAckReceiver);        return container;    }}

对应的手动确认消息监听类,MyAckReceiver.java(手动确认模式需要实现 ChannelAwareMessageListener):

package com.zsn.demo.resceiver;import com.rabbitmq.client.Channel;import org.springframework.amqp.core.Message;import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;import org.springframework.stereotype.Component;import java.util.HashMap;import java.util.Map;/** * @author: zhouzhou * @date:2021/7/22 9:50 */@Componentpublic class MyAckReceiver implements ChannelAwareMessageListener {    /**     * 用于处理接收到的 Rabbit 消息的回调。     * 实现者应该处理指定的信息     * 通常通过给定的会话发送回复消息     * @param message the received AMQP message (never <code>null</code>)     * @param channel the underlying Rabbit Channel (never <code>null</code>)     * @throws Exception Any.     */    @Override    public void onMessage(Message message, Channel channel) throws Exception {        long deliveryTag = message.getMessageProperties().getDeliveryTag();        try {            //因为传递消息的时候用的map传递,所以将Map从Message内取出需要做些处理            String msg = message.toString();            String[] msgArray = msg.split("'");//可以点进Message里面看源码,单引号直接的数据就是我们的map消息数据            Map<String, String> msgMap = mapStringToMap(msgArray[1].trim(),3);            String messageId=msgMap.get("messageId");            String messageData=msgMap.get("messageData");            String createTime=msgMap.get("createTime");            System.out.println("  MyAckReceiver  messageId:"+messageId+"  messageData:"+messageData+"  createTime:"+createTime);            System.out.println("消费的主题消息来自:"+message.getMessageProperties().getConsumerQueue());            channel.basicAck(deliveryTag, true); //第二个参数,手动确认可以被批处理,当该参数为 true 时,则可以一次性确认 delivery_tag 小于等于传入值的所有消息//channel.basicReject(deliveryTag, true);//第二个参数,true会重新放回队列,所以需要自己根据业务逻辑判断什么时候使用拒绝        } catch (Exception e) {            channel.basicReject(deliveryTag, false);            e.printStackTrace();        }    }    //{key=value,key=value,key=value} 格式转换成map    private Map<String, String> mapStringToMap(String str,int entryNum ) {        str = str.substring(1, str.length() - 1);        String[] strs = str.split(",",entryNum);        Map<String, String> map = new HashMap<String, String>();        for (String string : strs) {            String key = string.split("=")[0].trim();            String value = string.split("=")[1];            map.put(key, value);        }        return map;    }}

需要注意的 basicAck 方法需要传递两个参数

deliveryTag(唯一标识 ID):当一个消费者向 RabbitMQ 注册后,会建立起一个 Channel ,RabbitMQ 会用 basic.deliver 方法向消费者推送消息,这个方法携带了一个 delivery tag, 它代表了 RabbitMQ 向该 Channel 投递的这条消息的唯一标识 ID,是一个单调递增的正整数,delivery tag 的范围仅限于 Channel multiple:为了减少网络流量,手动确认可以被批处理,当该参数为 true 时,则可以一次性确认 delivery_tag 小于等于传入值的所有消息

basicNack方法需要传递三个参数

deliveryTag(唯一标识 ID):上面已经解释了。 multiple:上面已经解释了。 requeue: true :重回队列,false :丢弃,我们在nack方法中必须设置 false,否则重发没有意义。

basicReject方法需要传递两个参数

deliveryTag(唯一标识 ID):上面已经解释了。 requeue:上面已经解释了,在reject方法里必须设置true。

总结

    basic.ack用于肯定确认 basic.nack用于否定确认(注意:这是AMQP 0-9-1的RabbitMQ扩展) basic.reject用于否定确认,但与basic.nack相比有一个限制:一次只能拒绝单条消息

消费者端以上的3个方法都表示消息已经被正确投递,但是basic.ack表示消息已经被正确处理。而basic.nack,basic.reject表示没有被正确处理:

这时,先调用接口,给直连交换机TestDirectExchange 的队列TestDirectQueue 推送一条消息,可以看到监听器正常消费了下来:

扩展1除了直连交换机的队列TestDirectQueue需要变成手动确认以外,我们还需要将一个其他的队列或者多个队列也变成手动确认,而且不同队列实现不同的业务处理。那么我们需要做的第一步,往SimpleMessageListenerContainer里添加多个队列

MyAckReceiver.java 就可以同时将上面设置到的队列的消息都消费下来。

@Componentpublic class MyAckReceiver implements ChannelAwareMessageListener {   /**     * 用于处理接收到的 Rabbit 消息的回调。     * 实现者应该处理指定的信息     * 通常通过给定的会话发送回复消息     * @param message the received AMQP message (never <code>null</code>)     * @param channel the underlying Rabbit Channel (never <code>null</code>)     * @throws Exception Any.     */    @Override    public void onMessage(Message message, Channel channel) throws Exception {        long deliveryTag = message.getMessageProperties().getDeliveryTag();        try {            //因为传递消息的时候用的map传递,所以将Map从Message内取出需要做些处理            String msg = message.toString();            String[] msgArray = msg.split("'");//可以点进Message里面看源码,单引号直接的数据就是我们的map消息数据            Map<String, String> msgMap = mapStringToMap(msgArray[1].trim(),3);            String messageId=msgMap.get("messageId");            String messageData=msgMap.get("messageData");            String createTime=msgMap.get("createTime");                        if ("TestDirectQueue".equals(message.getMessageProperties().getConsumerQueue())){                System.out.println("消费的消息来自的队列名为:"+message.getMessageProperties().getConsumerQueue());                System.out.println("消息成功消费到  messageId:"+messageId+"  messageData:"+messageData+"  createTime:"+createTime);                System.out.println("执行TestDirectQueue中的消息的业务处理流程......");                            }             if ("fanout.A".equals(message.getMessageProperties().getConsumerQueue())){                System.out.println("消费的消息来自的队列名为:"+message.getMessageProperties().getConsumerQueue());                System.out.println("消息成功消费到  messageId:"+messageId+"  messageData:"+messageData+"  createTime:"+createTime);                System.out.println("执行fanout.A中的消息的业务处理流程......");             }                        channel.basicAck(deliveryTag, true);//channel.basicReject(deliveryTag, true);//为true会重新放回队列        } catch (Exception e) {            channel.basicReject(deliveryTag, false);            e.printStackTrace();        }    }     //{key=value,key=value,key=value} 格式转换成map    private Map<String, String> mapStringToMap(String str,int enNum) {        str = str.substring(1, str.length() - 1);        String[] strs = str.split(",",enNum);        Map<String, String> map = new HashMap<String, String>();        for (String string : strs) {            String key = string.split("=")[0].trim();            String value = string.split("=")[1];            map.put(key, value);        }        return map;    }}

分别调用这两个队列相关接口,运行结果如下:

扩展2: 手动确认的另一种写法:我们在实际工作中可能不会这么写,一般会写在server层,自己定义一个接口:RabbitConsumerService

public interface RabbitConsumerService {    void process(Channel channel, Message message) throws IOException;}
@Componentpublic class RabbitConsumerServiceImpl implements RabbitConsumerService{    @RabbitHandler    @RabbitListener(queues = "TestDirectQueue")    @Override    public void process(Channel channel, Message message) throws IOException {        long deliveryTag = message.getMessageProperties().getDeliveryTag();        try {            //因为传递消息的时候用的map传递,所以将Map从Message内取出需要做些处理            String msg = message.toString();            String[] msgArray = msg.split("'");//可以点进Message里面看源码,单引号直接的数据就是我们的map消息数据            Map<String, String> msgMap = mapStringToMap(msgArray[1].trim(),3);            String messageId=msgMap.get("messageId");            String messageData=msgMap.get("messageData");            String createTime=msgMap.get("createTime");            System.out.println("  MyAckReceiver  messageId:"+messageId+"  messageData:"+messageData+"  createTime:"+createTime);            System.out.println("消费的主题消息来自:"+message.getMessageProperties().getConsumerQueue());            channel.basicAck(deliveryTag, true); //第二个参数,手动确认可以被批处理,当该参数为 true 时,则可以一次性确认 delivery_tag 小于等于传入值的所有消息//channel.basicReject(deliveryTag, true);//第二个参数,true会重新放回队列,所以需要自己根据业务逻辑判断什么时候使用拒绝        } catch (Exception e) {            channel.basicReject(deliveryTag, false);            e.printStackTrace();        }    }    //{key=value,key=value,key=value} 格式转换成map    private Map<String, String> mapStringToMap(String str,int entryNum ) {        str = str.substring(1, str.length() - 1);        String[] strs = str.split(",",entryNum);        Map<String, String> map = new HashMap<String, String>();        for (String string : strs) {            String key = string.split("=")[0].trim();            String value = string.split("=")[1];            map.put(key, value);        }        return map;    }}

@Component这个理论上要换成@service,但是由于我没有添加日志,所以换成@service会报错,这里就是提供一个思路,运行结果如下:

附:rabbitmq在application.yml文件中的其他配置

rabbitmq:    addresses: 192.168.152.193:5672    username: guest    password: guest      #虚拟host 可以不设置,使用server默认host    virtual-host: /    listener:      simple:        prefetch: 1               #设置一次处理一个消息        acknowledge-mode: manual  #设置消费端手动 ack        concurrency: 3            #设置同时有3个消费者消费    connection-timeout: 500    # 确认消息是否正确到达queue,如果没有则触发,如果有则不触发    publisher-returns: true    #确认消息已发送到交换机(Exchange)    publisher-confirm-type: correlated    template:      #设置为 true后 消费者在消息没有被路由到合适队列情况下会被return监听,而不会自动删除      mandatory: true

解释:Mandatory 设置为 true 则会监听器会接受到路由不可达的消息,然后处理。如果设置为 false,broker 将会自动删除该消息。

参考https://blog.csdn.net/qq_35387940/article/details/100514134

到此这篇关于RabbitMQ交换机与Springboot整合的简单实现的文章就介绍到这了,更多相关RabbitMQ Springboot整合内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

每个人在他的人生发轫之初,总有一段时光,

RabbitMQ交换机与Springboot整合的简单实现

相关文章:

你感兴趣的文章:

标签云: