03消息队列系列-RabbitMQ在Spring boot中的使用

03消息队列系列-RabbitMQ在Spring boot中的使用

参考链接:
Springboot 整合RabbitMq

一、项目简介

创建两个项目,一个是rabbitmq-consumer 消息消费者,另一个是rabbitmq-provider消息发送者。基于消息的发送接收去了解直连型交换机、主题交换机、扇形交换机等交换机的使用和消息确认的使用。

二、项目实战

这里使用gradle编译项目

2.1 用到的依赖

implementation 'org.springframework.boot:spring-boot-starter-amqp'

2.2 RabbitMQ在application.properties里的配置

spring.rabbitmq.host=127.0.0.1
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest

2.3 Direct Exchange直连型交换机的使用

2.3.1 创建rabbitmq-provider

2.3.1.1 队列、交换机、绑定信息的配置

创建DirectRabbitConfig类文件,来配置队列、交换机、以及绑定信息

package com.lucky.spring.config;


import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Created by zhangdd on 2020/9/16
 */
@Configuration
public class DirectRabbitConfig {

    /**
     * 队列配置
     * @return
     */
    @Bean
    public Queue directQueue() {
        // durable:是否持久化,默认是false,持久化队列:会被存储在磁盘上,当消息代理重启时仍然存在,暂存队列:当前连接有效
        // exclusive:默认也是false,只能被当前创建的连接使用,而且当连接关闭后队列即被删除。此参考优先级高于durable
        // autoDelete:是否自动删除,当没有生产者或者消费者使用此队列,该队列会自动删除。
        //   return new Queue("TestDirectQueue",true,true,false);

        //一般设置一下队列的持久化就好,其余两个就是默认false
        return new Queue("directQueue", true);
    }

    @Bean
    public DirectExchange directExchange() {
        //durable:是否持久化
        //autoDelete:是否自动删除
        return new DirectExchange("directExchange", true, false);
    }

    @Bean
    public Binding directBinding(){
        return BindingBuilder.bind(directQueue()).to(directExchange())
                .with("directRouting");
    }

}

2.3.1.2 暴露发送消息接口

package com.lucky.spring.controller;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Created by zhangdd on 2020/9/16
 */
@RestController
public class SendDirectMsgController {

    @Autowired
    RabbitTemplate rabbitTemplate;


    @GetMapping("/sendDirectMsg")
    public void sendDirectMsg() {
        String uuid = String.valueOf(UUID.randomUUID());
        String msg = "test message, hello!";
        String createTime = new Date().toString();
        Map<String,Object> map=new HashMap<>();
        map.put("messageId",uuid);
        map.put("messageData",msg);
        map.put("createTime",createTime);

        //将消息携带绑定键值:directRouting 发送到交换机 directExchange
        rabbitTemplate.convertAndSend("directExchange", "directRouting", map);
    }
}

这里对外提供一个接口,用来触发发送消息。调用接口之后,在RabbitMQ管理台的Exchange面板可以看到配置的交换机directExchange以及在队列面板可以看到创建的队列directQueue以及两者的绑定关系。
image.pngimage.png
image.pngimage.png
可以看到消息已经到达队列里了。

2.3.2 创建rabbitmq-consumer

如果是一个单独的消息消费者,那么只需要创建消息接收监听即可。如果既是消息发送者同时又是消息接收者,那就需要创建接收消息监听的同时也需要交换机的配置、队列的配置等信息。这里仅以接收消息说明。

2.3.2.1 创建消息接收监听

package com.lucky.spring.receiver.direct;

import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * Created by zhangdd on 2020/9/19
 */
@Component
@RabbitListener(queues = "directQueue")//配置要监听的队列的名字
public class DirectReceiver {
    @RabbitHandler
    public void process(Map msg) {
        System.out.println("DirectReceiver:收到的消息是:" + msg.toString());
    }
}

2.3.2.2 接收消息

