• RabbitMQ的入门篇


    目录

    1. RabbitMQ简介

      1.1 RabbitMQ

      1.2 RabbitMQ的介绍

      1.3 RabbitMQ的特点

    2. RabbitMQ的安装

      2.1 RabbitMQ下载 

      2.2 下载的安装包

    ​  2.3  安装步骤

      2.4  登录访问

     3. RabbitMQ的入门

      3.1 RabbitMQ的架构原理

      3.2 永远的hello world程序 

    4. RabbitMQ的工作模式

     4.1 简单模式(Hello World)

     4.2 工作队列模式(Work Queues) 

     4.3 发布订阅模式(Publish/Subscribe) 

     4.4 路由模式(Routing) 

     4.5 主题模式(Topics) 

     4.6 发布确认模式(Publisher Confirms)  

    5. RabbitMQ的注解开发

     5.1 简单模式

     5.2 工作队列

     5.3 发布订阅

     5.4 路由模式

     5.5 主题模式

     5.6 发布确认 


         学习一门新技术,我们总会遇到许许多多的陌生名词,我们可以从我们熟悉的点切入,去学习和关联这门我们不熟悉的技术。RabbitMQ我们比较熟悉的是Q(Queue)队列的意思,那RabbitMQ是不是就是一个保存消息的队列,更准确的说法是,RabbitMQ是一个消息代理中间件。

    1. RabbitMQ简介

       1.1 RabbitMQ

      基于AMQP协议,erlang语言开发,是部署最广泛的开源消息中间件,是最受欢迎的开源消息中间件之一

       1.2 RabbitMQ的介绍

            RabbitMQ是使用Erlang语言来编写的,实现了AMQP协议的一款MQ产品。AMQP,即Advanced Message Queuing Protocol(高级消息队列协议),是一个网络协议,是应用层协议的一个开放标准,为面向消息的中间件设计。基于此协议的客户端与消息中间件可传递消息,并不受客户端/中间件不同产品,不同的开发语言等条件的限制。MQ(Message Queue)消息队列是以生产者和消费者的异步通信原理来实现系统解耦合的。

       1.3 RabbitMQ的特点

    • 可靠性。支持持久化,传输确认,发布确认,消费端消息手动确认等保证了MQ的可靠性 。
    • 灵活的分发消息策略。分发消息策略有:简单模式、工作队列模式、发布订阅模式、路由模式、主题模式。
    • 支持集群。多台RabbitMQ服务器可以组成一个集群,形成一个逻辑Broker。
    • 多种协议。RabbitMQ支持多种消息队列协议,比如 AMQP、STOMP、MQTT 等等。
    • 支持多种语言客户端。RabbitMQ几乎支持所有常用编程语言,包括 Java、Python 、JavaScript、Ruby、Go等。
    • 插件机制。RabbitMQ提供了许多插件,可以通过插件进行扩展,也可以编写自己的插件。

    2. RabbitMQ的安装

      2.1 RabbitMQ下载 

          官网下载地址:https://www.rabbitmq.com/download.html

          我们可以根据自身需求和操作系统版本下载自己想要的版本,我现在选择的是Linux操作系统CentOS版本下的 rabbitmq-server-3.8.22-1.el7.noarch.rpm,同时也需要下载erlang语言的依赖 erlang-23.2.5-1.el7.x86_64.rpm

      2.2 下载的安装包

      2.3  安装步骤

            1. 上传rabbitmq的软件包到Linux目录       

     

            2.  先安装erlang的依赖包

       rmp -ivh erlang-23.2.5-1.el7.x86_64.rpm

            3.  再安装socat的依赖包

       rmp -ivh socat-1.7.3.2-5.el7.lux.x86_64.rpm

            4.  最后安装rabbitmq的依赖包

       rmp -ivh rabbitmq-server-3.8.22-1.el7.noarch.rpm

            5.  安装成功后再新建主配置文件rabbitmq.conf

       vim /etc/rabbitmq/rabbitmq.conf

            6.  rabbitmq.conf 配置文中添加如下配置

    1. # 默认允许登录的用户名,无法修改
    2. default_user = guest
    3. # 默认用户的密码,无法修改
    4. default_pass = guest
    5. # 配置默认用户的身份为管理员
    6. default_user_tags.administrator = true
    7. # 创建默认用户时分配给它的​权限​​
    8. default_permissions.configure = .*
    9. default_permissions.read = .*
    10. default_permissions.write = .*
    11. # 默认loopback_users.guest = true,只允许本机访问,配置“guest”用户能够远程连接
    12. # 注意,生产环境下不建议开启guest用户远程登录
    13. loopback_users = none

             7. 用户管理

    1. rabbitmqctl add_user admin 123 # 创建新用户和密码
    2. rabbitmqctl change_password admin admin123 # 修改用户密码
    3. rabbitmqctl set_user_tags admin administrator # 设置角色
    4. rabbitmqctl set_permissions -p / admin '.*' '.*' '.*' # 设置用户权限

             8. 开启rabbitmq的管理界面插件功能

       rabbitmq-plugins enable rabbitmq_management

             9.  启动rabbitmq的服务

       systemctl start rabbitmq-server

    2.4  登录访问

         在浏览器中访问:192.168.8.129:15672 打开登录界面,输入用户名和密码:guest / guest 进行登录,登录成功后就可以进入到RabbitMQ的管理界面。

     

     3. RabbitMQ的入门

       3.1 RabbitMQ的架构原理

     RabbitMQ中的相关概念:

    •  Broker:RabbitMQ的实体服务器,提供一种传输服务,维护一条从生产者到消费者的传输线路,保证消息数据能按照指定的方式传输。
    • Virtual host:虚拟主机,与用户绑定,用于环境隔离。用户只能在自己的虚拟主机中创建Exchange和Queue,并且同一个虚拟主机里面不能有相同名称的Exchange或Queue。
    • Connection:Producer或Consumer和Broker之间建立的TCP连接。
    • Channel:Channel是在Connection内部建立的逻辑连接,如果应用程序支持多线程,通常每个thread创建单独的Channel进行通信,Channel作为轻量级的Connection极大减少了操作系统建立TCP Connection的开销。
    • Exchange:交换机,接收消息,按照路由规则将消息路由到一个或者多个队列。如果路由不到,或者返回给生产者,或者直接丢弃。RabbitMQ常用的交换器常用类型有direct、topic、fanout、headers四种。
    • Queue:接收交换机路由的消息的容器,消费者监听队列中有消息后进行消费。
    • Binding:绑定,Exchange和Queue之间的虚拟连接,绑定中可以包含一个或者多个routingKey。Binding信息被保存到Exchange中的查询表中,用于消息分发的依据。

      3.2 永远的hello world程序 

    •  添加Maven依赖
    1. <dependency>
    2. <groupId>com.rabbitmqgroupId>
    3. <artifactId>amqp-clientartifactId>
    4. <version>5.8.0version>
    5. dependency>
    • 在rabbitmq的管理界面中新建虚拟主机 /study 

    •  书写RabbitMQUtils工具类
    1. package com.example.rabbitmq.common;
    2. import com.rabbitmq.client.Channel;
    3. import com.rabbitmq.client.Connection;
    4. import com.rabbitmq.client.ConnectionFactory;
    5. /**
    6. * @author: gjm
    7. * @date: 2021/9/2 13:50
    8. * @description: TODO
    9. */
    10. public class RabbitMQUtils {
    11. private static final ConnectionFactory connectionFactory;
    12. static {
    13. //创建连接mq的连接工厂对象
    14. connectionFactory = new ConnectionFactory();
    15. //设置连接rabbitmq主机
    16. connectionFactory.setHost("192.168.8.129");
    17. //设置端口号
    18. connectionFactory.setPort(5672);
    19. //设置连接哪个虚拟主机
    20. connectionFactory.setVirtualHost("/study");
    21. //设置访问虚拟主机的用户名和密码
    22. connectionFactory.setUsername("guest");
    23. connectionFactory.setPassword("guest");
    24. }
    25. /**
    26. * 获取连接的方法
    27. * @return
    28. */
    29. public static Connection getRabbitMQConnection(){
    30. try{
    31. return connectionFactory.newConnection();
    32. }catch (Exception e){
    33. e.printStackTrace();
    34. }
    35. return null;
    36. }
    37. /**
    38. * 关闭通道和连接的方法
    39. * @param channel
    40. * @param conn
    41. */
    42. public static void closeConnectionAndChanel(Channel channel, Connection conn) {
    43. try{
    44. if(channel != null) channel.close();
    45. if(conn != null) conn.close();
    46. } catch (Exception e) {
    47. e.printStackTrace();
    48. }
    49. }
    50. }
    •  书写生产者Provider 
    1. import com.example.rabbitmq.common.RabbitMQUtils;
    2. import com.rabbitmq.client.Channel;
    3. import com.rabbitmq.client.Connection;
    4. import java.io.IOException;
    5. /**
    6. * @author: gjm
    7. * @date: 2021/9/2 11:05
    8. * @description: 生产者发送消息
    9. */
    10. public class Provider {
    11. private static final String QUEUE_NAME = "hello";
    12. public static void main(String[] args) throws IOException{
    13. //获取连接对象
    14. Connection connection = RabbitMQUtils.getRabbitMQConnection();
    15. //获取连接中通道
    16. Channel channel = connection.createChannel();
    17. //通道绑定对应消息队列
    18. //参数1: 队列名称,如果队列不存在则自动创建
    19. //参数2: 用来定义队列是否要持久化 true:持久化队列,false:不持久化
    20. //参数3: 是否独占队列 true: 独占队列, false: 不独占
    21. //参数4: autoDelete 是否在消费完成后自动删除队列, true:自动删除,false: 不自动删除
    22. channel.queueDeclare(QUEUE_NAME, true, false, false, null);
    23. //发布消息
    24. //参数1:交换机名称 参数2:队列名称 参数3:传递消息额外设置 参数4:消息的具体内容
    25. channel.basicPublish("",QUEUE_NAME, null, "hello world".getBytes());
    26. //关闭连接
    27. RabbitMQUtils.closeConnectionAndChanel(channel, connection);
    28. }
    29. }
    •  书写消费者Consumer
    1. import com.rabbitmq.client.*;
    2. import com.example.rabbitmq.common.RabbitMQUtils;
    3. import java.io.IOException;
    4. /**
    5. * @author: guojm
    6. * @date: 2021/9/3 0:47
    7. * @description: 消费者消费消息
    8. */
    9. public class Consumer {
    10. private static final String QUEUE_NAME = "hello";
    11. public static void main(String[] args) throws IOException{
    12. //获取连接对象
    13. Connection connection = RabbitMQUtils.getRabbitMQConnection();
    14. //获取连接中通道
    15. Channel channel = connection.createChannel();
    16. //通道绑定对应消息队列
    17. //参数1: queue: 队列名称,如果队列不存在则自动创建
    18. //参数2: durable: 队列是否要持久化 true:持久化队列,false:不持久化
    19. //参数3: exclusive: 是否独占队列 true: 独占队列, false: 不独占
    20. //参数4: autoDelete 是否在消费完成后自动删除队列, true:自动删除,false: 不自动删除
    21. channel.queueDeclare(QUEUE_NAME, true, false, false, null);
    22. System.out.println("等待消息中...");
    23. // 消息消费时回调函数
    24. DeliverCallback deliverCallback = (consumerTag, message)->{
    25. System.out.println("消费消息:" + new String(message.getBody()));
    26. System.out.println("等待消息中...");
    27. };
    28. // 消息取消时回调函数
    29. CancelCallback cancelCallback = consumerTag ->{};
    30. //发布消息
    31. //参数1: 消费哪个队列的消息 队列名称
    32. //参数2: 开始消息的自动确认机制
    33. //参数3: 消息的接收回调
    34. //参数3: 消息的取消回调
    35. channel.basicConsume(QUEUE_NAME, true, deliverCallback, cancelCallback);
    36. }
    37. }
    •    先执行消费者没有消息时会等待,再执行生产者发送消息,消费者有消息时就会消费消息 

    4. RabbitMQ的工作模式

      4.1 简单模式(Hello World)

          在上图的简单模式中一个生产者(Producer)生产的消息只有一个消费者(Consumer)消费,Producer直接发送消息到hello队列,Consumer直接从hello队列中取出消息消费。  

    • 简单模式生产者代码为入门案例代码
    1. //获取连接对象
    2. Connection connection = RabbitMQUtils.getRabbitMQConnection();
    3. //获取连接中通道
    4. Channel channel = connection.createChannel();
    5. //通道绑定对应消息队列
    6. channel.queueDeclare("hello", true, false, false, null);
    7. //生产者直接发送消息给队列
    8. channel.basicPublish("","hello", null, "hello world".getBytes());
    9. //关闭连接
    10. RabbitMQUtils.closeConnectionAndChanel(channel, connection);
    • 消费者代码也是入门案例代码
    1. //获取连接对象
    2. Connection connection = RabbitMQUtils.getRabbitMQConnection();
    3. //获取连接中通道
    4. Channel channel = connection.createChannel();
    5. //通道绑定对应消息队列
    6. channel.queueDeclare("hello", true, false, false, null);
    7. System.out.println("等待消息中...");
    8. // 消息消费时回调函数
    9. DeliverCallback deliverCallback = (consumerTag, message)->{
    10. System.out.println("消费消息:" + new String(message.getBody()));
    11. System.out.println("等待消息中...");
    12. };
    13. // 消息取消时回调函数
    14. CancelCallback cancelCallback = consumerTag ->{};
    15. // 消费者直接从队列中取出消息消费
    16. channel.basicConsume("hello", true, deliverCallback, cancelCallback);

    4.2 工作队列模式(Work Queues) 

       在工作队列模式中一个生产者(Producer)生产的消息由多个消费者(Consumer)消费,这种情况适合生产者生产消息速度远远大于消息消费速度的场景。这种模式下可以让多个消费者绑定同一个队列,共同消费队列中的消息,多个消费者之间是竞争关系,消息不会被重复消费。

    •  工作队列的生产者代码
    1. import com.rabbitmq.client.Channel;
    2. import com.rabbitmq.client.Connection;
    3. import com.example.rabbitmq.common.RabbitMQUtils;
    4. import java.io.IOException;
    5. /**
    6. * @author: gjm
    7. * @date: 2021/9/04 22:03
    8. * @description: Work Queues 模式的生产者
    9. */
    10. public class Producer {
    11. private static final String QUEUE_NAME = "work_queue";
    12. public static void main(String[] args) throws IOException {
    13. // 获取rabbitmq 的连接
    14. Connection connection = RabbitMQUtils.getRabbitMQConnection();
    15. // 通过连接获取信道
    16. Channel channel = connection.createChannel();
    17. // 声明队列
    18. channel.queueDeclare(QUEUE_NAME, false, false, false, null);
    19. // 发布消息给队列
    20. for (int i = 0; i < 10; i++) {
    21. channel.basicPublish("",QUEUE_NAME, null, ("work queues 生产者的消息" + i ).getBytes());
    22. }
    23. // 关闭连接
    24. RabbitMQUtils.closeConnectionAndChanel(channel,connection);
    25. }
    26. }
    • 工作队列的消费者代码,创建消费者1 和消费者2共同消费。
    1. import com.rabbitmq.client.*;
    2. import com.example.rabbitmq.common.RabbitMQUtils;
    3. import java.io.IOException;
    4. /**
    5. * @author: gjm
    6. * @date: 2021/9/04 22:11
    7. * @description: Work Queues 模式的消费者
    8. */
    9. public class Consumer1 {
    10. private static final String QUEUE_NAME = "work_queue";
    11. public static void main(String[] args) throws IOException {
    12. // 获取rabbitmq的连接对象
    13. Connection connection = RabbitMQUtils.getRabbitMQConnection();
    14. // 通过连接对象获取信道
    15. Channel channel = connection.createChannel();
    16. // 声明队列,如果队列不存在则自动创建
    17. channel.queueDeclare(QUEUE_NAME, false, false, false, null);
    18. // 消息消费时回调函数
    19. DeliverCallback deliverCallback = (consumerTag, message)-> {
    20. System.out.println("消费者1:" + new String(message.getBody()));
    21. };
    22. // 获取队列中的消息
    23. channel.basicConsume(QUEUE_NAME, true, deliverCallback,consumerTag ->{});
    24. }
    25. }
    • 先运行消费者1和消费者2代码,再运行生产者代码查看消费情况。从下面的结果我们可以看出工作队列模式中的消息默认是循环分发给每一个消费者的,就是不管消费者的消费速度如何都会按照轮询分发给每一个消费者。

     

    • 工作队列模式中的代码优化,消费者端不开启消息的自动确认机制,autoAck设置为fasle,开启消息的自动确认机制可能会导致消息丢失。因为消费者端开启消息的自动确认机制后消息会轮询分发给消费者等待消费,不管消息是否消费成功都会立马在队列中删除,这时如果消费端宕机就会导致消息丢失。
    1. import com.rabbitmq.client.*;
    2. import com.example.rabbitmq.common.RabbitMQUtils;
    3. import java.io.IOException;
    4. /**
    5. * @author: gjm
    6. * @date: 2021/9/04 22:11
    7. * @description: Work Queues 消费者手动确认消息
    8. */
    9. public class Consumer1 {
    10. private static final String QUEUE_NAME = "work_queue";
    11. public static void main(String[] args) throws IOException {
    12. // 获取rabbitmq的连接对象
    13. Connection connection = RabbitMQUtils.getRabbitMQConnection();
    14. // 通过连接对象获取信道
    15. Channel channel = connection.createChannel();
    16. // 声明队列,如果队列不存在则自动创建
    17. channel.queueDeclare(QUEUE_NAME, false, false, false, null);
    18. // 消息消费时回调函数
    19. DeliverCallback deliverCallback = (consumerTag, message)-> {
    20. System.out.println("消费者1:" + new String(message.getBody()));
    21. // 手动确认消息
    22. // 参数1:被确认消息的标签信息,参数2:是否批量确认消息
    23. channel.basicAck(message.getEnvelope().getDeliveryTag(), false);
    24. };
    25. // 消费队列中的消息,关闭消息的自动确认机制,autoAck设置为false
    26. channel.basicConsume(QUEUE_NAME, false, deliverCallback,consumerTag ->{});
    27. }
    28. }
    • 工作队列模式实现消费端能者多劳,即消费者消费快的能多消费消息,实现消息的不公平分发。这时只需要在消费者端设置信道每次只能接受一个消息等待消费,消费者消费快的就能多接收消息消费。
    1. // 消费者端设置信道每次只能接收一个消息
    2. channel.basicQos(1);
    3. // 消息消费时回调函数
    4. DeliverCallback deliverCallback = (consumerTag, message)-> {
    5. //模拟消息消费慢的场景
    6. try{
    7. Thread.sleep(500);
    8. }catch (Exception e){
    9. e.printStackTrace();
    10. }
    11. System.out.println("消费者1:" + new String(message.getBody()));
    12. // 手动确认消息
    13. // 参数1:被确认消息的标签信息,参数2:是否批量确认消息
    14. channel.basicAck(message.getEnvelope().getDeliveryTag(), false);
    15. };
    16. // 消费队列中的消息,关闭消息的自动确认机制,autoAck设置为false
    17. channel.basicConsume(QUEUE_NAME, false, deliverCallback,consumerTag ->{});
    •  工作队列模式中的能者多劳效果实现

     

     4.3 发布订阅模式(Publish/Subscribe) 

         发布订阅模式也被称为广播模式,就是使用广播(fanout)类型的交换机实现的。生产者直接发送消息给交换机,由交换机负责将消息转发给绑定的多个队列实现被多个消费者消费的效果。这个模式实现一个消息被多个消费者消费的原理是用到了多个临时队列,fanout型交换机把一个消息转发到了多个队列中,每个队列的消费者各自消费自己绑定队列中的消息。

    • 发布订阅模式的生产者代码 
    1. import com.example.rabbitmq.common.RabbitMQUtils;
    2. import com.rabbitmq.client.Channel;
    3. import com.rabbitmq.client.Connection;
    4. import java.io.IOException;
    5. /**
    6. * @author: gjm
    7. * @date: 2021/9/2 21:06
    8. * @description: Publish/Subscribe模型的生产者
    9. */
    10. public class Producer {
    11. public static void main(String[] args)throws IOException {
    12. //获取连接对象
    13. Connection connection = RabbitMQUtils.getRabbitMQConnection();
    14. Channel channel = connection.createChannel();
    15. //通过通道声明指定交换机
    16. // 参数1:交换机名称 参数2:交换机类型 fanout广播类型
    17. channel.exchangeDeclare("logs", "fanout");
    18. //发布消息给交换机
    19. channel.basicPublish("logs", "",null, "Publish/Subscribe 生产者的消息".getBytes());
    20. //关闭连接
    21. RabbitMQUtils.closeConnectionAndChanel(channel, connection);
    22. }
    23. }
    • 发布订阅模式的消费者代码,创建消费者1和消费者2演示消息的广播效果
    1. import com.example.rabbitmq.common.RabbitMQUtils;
    2. import com.rabbitmq.client.*;
    3. import java.io.IOException;
    4. /**
    5. * @author: gjm
    6. * @date: 2021/9/2 21:30
    7. * @description: Publish/Subscribe模型的消费者1
    8. */
    9. public class consumer1 {
    10. public static void main(String[] args)throws IOException {
    11. //获取连接对象
    12. Connection connection = RabbitMQUtils.getRabbitMQConnection();
    13. //获取通道
    14. Channel channel = connection.createChannel();
    15. //通道绑定交换机
    16. channel.exchangeDeclare("logs", "fanout");
    17. //临时队列
    18. String queueName = channel.queueDeclare().getQueue();
    19. //绑定交换机和临时队列
    20. channel.queueBind(queueName, "logs", "");
    21. //消费消息
    22. channel.basicConsume(queueName, true, new DefaultConsumer(channel){
    23. @Override
    24. public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
    25. System.out.println("消费者1:" + new String(body));
    26. }
    27. });
    28. }
    29. }
    • 先运行消费者在管理界面中查看创建的临时队列信息

    • 消费者1和消费者2都消费到了生产者发送的消息

     

     4.4 路由模式(Routing) 

     

          路由模式是由direct类型的交换机实现的,交换机和队列通过routingKey进行绑定,生产者发送消息给交换机时需要指定routingKey,交换机在转发消息给队列时会根据routingKey直接找到队列转发。路由模式下同一个routingKey可以和多个队列绑定,所以也能实现广播模式的效果,但是业务中一般是消息是需要由不同的标识做区别处理场景下使用。

    • 路由模式的生产者代码 
    1. import com.example.rabbitmq.common.RabbitMQUtils;
    2. import com.rabbitmq.client.Channel;
    3. import com.rabbitmq.client.Connection;
    4. import java.io.IOException;
    5. /**
    6. * @author: gjm
    7. * @date: 2021/9/3 9:50
    8. * @description: 路由模式的生产者
    9. */
    10. public class Producer {
    11. public static final String ROUTING_KEY = "error";
    12. public static void main(String[] args) throws IOException {
    13. //获取连接对象
    14. Connection connection = RabbitMQUtils.getRabbitMQConnection();
    15. //获取连接中的信道
    16. Channel channel = connection.createChannel();
    17. //通过信道声明交换机名称和类型
    18. channel.exchangeDeclare("logs direct", "direct");
    19. //发送消息给交换机并指定routingKey
    20. channel.basicPublish("logs direct", ROUTING_KEY,null, ("路由模型生产者发布的routingKey:"+ ROUTING_KEY +"的消息").getBytes());
    21. //关闭连接
    22. RabbitMQUtils.closeConnectionAndChanel(channel,connection);
    23. }
    24. }
    •  路由模式的消费者代码 
    1. import com.example.rabbitmq.common.RabbitMQUtils;
    2. import com.rabbitmq.client.*;
    3. import java.io.IOException;
    4. /**
    5. * @author: gjm
    6. * @date: 2021/9/3 10:04
    7. * @description: 路由模式的消费者
    8. */
    9. public class Consumer1 {
    10. public static void main(String[] args) throws IOException {
    11. //获取连接对象
    12. Connection connection = RabbitMQUtils.getRabbitMQConnection();
    13. //获取连接的信道对象
    14. Channel channel = connection.createChannel();
    15. //通过信道声明交换机名称和类型
    16. channel.exchangeDeclare("logs direct", "direct");
    17. //创建一个临时队列
    18. String queue = channel.queueDeclare().getQueue();
    19. //基于routingkey绑定队列和交换机
    20. channel.queueBind(queue, "logs direct", "error");
    21. //获取消费的消息
    22. channel.basicConsume(queue, true, new DefaultConsumer(channel){
    23. @Override
    24. public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
    25. System.out.println("消费者1:"+ new String(body));
    26. }
    27. });
    28. }
    29. }
    •  消费者1程序运行,生产者发送routingKey为error的消息只能被routingKey也为error的消费者消费

    4.5 主题模式(Topics) 

      

         主题模式本质就是路由模式的升级,也被称为动态路由模式。消费者端在声明队列和topic类型的交换机绑定时采用通配符形式的routingKey达到动态匹配的效果,这种模型routingKey一般是由一个或多个单词组成,多个单词之间以 “.” 分割,例如 order.create

    • 通配符 * 只能代替一个词
      比如:user.* 只能匹配 user.create 或 user.update这种.后面一个单词的
    •  通配符 # 可以替换零个或多个单词
      比如:order.# 能匹配 order.seckill.create 或 order.delete
    •  主题模式的生产者代码 
    1. import com.example.rabbitmq.common.RabbitMQUtils;
    2. import com.rabbitmq.client.Channel;
    3. import com.rabbitmq.client.Connection;
    4. import java.io.IOException;
    5. /**
    6. * @author: gjm
    7. * @date: 2021/9/3 10:38
    8. * @description: topics模式的生产者
    9. */
    10. public class Producer {
    11. public static final String ROUTING_KEY = "order.seckill.create";
    12. public static void main(String[] args) throws IOException {
    13. //获取连接对象
    14. Connection connection = RabbitMQUtils.getRabbitMQConnection();
    15. //获取连接的信道对象
    16. Channel channel = connection.createChannel();
    17. //通过信道声明交换机名称和类型
    18. channel.exchangeDeclare("topics", "topic");
    19. //发布消息
    20. channel.basicPublish("topics", ROUTING_KEY,null, ("主题模式生产者发布的routingKey:"+ ROUTING_KEY +"的消息").getBytes());
    21. //关闭连接
    22. RabbitMQUtils.closeConnectionAndChanel(channel,connection);
    23. }
    24. }
    • 主题模式的消费者代码 
    1. import com.example.rabbitmq.common.RabbitMQUtils;
    2. import com.rabbitmq.client.*;
    3. import java.io.IOException;
    4. /**
    5. * @author: gjm
    6. * @date: 2021/9/3 10:51
    7. * @description: topics模式的消费者
    8. */
    9. public class Consumer1 {
    10. public static void main(String[] args) throws IOException{
    11. //获取连接对象
    12. Connection connection = RabbitMQUtils.getRabbitMQConnection();
    13. //获取连接的信道对象
    14. Channel channel = connection.createChannel();
    15. //通过信道声明交换机名称和类型
    16. channel.exchangeDeclare("topics", "topic");
    17. //通过信道声明队列
    18. channel.queueDeclare("Q1", true, false, false, null);
    19. //基于通配符的routingkey绑定队列和交换机
    20. channel.queueBind("Q1", "topics", "order.#");
    21. //消费消息
    22. channel.basicConsume("Q1", true, new DefaultConsumer(channel){
    23. @Override
    24. public void handleDelivery(String consumerTag, Envelope envelope,
    25. AMQP.BasicProperties properties, byte[] body) throws IOException {
    26. System.out.println("消费者1:"+ new String(body));
    27. }
    28. });
    29. }
    30. }
    • 消费者1程序运行,生产者发送routingKey为order.seckill.create的消息被routingKey为order.#的消费者消费

    4.6 发布确认模式(Publisher Confirms)  

         

          发布确认模式和前面介绍的模式有所不同,它更像是一种生产者端保证消息能够进行可靠投递的一种发送策略。如何保证消息不丢失这是生产中经常需要解决的问题,我们一般需要对队列和消息进行开启持久化机制,但是还需要考虑生产者端和消费者端的消息丢失问题,而发布确认模式是用于解决生产者发布消息到MQ服务器的过程中的消息丢失问题。从上图可以看出 RabbitMQ 提供的是“至少一次交付”(at-least-once delivery),异常情况下,消息会被重复投递或消费。

    • 单个消息发布确认策略,即每次发布一个消息后都等待MQ服务端应答确认成功后再继续发下一个消息;这种方式消息投递的效率不高,但是比较可靠。
    1. import com.rabbitmq.client.Channel;
    2. import com.rabbitmq.client.Connection;
    3. import com.rabbitmq.client.MessageProperties;
    4. import com.example.rabbitmq.common.RabbitMQUtils;
    5. import java.io.IOException;
    6. import java.util.UUID;
    7. /**
    8. * @author: gjm
    9. * @date: 2021/9/05 8:50
    10. * @description: 单个消息发布确认策略
    11. */
    12. public class PublishMessageIndividually {
    13. public static void main(String[] args) throws IOException, InterruptedException {
    14. // 获取rabbitmq的连接
    15. Connection connection = RabbitMQUtils.getRabbitMQConnection();
    16. // 通过连接创建信道
    17. Channel channel = connection.createChannel();
    18. // 生成队列名称
    19. String queueName = UUID.randomUUID().toString();
    20. // 声明队列,开启队列持久化
    21. channel.queueDeclare(queueName, true, false,false, null);
    22. // 开启发布确认
    23. channel.confirmSelect();
    24. // 开始时间
    25. long begin = System.currentTimeMillis();
    26. int count = 0;
    27. // 批量发消息
    28. for (int i = 0; i < 1000; i++) {
    29. String message ="单个确认模式的消息: "+i;
    30. // 投递消息,设置消息的持久化
    31. channel.basicPublish("",queueName, MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes());
    32. // 单个消息发送后,调用同步等待确认方法获取结果
    33. boolean flag = channel.waitForConfirms();
    34. // 如果flag为true则表明消息被确认成功投递
    35. if(flag) count++;
    36. }
    37. // 如果确认的消息数等于发布数则消息被全部投递成功
    38. if (count == 1000) {
    39. System.out.println("成功投递"+ count + "个消息并且确认");
    40. }
    41. //关闭连接
    42. RabbitMQUtils.closeConnectionAndChanel(channel, connection);
    43. long end = System.currentTimeMillis();
    44. System.out.println("投递"+ 1000 + "个单个确认的消息,耗时:"+(end-begin)+"ms");
    45. }
    46. }

       单个消息发布确认策略运行结果: 

    •  批量消息发布确认策略,即每次发布一批消息后才去请求MQ服务端的确认应答结果。这种方式要保证这一批消息全部都成功发送才能拿到确认成功的结果,中间只要有一条发送不成功拿到的是全局不成功的结果false。官网上已经说明这样会导致我们不知道哪条信息没有被成功发送,需要记录这批消息的内容做消息的发送重试,这会导致消息的重复发送,消费者端要处理消息的幂等性问题。
    1. import com.rabbitmq.client.Channel;
    2. import com.rabbitmq.client.Connection;
    3. import com.rabbitmq.client.MessageProperties;
    4. import com.example.rabbitmq.common.RabbitMQUtils;
    5. import java.io.IOException;
    6. import java.util.UUID;
    7. /**
    8. * @author: gjm
    9. * @date: 2021/9/05 9:57
    10. * @description: 消息批量确认策略
    11. */
    12. public class PublishMessageBatch {
    13. public static void main(String[] args) throws IOException, InterruptedException {
    14. // 获取rabbitmq的连接
    15. Connection connection = RabbitMQUtils.getRabbitMQConnection();
    16. // 通过连接创建信道
    17. Channel channel = connection.createChannel();
    18. // 生成队列名称
    19. String queueName = UUID.randomUUID().toString();
    20. // 声明队列,开启队列持久化
    21. channel.queueDeclare(queueName, true, false,false, null);
    22. // 开启发布确认
    23. channel.confirmSelect();
    24. // 开始时间
    25. long begin = System.currentTimeMillis();
    26. // 每次确认需要投递的消息总数
    27. int batchSize = 100;
    28. // 记录已投递的消息总数
    29. int outstandingMessageCount = 0;
    30. // 记录确认的次数
    31. int confirmCount = 0;
    32. // 批量发消息
    33. for (int i = 0; i < 1000; i++) {
    34. String message ="批量确认模式的消息: "+i;
    35. // 投递消息,设置消息的持久化
    36. channel.basicPublish("",queueName, MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes());
    37. // 已投递的消息+1
    38. outstandingMessageCount ++;
    39. // 已投递的消息总数达到确认要求
    40. if (outstandingMessageCount == batchSize) {
    41. outstandingMessageCount = 0;
    42. confirmCount ++;
    43. boolean confirms = channel.waitForConfirms();
    44. if (confirms) {
    45. System.out.println("第" +confirmCount+ "次投递"+ batchSize +"条消息并确认");
    46. }
    47. }
    48. }
    49. RabbitMQUtils.closeConnectionAndChanel(channel, connection);
    50. long end = System.currentTimeMillis();
    51. System.out.println("投递"+ 1000 + "个批量确认消息,耗时:"+(end-begin)+"ms");
    52. }
    53. }

     批量消息发布确认策略运行结果: 

    • 异步消息发布确认策略,即消息的发布和确认是异步的,可以显著提升消息发布的速度,也能通过异步消息确认的回调函数记录出未被确认投递成功的消息,三种消息确认发布策略中官网也指出这种效率为最高。
    1. import com.rabbitmq.client.Channel;
    2. import com.rabbitmq.client.ConfirmCallback;
    3. import com.rabbitmq.client.Connection;
    4. import com.example.rabbitmq.common.RabbitMQUtils;
    5. import java.io.IOException;
    6. import java.util.concurrent.ConcurrentNavigableMap;
    7. import java.util.concurrent.ConcurrentSkipListMap;
    8. /**
    9. * @author: gjm
    10. * @date: 2021/9/05 11:12
    11. * @description: 异步消息发布确认策略 
    12. */
    13. public class PublishMessageAsync {
    14. public static void main(String[] args) throws IOException{
    15. // 获取rabbitmq的连接
    16. Connection connection = RabbitMQUtils.getRabbitMQConnection();
    17. // 通过连接创建信道
    18. Channel channel = connection.createChannel();
    19. // 声明队列,开启队列持久化
    20. String queueName = "confirm_queue";
    21. channel.queueDeclare(queueName, true, false,false, null);
    22. // 开启发布确认
    23. channel.confirmSelect();
    24. // 开始时间
    25. long begin = System.currentTimeMillis();
    26. // 记录未确认的消息,方便后续重发
    27. ConcurrentSkipListMap outstandingConfirms = new ConcurrentSkipListMap<>();
    28. //消息确认成功的回调函数
    29. ConfirmCallback ackCallback = ((deliveryTag, multiple) -> {
    30. /*
    31. * 如果multiple等于true表明这次回调为多个消息确认,标识为deliveryTag的消息和他前面的消息都一起被确认
    32. * 如果multiple等于false表明这次回调为单个消息确认,只有标识为deliveryTag的消息被确认
    33. */
    34. if (multiple) {
    35. // 使用headMap方法拿到标识为deliveryTag的消息和他前面的消息
    36. ConcurrentNavigableMap confirmed = outstandingConfirms.headMap(deliveryTag, true);
    37. // 批量删除已确认的消息
    38. confirmed.clear();
    39. } else {
    40. // 删除单个确认的消息
    41. outstandingConfirms.remove(deliveryTag);
    42. }
    43. System.out.println("多个消息确认:"+ multiple + " -- 确认的消息deliveryTag:"+ deliveryTag);
    44. });
    45. //消息未确认的回调函数
    46. ConfirmCallback nackCallback = ((deliveryTag, multiple) -> {
    47. // 取出未确认的消息
    48. String message = outstandingConfirms.get(deliveryTag);
    49. // 打印消息的详情
    50. System.out.println("message:"+ message+ " -- deliveryTag:" +deliveryTag+ " -- multiple:"+multiple);
    51. });
    52. // 消息的监听器,监听哪些消息成功和失败
    53. channel.addConfirmListener(ackCallback, nackCallback);
    54. // 批量发消息
    55. for (int i = 0; i < 1000; i++) {
    56. String message ="批量异步确认模式的消息: "+i;
    57. channel.basicPublish("",queueName, MessageProperties.PERSISTENT_TEXT_PLAIN, message.getBytes());
    58. // 保存未处理的确认信息
    59. outstandingConfirms.put(channel.getNextPublishSeqNo(), message);
    60. }
    61. long end = System.currentTimeMillis();
    62. System.out.println("投递"+ 1000 + "个异步批量确认消息,耗时:"+(end-begin)+"ms");
    63. }
    64. }

     异步消息发布确认策略运行结果:

     

    5. RabbitMQ的注解开发

       5.1 简单模式

    •  添加springboot整合rabbitmq的依赖
    1. <dependency>
    2. <groupId>org.springframework.boot</groupId>
    3. <artifactId>spring-boot-starter-amqp</artifactId>
    4. </dependency>
    •  在application.yml文件中配置如下内容
    1. spring:
    2. rabbitmq:
    3. host: 192.168.8.129
    4. port: 5672
    5. username: guest
    6. password: guest
    7. virtual-host: /study
    •  书写生产者的代码,使用接口开发,在SpringBoot程序的主入口类上书写注解@EnableRabbit ,表示开启rabbitmq的自动配置功能,然后就可以直接注入和使用RabbitTemplate对象非常简单地发送消息给指定队列。
    1. import org.slf4j.Logger;
    2. import org.slf4j.LoggerFactory;
    3. import org.springframework.amqp.rabbit.core.RabbitTemplate;
    4. import org.springframework.beans.factory.annotation.Autowired;
    5. import org.springframework.web.bind.annotation.RequestMapping;
    6. import org.springframework.web.bind.annotation.RestController;
    7. /**
    8. * @author: gjm
    9. * @date: 2021/9/04 10:14
    10. * @description: 生产者端
    11. */
    12. @RestController
    13. @RequestMapping("/producer")
    14. public class ProducerController {
    15. private Logger logger = LoggerFactory.getLogger(ProducerController.class);
    16. @Autowired
    17. private RabbitTemplate rabbitTemplate;
    18. @RequestMapping("/simple")
    19. public String sendSimpleMessage(){
    20. String message = "Hello World";
    21. rabbitTemplate.convertAndSend("hello", message);
    22. logger.info("简单模式的生产者发送了消息:{}", message);
    23. return "success";
    24. }
    25. }
    • 书写消费者的代码,消费者端使用@RabbitListener注解来声明一个队列,表示这是消费者端。通过@Queue(value = "hello")指定的队列名称,并且可以指定队列持久化,独占,自动删除等参数,默认不指定的话队列是持久化,非独占,非自动删除的。
    1. import org.slf4j.Logger;
    2. import org.slf4j.LoggerFactory;
    3. import org.springframework.amqp.rabbit.annotation.Queue;
    4. import org.springframework.amqp.rabbit.annotation.RabbitHandler;
    5. import org.springframework.amqp.rabbit.annotation.RabbitListener;
    6. import org.springframework.stereotype.Component;
    7. /**
    8. * @author: gjm
    9. * @date: 2021/9/04 9:40
    10. * @description: 消费者端
    11. */
    12. @Component
    13. @RabbitListener(queuesToDeclare = @Queue(value = "hello"))
    14. public class Consumer {
    15. private Logger logger = LoggerFactory.getLogger(Consumer.class);
    16. @RabbitHandler
    17. public void receive(String message){
    18. logger.info("简单模式的消费者接收了消息:{}", message);
    19. }
    20. }
    • 运行程序,调用接口/producer/simple发送消息,消费者端会监听到消息并处理。

     

     5.2 工作队列

    •  加入配置
    1. spring:
    2. rabbitmq:
    3. listener:
    4. simple:
    5. prefetch: 1 # 消费预取值,设置为1可实现消费者能者多劳,不设置则为轮询分发
    6. acknowledge-mode: manual # 消息需消费者手动确认
    • 生产者代码
    1. import org.slf4j.Logger;
    2. import org.slf4j.LoggerFactory;
    3. import org.springframework.amqp.rabbit.core.RabbitTemplate;
    4. import org.springframework.beans.factory.annotation.Autowired;
    5. import org.springframework.web.bind.annotation.RequestMapping;
    6. import org.springframework.web.bind.annotation.RestController;
    7. /**
    8. * @author: gjm
    9. * @date: 2021/9/04 10:14
    10. * @description: 生产者端
    11. */
    12. @RestController
    13. @RequestMapping("/producer")
    14. public class ProducerController {
    15. private Logger logger = LoggerFactory.getLogger(ProducerController.class);
    16. @Autowired
    17. private RabbitTemplate rabbitTemplate;
    18. @RequestMapping("/work")
    19. public String sendWorkMessage(){
    20. for (int i = 0; i < 10; i++) {
    21. String message = "work mode message " + i;
    22. rabbitTemplate.convertAndSend("work", message);
    23. }
    24. logger.info("工作模式的生产者发送了10条消息");
    25. return "success";
    26. }
    27. }
    •  消费者代码
    1. import com.rabbitmq.client.Channel;
    2. import org.slf4j.Logger;
    3. import org.slf4j.LoggerFactory;
    4. import org.springframework.amqp.core.Message;
    5. import org.springframework.amqp.rabbit.annotation.Queue;
    6. import org.springframework.amqp.rabbit.annotation.RabbitListener;
    7. import org.springframework.stereotype.Component;
    8. import java.io.IOException;
    9. import java.util.concurrent.TimeUnit;
    10. /**
    11. * @author: gjm
    12. * @date: 2021/9/04 9:15
    13. * @description: 工作队列消费者
    14. */
    15. @Component
    16. public class WorkConsumer {
    17. private Logger logger = LoggerFactory.getLogger(WorkConsumer.class);
    18. @RabbitListener(queuesToDeclare = @Queue(value = "work"))
    19. public void consumer1(String body, Message message, Channel channel) throws InterruptedException{
    20. logger.info("工作模式的消费者1接收了消息:{}", body);
    21. TimeUnit.MILLISECONDS.sleep(500);
    22. try {
    23. // 消费者手动确认消息已消费
    24. channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    25. } catch (IOException e) {
    26. e.printStackTrace();
    27. }
    28. }
    29. @RabbitListener(queuesToDeclare = @Queue(value = "work"))
    30. public void consumer2(String body, Message message, Channel channel) {
    31. logger.info("工作模式的消费者2接收了消息:{}", body);
    32. try {
    33. // 消费者手动确认消息已消费
    34. channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    35. } catch (IOException e) {
    36. e.printStackTrace();
    37. }
    38. }
    39. }

    5.3 发布订阅

    •  使用配置类的方式声明队列和交换机并进行绑定(Binding)
    1. import org.springframework.amqp.core.*;
    2. import org.springframework.context.annotation.Bean;
    3. import org.springframework.context.annotation.Configuration;
    4. /**
    5. * @author: gjm
    6. * @date: 2021/9/05 8:16
    7. * @description: 发布订阅模式的配置类
    8. */
    9. @Configuration
    10. public class FanoutModeConfig {
    11. // 交换机名称
    12. public static final String FANOUT_EXCHANGE_NAME = "fanout_exchange";
    13. // 队列名称
    14. public static final String FANOUT_QUEUE1_NAME = "fanout_queue1";
    15. // 队列名称
    16. public static final String FANOUT_QUEUE2_NAME = "fanout_queue2";
    17. // 创建fanout类型的交换机
    18. @Bean
    19. public FanoutExchange fanoutExchange() {
    20. return new FanoutExchange(FANOUT_EXCHANGE_NAME);
    21. }
    22. // 声明队列
    23. @Bean
    24. public Queue fanoutQueue1() {
    25. return QueueBuilder.durable(FANOUT_QUEUE1_NAME).build();
    26. }
    27. // 声明队列
    28. @Bean
    29. public Queue fanoutQueue2() {
    30. return QueueBuilder.durable(FANOUT_QUEUE2_NAME).build();
    31. }
    32. // 队列fanoutQueue1和交换机绑定
    33. @Bean
    34. public Binding queue1BindingExchange(Queue fanoutQueue1, FanoutExchange fanoutExchange) {
    35. return BindingBuilder.bind(fanoutQueue1).to(fanoutExchange);
    36. }
    37. // 队列fanoutQueue2和交换机绑定
    38. @Bean
    39. public Binding queue2BindingExchange(Queue fanoutQueue2, FanoutExchange fanoutExchange) {
    40. return BindingBuilder.bind(fanoutQueue2).to(fanoutExchange);
    41. }
    42. }
    • 生产者代码,生产者直接发送消息给交换机。
    1. import org.slf4j.Logger;
    2. import org.slf4j.LoggerFactory;
    3. import org.springframework.amqp.rabbit.core.RabbitTemplate;
    4. import org.springframework.beans.factory.annotation.Autowired;
    5. import org.springframework.web.bind.annotation.RequestMapping;
    6. import org.springframework.web.bind.annotation.RestController;
    7. /**
    8. * @author: gjm
    9. * @date: 2021/9/05 10:14
    10. * @description: 生产者端
    11. */
    12. @RestController
    13. @RequestMapping("/producer")
    14. public class ProducerController {
    15. private Logger logger = LoggerFactory.getLogger(ProducerController.class);
    16. @Autowired
    17. private RabbitTemplate rabbitTemplate;
    18. @RequestMapping("/fanout")
    19. public String sendFanoutMessage(){
    20. String message = "fanout mode message";
    21. rabbitTemplate.convertAndSend("fanout_exchange", "", message);
    22. logger.info("广播模式的生产者发送了消息:{}", message);
    23. return "success";
    24. }
    25. }
    •  消费者代码,消费者端使用@RabbitListener(queues = "queueName")直接监听队列就行,这里无需再声明和创建队列,配置类中已经声明。
    1. import com.rabbitmq.client.Channel;
    2. import org.slf4j.Logger;
    3. import org.slf4j.LoggerFactory;
    4. import org.springframework.amqp.core.Message;
    5. import org.springframework.amqp.rabbit.annotation.RabbitListener;
    6. import org.springframework.stereotype.Component;
    7. import java.io.IOException;
    8. /**
    9. * @author: gjm
    10. * @date: 2021/9/05 9:15
    11. * @description: 发布订阅模式的消费者
    12. */
    13. @Component
    14. public class FanoutConsumer {
    15. private Logger logger = LoggerFactory.getLogger(FanoutConsumer.class);
    16. @RabbitListener(queues = "fanout_queue1")
    17. public void consumer1(String body, Message message, Channel channel) {
    18. logger.info("广播模式的消费者1接收了消息:{}", body);
    19. try {
    20. // 消费者手动确认消息已消费
    21. channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    22. } catch (IOException e) {
    23. e.printStackTrace();
    24. }
    25. }
    26. @RabbitListener(queues = "fanout_queue2")
    27. public void consumer2(String body, Message message, Channel channel){
    28. logger.info("广播模式的消费者2接收了消息:{}", body);
    29. try {
    30. // 消费者手动确认消息已消费
    31. channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    32. } catch (IOException e) {
    33. e.printStackTrace();
    34. }
    35. }
    36. }

     5.4 路由模式

    • 使用direct类型的交换机通过routingKey和队列进行绑定(Binding) 
    1. import org.springframework.amqp.core.*;
    2. import org.springframework.context.annotation.Bean;
    3. import org.springframework.context.annotation.Configuration;
    4. /**
    5. * @author: gjm
    6. * @date: 2021/9/05 8:16
    7. * @description: 路由模式的配置类
    8. */
    9. @Configuration
    10. public class DirectModeConfig {
    11. // 交换机名称
    12. public static final String DIRECT_EXCHANGE_NAME = "direct_exchange";
    13. // 队列名称
    14. public static final String DIRECT_QUEUE_NAME = "direct_queue";
    15. // 创建direct类型的交换机
    16. @Bean
    17. public DirectExchange directExchange(){
    18. return new DirectExchange(DIRECT_EXCHANGE_NAME);
    19. }
    20. // 声明队列
    21. @Bean
    22. public Queue directQueue(){
    23. return QueueBuilder.durable(DIRECT_QUEUE_NAME).build();
    24. }
    25. // 队列directQueue和交换机使用routingKey绑定
    26. @Bean
    27. public Binding queueBindingExchange(Queue directQueue, DirectExchange directExchange){
    28. return BindingBuilder.bind(directQueue).to(directExchange).with("route.test");
    29. }
    30. }
    • 生产者代码,生产者发送消息给交换机时指定routingKey。
    1. import org.slf4j.Logger;
    2. import org.slf4j.LoggerFactory;
    3. import org.springframework.amqp.rabbit.core.RabbitTemplate;
    4. import org.springframework.beans.factory.annotation.Autowired;
    5. import org.springframework.web.bind.annotation.GetMapping;
    6. import org.springframework.web.bind.annotation.RequestMapping;
    7. import org.springframework.web.bind.annotation.RestController;
    8. /**
    9. * @author: gjm
    10. * @date: 2021/9/05 19:14
    11. * @description: TODO
    12. */
    13. @RestController
    14. @RequestMapping("/producer")
    15. public class ProducerController {
    16. private Logger logger = LoggerFactory.getLogger(ProducerController.class);
    17. @Autowired
    18. private RabbitTemplate rabbitTemplate;
    19. @GetMapping("/routing")
    20. public String sendRoutingMessage(){
    21. String message = "routing mode message";
    22. rabbitTemplate.convertAndSend("direct_exchange","route.test", message);
    23. logger.info("路由模式的生产者发送了消息:{}", message);
    24. return "success";
    25. }
    26. }
    • 消费者代码
    1. import com.rabbitmq.client.Channel;
    2. import org.slf4j.Logger;
    3. import org.slf4j.LoggerFactory;
    4. import org.springframework.amqp.core.Message;
    5. import org.springframework.amqp.rabbit.annotation.RabbitListener;
    6. import org.springframework.stereotype.Component;
    7. import java.io.IOException;
    8. /**
    9. * @author: gjm
    10. * @date: 2021/9/05 21:15
    11. * @description: 路由模式的消费者
    12. */
    13. @Component
    14. public class DirectConsumer {
    15. private Logger logger = LoggerFactory.getLogger(DirectConsumer.class);
    16. @RabbitListener(queues = "direct_queue")
    17. public void consumer(String body, Message message, Channel channel) {
    18. logger.info("路由模式的消费者接收了消息:{}", body);
    19. try {
    20. // 消费者手动确认消息已消费
    21. channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    22. } catch (IOException e) {
    23. e.printStackTrace();
    24. }
    25. }
    26. }

    5.5 主题模式

    • 使用topic类型的交换机通过routingKey和队列进行绑定(Binding) 
    1. import org.springframework.amqp.core.*;
    2. import org.springframework.context.annotation.Bean;
    3. import org.springframework.context.annotation.Configuration;
    4. /**
    5. * @author: gjm
    6. * @date: 2021/9/05 8:16
    7. * @description: 主题模式的配置类
    8. */
    9. @Configuration
    10. public class TopicModeConfig {
    11. // 交换机名称
    12. public static final String TOPIC_EXCHANGE_NAME = "topic_exchange";
    13. // 队列名称
    14. public static final String TOPIC_QUEUE_NAME = "topic_queue";
    15. // 创建topic类型的交换机
    16. @Bean
    17. public TopicExchange topicExchange(){
    18. return new TopicExchange(TOPIC_EXCHANGE_NAME);
    19. }
    20. // 声明队列
    21. @Bean
    22. public Queue topicQueue(){
    23. return QueueBuilder.durable(TOPIC_QUEUE_NAME).build();
    24. }
    25. // 队列topicQueue和交换机使用routingKey绑定
    26. @Bean
    27. public Binding topicQueueBindingExchange(Queue topicQueue, TopicExchange topicExchange){
    28. return BindingBuilder.bind(topicQueue).to(topicExchange).with("topic.*");
    29. }
    30. }
    • 生产者代码,生产者发送消息给交换机时指定routingKey 。
    1. import org.slf4j.Logger;
    2. import org.slf4j.LoggerFactory;
    3. import org.springframework.amqp.rabbit.core.RabbitTemplate;
    4. import org.springframework.beans.factory.annotation.Autowired;
    5. import org.springframework.web.bind.annotation.GetMapping;
    6. import org.springframework.web.bind.annotation.RequestMapping;
    7. import org.springframework.web.bind.annotation.RestController;
    8. /**
    9. * @author: gjm
    10. * @date: 2021/9/05 19:14
    11. * @description: 主题模式的生产者
    12. */
    13. @RestController
    14. @RequestMapping("/producer")
    15. public class ProducerController {
    16. private Logger logger = LoggerFactory.getLogger(ProducerController.class);
    17. @Autowired
    18. private RabbitTemplate rabbitTemplate;
    19. @RequestMapping("/topic")
    20. public String sendTopicMessage(){
    21. String message = "topic mode message";
    22. rabbitTemplate.convertAndSend("topic_exchange","topic.test", message);
    23. logger.info("主题模式的生产者发送了消息:{}", message);
    24. return "success";
    25. }
    26. }
    • 消费者代码,消费者端直接监听队列
    1. import com.rabbitmq.client.Channel;
    2. import org.slf4j.Logger;
    3. import org.slf4j.LoggerFactory;
    4. import org.springframework.amqp.core.Message;
    5. import org.springframework.amqp.rabbit.annotation.RabbitListener;
    6. import org.springframework.stereotype.Component;
    7. import java.io.IOException;
    8. /**
    9. * @author: gjm
    10. * @date: 2021/9/05 19:15
    11. * @description: 主题模式的消费者
    12. */
    13. @Component
    14. public class TopicConsumer {
    15. private Logger logger = LoggerFactory.getLogger(TopicConsumer.class);
    16. @RabbitListener(queues = "topic_queue")
    17. public void consumer(String body, Message message, Channel channel) {
    18. logger.info("主题模式的消费者接收了消息:{}", body);
    19. try {
    20. // 消费者手动确认消息已消费
    21. channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    22. } catch (IOException e) {
    23. e.printStackTrace();
    24. }
    25. }
    26. }

     5.6 发布确认 

    • 配置文件中配置:spring.rabbitmq.publisher-confirm-type: correlated;默认值为none,禁用发布确认模式;还可以设置为simple。
    1. spring:
    2. rabbitmq:
    3. publisher-confirm-type: correlated # 消息发送给交换机时会触发回调
    4. publisher-returns: true # 交换机无法路由到队列的消息会触发回调变成回退消息
    • 实现交换机确认的回调接口RabbitTemplate.ConfirmCallback

      1. import org.slf4j.Logger;
      2. import org.slf4j.LoggerFactory;
      3. import org.springframework.amqp.rabbit.connection.CorrelationData;
      4. import org.springframework.amqp.rabbit.core.RabbitTemplate;
      5. import org.springframework.beans.factory.annotation.Autowired;
      6. import org.springframework.stereotype.Component;
      7. import javax.annotation.PostConstruct;
      8. /**
      9. * @author: gjm
      10. * @date: 2021/9/05 20:09
      11. * @description: 消息发送到交换机的确认回调实现
      12. */
      13. @Component
      14. public class MyConfirmCallback implements RabbitTemplate.ConfirmCallback {
      15. private Logger logger = LoggerFactory.getLogger(MyConfirmCallback.class);
      16. @Autowired
      17. private RabbitTemplate rabbitTemplate;
      18. @PostConstruct
      19. public void init(){
      20. rabbitTemplate.setConfirmCallback(this);
      21. }
      22. @Override
      23. public void confirm(CorrelationData correlationData, boolean ack, String cause) {
      24. String id = correlationData.getId();
      25. if(ack) {
      26. logger.info("交换机确认收到id:{}的消息", id);
      27. }else {
      28. // 这里需要对发送失败id的消息做消息处理,后续做消息补偿,应保证消息可通过id找回
      29. logger.info("交换机未收到id:{}的消息, 原因是:{}", id, cause);
      30. }
      31. }
      32. }
    • 发布确认模式的配置类
    1. import org.springframework.amqp.core.*;
    2. import org.springframework.context.annotation.Bean;
    3. import org.springframework.context.annotation.Configuration;
    4. /**
    5. * @author: gjm
    6. * @date: 2021/9/05 20:17
    7. * @description: 发布确认模式配置类
    8. */
    9. @Configuration
    10. public class PublisherConfirmConfig {
    11. // 交换机名称
    12. public static final String PUBLISHER_CONFIRM_EXCHANGE = "publisher_confirm_exchange";
    13. // 队列的名称
    14. public static final String PUBLISHER_CONFIRM_QUEUE = "publisher_confirm_queue";
    15. // 路由键的值
    16. public static final String CONFIRM_ROUTING_KEY = "confirm.routing.key";
    17. // 创建direct类型的交换机
    18. @Bean
    19. public DirectExchange confirmExchange(){
    20. return new DirectExchange(PUBLISHER_CONFIRM_EXCHANGE);
    21. }
    22. // 创建队列
    23. @Bean
    24. public Queue confirmQueue(){
    25. return QueueBuilder.durable(PUBLISHER_CONFIRM_QUEUE).build();
    26. }
    27. // 队列confirmQueue和交换机通过routingKey绑定
    28. @Bean
    29. public Binding confirmQueueBindingExchange(Queue confirmQueue, DirectExchange confirmExchange){
    30. return BindingBuilder.bind(confirmQueue).to(confirmExchange).with(CONFIRM_ROUTING_KEY);
    31. }
    32. }
    • 发布确认的生产者代码
    1. import com.mj.rabbitmq.config.PublisherConfirmConfig;
    2. import org.slf4j.Logger;
    3. import org.slf4j.LoggerFactory;
    4. import org.springframework.amqp.rabbit.connection.CorrelationData;
    5. import org.springframework.amqp.rabbit.core.RabbitTemplate;
    6. import org.springframework.beans.factory.annotation.Autowired;
    7. import org.springframework.web.bind.annotation.GetMapping;
    8. import org.springframework.web.bind.annotation.PathVariable;
    9. import org.springframework.web.bind.annotation.RequestMapping;
    10. import org.springframework.web.bind.annotation.RestController;
    11. import java.util.UUID;
    12. /**
    13. * @author: gjm
    14. * @date: 202/9/05 20:35
    15. * @description: 发布确认模式发送消息的生产者
    16. */
    17. @RestController
    18. @RequestMapping("/confirm")
    19. public class PublisherConfirmController {
    20. private Logger logger = LoggerFactory.getLogger(PublisherConfirmController.class);
    21. @Autowired
    22. private RabbitTemplate rabbitTemplate;
    23. @GetMapping("/sendMsg/{confirmMsg}")
    24. public void sendConfirmMessage(@PathVariable("confirmMsg")String confirmMsg) {
    25. // 生成消息id,为了消息不丢失,应该保存消息到数据库
    26. String msgId = UUID.randomUUID().toString();
    27. // 生成消息的唯一标识信息
    28. CorrelationData correlationData = new CorrelationData(msgId);
    29. rabbitTemplate.convertAndSend(PublisherConfirmConfig.PUBLISHER_CONFIRM_EXCHANGE,
    30. PublisherConfirmConfig.CONFIRM_ROUTING_KEY, confirmMsg, correlationData);
    31. logger.info("发布确认的生产者发送消息:{}", confirmMsg);
    32. }
    33. }
    •  发布确认的消费者代码
    1. import com.mj.rabbitmq.config.PublisherConfirmConfig;
    2. import com.rabbitmq.client.Channel;
    3. import org.slf4j.Logger;
    4. import org.slf4j.LoggerFactory;
    5. import org.springframework.amqp.core.Message;
    6. import org.springframework.amqp.rabbit.annotation.RabbitHandler;
    7. import org.springframework.amqp.rabbit.annotation.RabbitListener;
    8. import org.springframework.stereotype.Component;
    9. import java.io.IOException;
    10. /**
    11. * @author: gjm
    12. * @date: 2021/9/05 12:41
    13. * @description: 发布确认模式发送消息的消费者
    14. */
    15. @Component
    16. @RabbitListener(queues = PublisherConfirmConfig.PUBLISHER_CONFIRM_QUEUE)
    17. public class PublisherConfirmConsumer {
    18. private Logger logger = LoggerFactory.getLogger(PublisherConfirmConsumer.class);
    19. @RabbitHandler
    20. public void receive(String msg, Message message, Channel channel){
    21. logger.info("发布确认的消费者收到了消息:{}", msg);
    22. try {
    23. // 消费者手动确认消息已消费
    24. channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
    25. } catch (IOException e) {
    26. e.printStackTrace();
    27. }
    28. }
    29. }
    • 查看消息发送给交换机后的确认回调结果

    • 实现交换机无法路由到队列的消息进行回调的接口RabbitTemplate.ReturnCallback 
    1. import org.slf4j.Logger;
    2. import org.slf4j.LoggerFactory;
    3. import org.springframework.amqp.core.Message;
    4. import org.springframework.amqp.rabbit.core.RabbitTemplate;
    5. import org.springframework.beans.factory.annotation.Autowired;
    6. import org.springframework.stereotype.Component;
    7. import javax.annotation.PostConstruct;
    8. /**
    9. * @author: gjm
    10. * @date: 2021/09/05 21:02
    11. * @description: 消息发送到交换机的确认回调实现
    12. */
    13. @Component
    14. public class MyReturnCallback implements RabbitTemplate.ReturnCallback {
    15. private Logger logger = LoggerFactory.getLogger(MyReturnCallback.class);
    16. @Autowired
    17. private RabbitTemplate rabbitTemplate;
    18. @PostConstruct
    19. public void init() {
    20. rabbitTemplate.setReturnCallback(this);
    21. }
    22. @Override
    23. public void returnedMessage(Message message, int replyCode, String replyText,
    24. String exchange, String routingKey) {
    25. logger.info("replyCode:{} -- replyText:{} -- exchange:{} -- routingKey:{}",
    26. replyCode, replyText, exchange, routingKey);
    27. logger.info("交换机无法路由到队列的消息:{}", new String(message.getBody()));
    28. }
    29. }
    •  产生回退消息的生产者代码
    1. import com.mj.rabbitmq.config.PublisherConfirmConfig;
    2. import org.slf4j.Logger;
    3. import org.slf4j.LoggerFactory;
    4. import org.springframework.amqp.rabbit.connection.CorrelationData;
    5. import org.springframework.amqp.rabbit.core.RabbitTemplate;
    6. import org.springframework.beans.factory.annotation.Autowired;
    7. import org.springframework.web.bind.annotation.GetMapping;
    8. import org.springframework.web.bind.annotation.PathVariable;
    9. import org.springframework.web.bind.annotation.RequestMapping;
    10. import org.springframework.web.bind.annotation.RestController;
    11. import java.util.UUID;
    12. /**
    13. * @author: gjm
    14. * @date: 2021/9/05 21:05
    15. * @description: 发布确认发送消息的生产者
    16. */
    17. @RestController
    18. @RequestMapping("/confirm")
    19. public class PublisherConfirmController {
    20. private Logger logger = LoggerFactory.getLogger(PublisherConfirmController.class);
    21. @Autowired
    22. private RabbitTemplate rabbitTemplate;
    23. @GetMapping("/sendReturnMsg/{returnMsg}")
    24. public void sendReturnMessage(@PathVariable("returnMsg")String returnMsg) {
    25. // 生成消息id,为了消息不丢失,应该保存消息到数据库
    26. String msgId = UUID.randomUUID().toString();
    27. // 生成消息的唯一标识信息
    28. CorrelationData correlationData = new CorrelationData(msgId);
    29. rabbitTemplate.convertAndSend(PublisherConfirmConfig.PUBLISHER_CONFIRM_EXCHANGE,
    30. "return_routing_key", returnMsg, correlationData);
    31. logger.info("发布确认的生产者发送消息:{}", returnMsg);
    32. }
    33. }
    • 生产者发送消息后查看结果,交换机可以接收到消息,队列无法接收到消息 ,从回调函数中的打印结果中我们知道消息无法路由的原因是routingKey不存在,消息变成回退消息。

  • 相关阅读:
    Leetcode 349.两个数组的交集
    MySQL的全局锁和表级锁
    HTML - input type=file 允许用户选择多个文件
    Kafka的docker安装
    Linux实用操作-----软件的安装
    电商商品详情 API(商品主图、sku)
    《智能风控实践指南》笔记(二)
    1796. 字符串中第二大的数字
    【每日练习】删除公共字符
    APP信息侦察&夜神模拟器Burp抓包配置
  • 原文地址:https://blog.csdn.net/G_12_M/article/details/127635172