启动rabbitmq-consumer项目,可以看到把之前推送的那条消息消费了下来。可以再次调用rabbitmq-provider里的消息推送接口,可以看到消费者是及时的接收到了消息。

2.3.3 多个监听绑定同一个队列

既然直连交换机是一对一的,如果有多个监听绑定到同一个监听队列,会怎么样。这里在创建出两个 消息接收监听 DirectReceiverADirectReceiverB

package com.lucky.spring.receiver.direct;

import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * Created by zhangdd on 2020/9/19
 */
@Component
@RabbitListener(queues = "directQueue")//配置要监听的队列的名字
public class DirectReceiverA {
    @RabbitHandler
    public void process(Map msg) {
        System.out.println("DirectReceiverA:收到的消息是:" + msg.toString());
    }
}

package com.lucky.spring.receiver.direct;

import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * Created by zhangdd on 2020/9/19
 */
@Component
@RabbitListener(queues = "directQueue")//配置要监听的队列的名字
public class DirectReceiverB {
    @RabbitHandler
    public void process(Map msg) {
        System.out.println("DirectReceiverB:收到的消息是:" + msg.toString());
    }
}

调用rabbitmq-provider的消息推送接口,控制台日志信息如下:

DirectReceiver:收到的消息是:{createTime=Sun Sep 27 08:29:57 CST 2020, messageId=7ffd1517-b3bc-4e72-8355-6b58de4c3277, messageData=test message, hello!}
DirectReceiverA:收到的消息是:{createTime=Sun Sep 27 08:29:59 CST 2020, messageId=2f296ca3-4295-418e-9592-d5d3c90d373a, messageData=test message, hello!}
DirectReceiverB:收到的消息是:{createTime=Sun Sep 27 08:30:00 CST 2020, messageId=759b34c9-98de-4aad-8bc5-fdac2ec5b5ed, messageData=test message, hello!}
DirectReceiver:收到的消息是:{createTime=Sun Sep 27 08:30:07 CST 2020, messageId=bb276692-cf14-405f-a91a-76df7b6e2fca, messageData=test message, hello!}
DirectReceiverA:收到的消息是:{createTime=Sun Sep 27 08:30:13 CST 2020, messageId=15381f29-5769-442d-bece-e5acec33f478, messageData=test message, hello!}
DirectReceiverB:收到的消息是:{createTime=Sun Sep 27 08:30:13 CST 2020, messageId=0dd855f1-f9ef-45f6-9883-c65d6480f0aa, messageData=test message, hello!}
DirectReceiver:收到的消息是:{createTime=Sun Sep 27 08:30:15 CST 2020, messageId=6f902f7c-ff61-4a3b-a6f6-28e428ca8b43, messageData=test message, hello!}

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

2.4 Topic Exchange 主题交换机的使用

2.4.1 rabbitmq-provider端配置

2.4.1.1 队列、交换机、绑定信息的配置

创建 TopicRabbitConfig 类进行交换机、队列、绑定信息的配置。

package com.lucky.spring.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Created by zhangdd on 2020/9/19
 */
@Configuration
public class TopicRabbitConfig {
    //绑定键
    public final static String MAN = "topic.man";
    public final static String WOMAN = "topic.woman";

    @Bean
    public Queue firstQueue() {
        return new Queue(MAN);
    }

    @Bean
    public Queue secondQueue() {
        return new Queue(WOMAN);
    }

    @Bean
    public TopicExchange exchange() {
        return new TopicExchange("topicExchange");
    }

    /**
     * 将 firstQueue与topicExchange绑定,而且绑定的键值为topic.man
     * 这样只要是消息 携带的路由键是 topic.man 才会分发到该队列
     * @return
     */
    @Bean
    public Binding bindingExchange1() {
        return BindingBuilder.bind(firstQueue()).to(exchange()).with(MAN);
    }

    /**
     * 将 secondQueue与topicExchange绑定,而且绑定的键值为用上通配路由键规则topic.#
     * 这样只要是消息 携带的路由键是 topic. 开头都会分发到该队列
     * @return
     */
    @Bean
    public Binding bindingExchange2() {
        return BindingBuilder.bind(secondQueue()).
                to(exchange())
                .with("topic.#");
    }
}

2.4.1.2 添加消息推送接口

package com.lucky.spring.controller;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Created by zhangdd on 2020/9/20
 */
@RestController
public class SendTopicMsgController {

    @Autowired
    private RabbitTemplate rabbitTemplate;


    @GetMapping("/sendTopicMessage1")
    public String sendTopicMessage1() {
        String messageId = String.valueOf(UUID.randomUUID());
        String messageData = "message: M A N ";
        String createTime = new Date().toString();
        Map<String, Object> manMap = new HashMap<>();
        manMap.put("messageId", messageId);
        manMap.put("messageData", messageData);
        manMap.put("createTime", createTime);
        rabbitTemplate.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 = new Date().toString();
        Map<String, Object> womanMap = new HashMap<>();
        womanMap.put("messageId", messageId);
        womanMap.put("messageData", messageData);
        womanMap.put("createTime", createTime);
        rabbitTemplate.convertAndSend("topicExchange", "topic.woman", womanMap);
        return "ok";
    }
}

2.4.2 rabbitmq-consumer端配置

2.4.2.1 创建消息接收监听类

创建消息接收监听类,TopicManReceiverTopicTotalReceiver

package com.lucky.spring.receiver.topic;

import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * Created by zhangdd on 2020/9/20
 */
@Component
@RabbitListener(queues = "topic.man")
public class TopicManReceiver {

    @RabbitHandler
    public void process(Map msg) {
        System.out.println("TopicManReceiver消费者收到消息  : " +
                msg.toString());
    }
}

package com.lucky.spring.receiver.topic;

import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * Created by zhangdd on 2020/9/20
 */
@Component
@RabbitListener(queues = "topic.woman")
public class TopicTotalReceiver {

    @RabbitHandler
    public void process(Map testMessage) {
        System.out.println("TopicTotalReceiver消费者收到消息  : " +
                testMessage.toString());
    }
}

2.4.2.2 推送消息

  • 调用/sendTopicMessage1接口:

在rabbitmq-consumer端 控制台输出信息如下:

TopicManReceiver消费者收到消息  : {createTime=Sun Sep 27 08:41:18 CST 2020, messageId=b949f9fd-0c9e-412d-a55f-9476d2427e3b, messageData=message: M A N }
TopicTotalReceiver消费者收到消息  : {createTime=Sun Sep 27 08:41:18 CST 2020, messageId=b949f9fd-0c9e-412d-a55f-9476d2427e3b, messageData=message: M A N }

TopicManReceiver监听队列1,绑定键为:topic.man
TopicTotalReceiver监听队列2,绑定键为:topic.#


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

  • 调用/sendTopicMessage2接口

在rabbitmq-consumer端 控制台输出信息如下:

TopicTotalReceiver消费者收到消息  : {createTime=Sun Sep 27 08:44:32 CST 2020, messageId=47c434ee-3b6d-4f52-bb75-2482a1dc5893, messageData=message: woman is all }

TopicManReceiver监听队列1,绑定键为:topic.man
TopicTotalReceiver监听队列2,绑定键为:topic.#


当前推送的消息,携带的路由键为:topic.woman ,所以可以看到两个监听消费者只有TopicTotalReceiver成功消费到了消息,因为这个时候只有TopicTotalReceiver监听的队列绑定的键才能与当前消息携带的路由键匹配上。

2.5 Fanout Exchange 扇形交换机的使用

2.5.1 rabbitmq-provider端的配置

2.5.1.1 交换机、队列、绑定等信息的配置

创建FanoutRabbitConfig类对扇形交换机的队列、交换机、绑定等信息配置。

package com.lucky.spring.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.FanoutExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Created by zhangdd on 2020/9/20
 */
@Configuration
public 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());
    }
}

2.5.1.2 添加消息推送接口

package com.lucky.spring.controller;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Created by zhangdd on 2020/9/20
 */
@RestController
public class SendFanoutMsgController {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @GetMapping("/sendFanoutMessage")
    public String sendFanoutMessage() {
        String messageId = String.valueOf(UUID.randomUUID());
        String messageData = "message: testFanoutMessage ";
        String createTime = new Date().toString();
        Map<String, Object> map = new HashMap<>();
        map.put("messageId", messageId);
        map.put("messageData", messageData);
        map.put("createTime", createTime);
        rabbitTemplate.convertAndSend("fanoutExchange", null, map);
        return "ok";
    }
}

2.5.2 rabbitmq-consumer 端配置

2.5.2.1 创建消息消费监听类

这里创建三个 监听类,主要是基于扇形交换机无需路由键配置。

package com.lucky.spring.receiver.fanout;

import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * Created by zhangdd on 2020/9/20
 */
@Component
@RabbitListener(queues = "fanout.A")
public class FanoutAReceiver {

    @RabbitHandler
    public void process(Map testMessage) {
        System.out.println("FanoutReceiverA消费者收到消息  : "
                + testMessage.toString());

    }
}

package com.lucky.spring.receiver.fanout;

import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * Created by zhangdd on 2020/9/20
 */
@Component
@RabbitListener(queues = "fanout.B")
public class FanoutBReceiver {

    @RabbitHandler
    public void process(Map testMessage) {
        System.out.println("FanoutReceiverB消费者收到消息  : " +
                testMessage.toString());
    }
}

package com.lucky.spring.receiver.fanout;

import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * Created by zhangdd on 2020/9/20
 */
@Component
@RabbitListener(queues = "fanout.C")
public class FanoutCReceiver {

    @RabbitHandler
    public void process(Map testMessage) {
        System.out.println("FanoutReceiverC消费者收到消息  : " +
                testMessage.toString());
    }

}

2.5.2.2 推送消息

  • 调用/sendFanoutMessage接口发送消息

rabbitmq-consumer端控制台日志信息如下:

FanoutReceiverA消费者收到消息  : {createTime=Sun Sep 27 12:48:25 CST 2020, messageId=dc5e48bf-d800-4791-8f34-2d6ab8056669, messageData=message: testFanoutMessage }
FanoutReceiverB消费者收到消息  : {createTime=Sun Sep 27 12:48:25 CST 2020, messageId=dc5e48bf-d800-4791-8f34-2d6ab8056669, messageData=message: testFanoutMessage }
FanoutReceiverC消费者收到消息  : {createTime=Sun Sep 27 12:48:25 CST 2020, messageId=dc5e48bf-d800-4791-8f34-2d6ab8056669, messageData=message: testFanoutMessage }

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

2.6消息确认

消息的回调即消息确认(生产者推送消息成功,消费者接收消息成功)。

2.6.1 生产者推送消息确认

2.6.1.1 添加application.properties配置

#确认消息已发送到交换机(Exchange)
spring.rabbitmq.publisher-confirms=true
#确认消息已发送到队列(Queue)
spring.rabbitmq.publisher-returns=true

2.6.1.2 配置消息确认回调函数

package com.lucky.spring.config;


import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Created by zhangdd on 2020/9/20
 */
@Configuration
public class RabbitConfig {

    @Bean
    public RabbitTemplate createRabbitTemplate(ConnectionFactory
                                                       connectionFactory) {
        RabbitTemplate template = new RabbitTemplate();
        template.setConnectionFactory(connectionFactory);
        //设置开启Mandatory,才能触发回调函数,无论消息推送结果怎么样都强制调用回调函数
        template.setMandatory(true);
        template.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                System.out.println("ConfirmCallback:     "+"相关数据:"+correlationData);
                System.out.println("ConfirmCallback:     "+"确认情况:"+ack);
                System.out.println("ConfirmCallback:     "+"原因:"+cause);

            }
        });
        template.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 template;
    }
}

上面就是生产者推送消息的相关回调函数配置,一个是ConfirmCallback另一个是ReturnCallback


先从总体的情况分析,推送消息存在四种情况:
①消息推送到server,但是在server里找不到交换机
②消息推送到server,找到交换机了,但是没找到队列
③消息推送到sever,交换机和队列啥都没找到
④消息推送成功


这里先写几个接口来分别测试和认证下以上4种情况,消息确认触发回调函数的情况:
①消息推送到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 = new Date().toString();
        Map<String, Object> map = new HashMap<>();
        map.put("messageId", messageId);
        map.put("messageData", messageData);
        map.put("createTime", createTime);
        rabbitTemplate.convertAndSend("non-existent-exchange", "TestDirectRouting", map);
        return "ok";
    }

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

ConfirmCallback:     相关数据:null
ConfirmCallback:     确认情况:false
ConfirmCallback:     原因:channel error; protocol method: #method<channel.close>(reply-code=404, reply-text=NOT_FOUND - no exchange 'non-existent-exchange' in vhost '/', class-id=60, method-id=40)
2020-09-27 14:02:47.167 ERROR 67934 --- [ 127.0.0.1:5672] o.s.a.r.c.CachingConnectionFactory       : Channel shutdown: channel error; protocol method: #method<channel.close>(reply-code=404, reply-text=NOT_FOUND - no exchange 'non-existent-exchange' in vhost '/', class-id=60, method-id=40)

结论: ①这种情况触发的是 ConfirmCallback 回调函数。

**②消息推送到server,找到交换机了,但是没找到队列 **
这种情况就是需要新增一个交换机,但是不给这个交换机绑定队列,新增一个直连交换机,名叫‘lonelyDirectExchange’,但没给它做任何绑定配置操作

package com.lucky.spring.config;

import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Exchange;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Created by zhangdd on 2020/9/20
 */
@Configuration
public class MsgCallbackRabbitConfig {

    /**
     * 新增一个交换机,但是不给这个交换机绑定队列
     * @return
     */
    @Bean
    public DirectExchange lonelyDirectExchange() {
        return new DirectExchange("lonelyDirectExchange");
    }
}

然后写个测试接口,把消息推送到名为‘lonelyDirectExchange’的交换机上(这个交换机是没有任何队列配置的):

    @GetMapping("/testMessageAck2")
    public String TestMessageAck2() {
        String messageId = String.valueOf(UUID.randomUUID());
        String messageData = "message: lonelyDirectExchange test message ";
        String createTime = new Date().toString();
        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";
    }

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

ReturnCallback:     消息:(Body:'{createTime=Sun Sep 27 14:08:43 CST 2020, messageId=9009ed23-0329-41fc-9d2a-77bb7ca67680, messageData=message: lonelyDirectExchange test message }' MessageProperties [headers={}, contentType=application/x-java-serialized-object, contentLength=0, receivedDeliveryMode=PERSISTENT, priority=0, deliveryTag=0])
ReturnCallback:     回应码:312
ReturnCallback:     回应信息:NO_ROUTE
ReturnCallback:     交换机:lonelyDirectExchange
ReturnCallback:     路由键:TestDirectRouting
ConfirmCallback:     相关数据:null
ConfirmCallback:     确认情况:true
ConfirmCallback:     原因:null

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

③消息推送到sever,交换机和队列啥都没找到 
这种情况其实一看就觉得跟①很像,没错 ,③和①情况回调是一致的,所以不做结果说明了。
  结论: ③这种情况触发的是 ConfirmCallback 回调函数。

④消息推送成功
那么测试下,按照正常调用之前消息推送的接口就行,就调用下 /sendFanoutMessage接口,可以看到控制台输出:

ConfirmCallback:     相关数据:null
ConfirmCallback:     确认情况:true
ConfirmCallback:     原因:null

结论: ④这种情况触发的是 ConfirmCallback 回调函数。

2.6.2 消费者接收消息确认机制

和生产者的消息确认机制不同,因为消息接收本来就是在监听消息,符合条件的消息就会消费下来。所以消息接收的确认机制主要存在三种模式。

  1. 自动确认:这也是默认的消息确认情况,AcknowledgeMode.NONE
    1. RabbitMQ成功将消息发送(即将消息写入TCP Socket)中立即认为本次投递已经被正确处理,不管消费者端是否成功处理本次投递。
    2. 所以这种情况如果消费端消费逻辑跑出异常,也就是消费端没有处理成功这条消息,那么就相当于丢失了消息。一般这种情况下我们都是使用try catch捕获异常后,打印日志用于追踪数据,这样找出对应数据在做后续处理
  2. 根据情况确认,这个不做介绍
  3. 手动确认,这个比较关键,也是我们配置接收消息确认机制时,多数选择的模式

消费者收到消息后,手动调用basic.ack/basic.nack/basic.reject后,RabbitMQ收到这些消息后,才认为本次投递成功。

  • basic.ack:用于肯定确认
  • basic.nack:用于否定确认
  • basic.reject:用于否定确认,但与basic.nack相比有一个限制:basic.reject一次只能拒绝单条消息


手动确认模式下,消费者端对于以上三个方法都表示消息已经被正确投递,但是basic.ack表示消息已经被正确处理,而basic.nack和basic.reject表示没有被正确处理。

2.6.2.1 basic.reject模式

着重讲下reject,因为有时候一些场景是需要重新入队列的。channel.basicReject(deliveryTag,true),拒绝消费当前消息,如果第二个参数传入true,就是表示将数据重新丢回队列里,那么下次还会消费这条消息。设置false,就是告诉服务器,我已经知道这条消息数据了,因为一些原因拒绝他,而且服务弃也把它丢掉就行了,下次不想在消费这条消息了。


使用拒绝后重新入队列这个模式要谨慎,因为一般都是出现异常的时候,catch异常时选择是否重入队列,但是如果使用不当会导致一些被重入队列的消息一直消费:异常->重入队列->接收消息处理->异常。这样循环会导致消息积压。

2.6.2.2 basic.nack模式

对于basic.nack而言,这个也是设置不消费某条消息.channel.basicNack(deliveryTag,false,true)
第一个参数依然是当前消息数据的唯一ID
第二个参数是指是否针对多条消息,如果是true,也就是说一次性针对当前通道的消息tagID小于当前这小消息的都拒绝确认。
第三个参数是指是否重新入队列,也就是指不确认的消息是否重新丢回到队列里面去

这里同样要注意消息循环积压的问题。

2.6.2.3 消费端配置消息确认

首先创建MyAckReceiver类即手动确认消息监听类,需要实现ChannelAwareMessageListener接口:

package com.lucky.spring.config;

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.ChannelAwareMessageListener;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by zhangdd on 2020/9/20
 */
@Component
public class MyAckReceiver implements ChannelAwareMessageListener {


    @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);
//			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;
    }

}


接着创建MessageListenerConfig添加相关的配置代码:

package com.lucky.spring.config;

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;

/**
 * Created by zhangdd on 2020/9/20
 */
@Configuration
public 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);
        // RabbitMQ默认是自动确认,这里改为手动确认消息
        container.setAcknowledgeMode(AcknowledgeMode.MANUAL);
        //设置一个队列
        container.setQueueNames("directQueue");

        //设置 手动确认消息监听类
        container.setMessageListener(myAckReceiver);

        return container;
    }

}


因为上面配置的是directQueue这个队列作为示例,所以调用/sendDirectMsg接口进行查看结果:

  MyAckReceiver  messageId:b7b95a08-2354-4d90-9f21-376b5bcc1fef  messageData:test message, hello!  createTime:Mon Sep 28 08:41:06 CST 2020
消费的主题消息来自:directQueue

可以看到监听器正常的消费的消息。


到此RabbitMQ在Spring boot中的简单使用就结束了。

posted @ 2020-10-07 19:59  在线打工者  阅读(460)  评论(0编辑  收藏  举报