Rabbitmq详解

一、消息中间件概述

1、MQ概述

MQ全称 Message Queue(消息队列),是在消息的传输过程中保存消息的容器。多用于分布式系统之间进行通信。

应用之间的远程调用

image-20211201094908668

加入MQ后应用之间的调用

image-20211201094938207

2、MQ的优势

①应用解耦

MQ相当于一个中介,生产方通过MQ与消费方交互,它将应用程序进行解耦合。

系统的耦合性越高,容错性就越低,可维护性就越低。

image-20211201095031486

使用 MQ 使得应用间解耦,提升容错性和可维护性。

image-20211201095048208

②任务异步处理

将不需要同步处理的并且耗时长的操作由消息队列通知消息接收方进行异步处理。提高了应用程序的响 应时间。

image-20211201095118343

一个下单操作耗时:20 + 300 + 300 + 300 = 920m

用户点击完下单按钮后,需要等待920ms才能得到下单响应,太慢!

image-20211201095152014

用户点击完下单按钮后,只需等待25ms就能得到下单响应 (20 + 5 = 25ms)。

提升用户体验和系统吞吐量(单位时间内处理请求的数目)。

③削峰填谷

如订单系统,在下单的时候就会往数据库写数据。但是数据库只能支撑每秒1000左右的并发写入,并发 量再高就容易宕机。低峰期的时候并发也就100多个,但是在高峰期时候,并发量会突然激增到5000以 上,这个时候数据库肯定卡死了。

image-20211201095249126

消息被MQ保存起来了,然后系统就可以按照自己的消费能力来消费,比如每秒1000个消息,这样慢慢 写入数据库,这样就不会卡死数据库了。

image-20211201095312031

但是使用了MQ之后,限制消费消息的速度为1000,但是这样一来,高峰期产生的数据势必会被积压在 MQ中,高峰就被“削”掉了。但是因为消息积压,在高峰期过后的一段时间内,消费消息的速度还是会 维持在1000QPS,直到消费完积压的消息,这就叫做“填谷”

image-20211201095334497

3、MQ的劣势

①系统可用性降低

系统引入的外部依赖越多,系统稳定性越差。一旦 MQ 宕机,就会对业务造成影响。如何保证MQ的高 可用?

②系统复杂度提高

MQ 的加入大大增加了系统的复杂度,以前系统间是同步的远程调用,现在是通过 MQ 进行异步调用。 如何保证消息没有被重复消费?怎么处理消息丢失情况?那么保证消息传递的顺序性?

③一致性问题

A 系统处理完业务,通过 MQ 给B、C、D三个系统发消息,如果 B 系统、C 系统处理成功,D 系统处理 失败。如何保证消息数据处理的一致性?

4、常见的 MQ 产品

目前业界有很多的 MQ 产品,例如 RabbitMQ、RocketMQ、ActiveMQ、Kafka、ZeroMQ、MetaMq 等,也有直接使用 Redis 充当消息队列的案例,而这些消息队列产品,各有侧重,在实际选型时,需要 结合自身需求及 MQ 产品特征,综合考虑。

image-20211201095509122

由于 RabbitMQ 综合能力强劲,所以接下来的课程中,我们将主要学习 RabbitMQ。

5、AMQP 和 JMS

实现MQ的大致有两种主流方式:AMQP、JMS。

①AMQP

AMQP,即 Advanced Message Queuing Protocol(高级消息队列协议),是一个网络协议,是应用 层协议的一个开放标准,为面向消息的中间件设计。基于此协议的客户端与消息中间件可传递消息,遵 循此协议,不受客户端和中间件产品和开发语言限制。2006年,AMQP 规范发布。类比HTTP。

image-20211201095559623

②JMS

JMS 即 Java 消息服务(JavaMessage Service)应用程序接口,是一个 Java 平台中关于面向消息中间 件的API

JMS 是 JavaEE 规范中的一种,类比JDBC

很多消息中间件都实现了JMS规范,例如:ActiveMQ。RabbitMQ 官方没有提供 JMS 的实现包,但是 开源社区有

③AMQP 与 JMS 区别

  • JMS是定义了统一的接口,来对消息操作进行统一;AMQP是通过规定协议来统一数据交互的格式

  • JMS限定了必须使用Java语言;AMQP只是协议,不规定实现方式,因此是跨语言的。

  • JMS规定了两种消息模式;而AMQP的消息模式更加丰富

6、RabbitMQ

RabbitMQ官方地址:http://www.rabbitmq.com/

2007年,Rabbit 技术公司基于 AMQP 标准开发的 RabbitMQ 1.0 发布。RabbitMQ 采用 Erlang 语言开 发。Erlang 语言专门为开发高并发和分布式系统的一种语言,在电信领域使用广泛。

RabbitMQ 基础架构如下图:

image-20211201095728646

RabbitMQ 中的相关概念:

  • Broker:接收和分发消息的应用,RabbitMQ Server就是 Message Broker

  • Virtual host:出于多租户和安全因素设计的,把 AMQP 的基本组件划分到一个虚拟的分组中,类似于网络中的 namespace 概念。当多个不同的用户使用同一个 RabbitMQ server 提供的服务时,可以划分出多个vhost,每个用户在自己的 vhost 创建 exchange/queue 等

  • Connection:publisher/consumer 和 broker 之间的 TCP 连接

  • Channel:如果每一次访问 RabbitMQ 都建立一个 Connection,在消息量大的时候建立 TCPConnection的开销将是巨大的,效率也较低。Channel 是在 connection 内部建立的逻辑连接,如果应用程序支持多线程,通常每个thread创建单独的 channel 进行通讯,AMQP method 包含了channel id 帮助客户端和message broker 识别 channel,所以 channel 之间是完全隔离的。Channel 作为轻量级的 Connection 极大减少了操作系统建立 TCP connection 的开销

  • Exchange:message 到达 broker 的第一站,根据分发规则,匹配查询表中的 routing key,分发消息到queue 中去。常用的类型有:direct (point-to-point), topic (publish-subscribe) andfanout (multicast)

  • Queue:消息最终被送到这里等待 consumer 取走

  • Binding:exchange 和 queue 之间的虚拟连接,binding 中可以包含 routing key。Binding 信息被保存到 exchange 中的查询表中,用于 message 的分发依据

RabbitMQ提供了6种模式:简单模式,work模式,Publish/Subscribe发布与订阅模式,Routing路由 模式,Topics主题模式,RPC远程调用模式(远程调用,不太算MQ;暂不作介绍);

官网对应模式介绍:https://www.rabbitmq.com/getstarted.html

image-20211201100031768

二、安装及配置RabbitMQ

详细查看 资料/软件/安装RabbitMQ.md 文档。

三、RabbitMQ入门

简单模式

image-20211201100118486

在上图的模型中,有以下概念:

  • P:生产者,也就是要发送消息的程序

  • C:消费者:消息的接收者,会一直等待消息到来

  • queue:消息队列,图中红色部分。类似一个邮箱,可以缓存消息;生产者向其中投递消息,消费者从其中取出消息

1、搭建示例工程

①创建工程

image-20211201100206367

②添加依赖

往lxs-rabbitmq的pom.xml文件中添加如下依赖:

<dependency>
   <groupId>com.rabbitmq</groupId>
   <artifactId>amqp-client</artifactId>
   <version>5.6.0</version>
</dependency>

2、编写生产者

编写消息生产者com.lxs.rabbitmq.simple.Producer

package com.lxs.rabbitmq.simple;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
public class Producer {
   static final String QUEUE_NAME = "simple_queue";
   public static void main(String[] args) throws Exception {
       //创建连接工厂
       ConnectionFactory connectionFactory = new ConnectionFactory();
       //主机地址;默认为 localhost
       connectionFactory.setHost("192.168.88.128");
       //连接端口;默认为 5672
       connectionFactory.setPort(5672);
       //虚拟主机名称;默认为 /
       connectionFactory.setVirtualHost("/msk");
       //连接用户名;默认为guest
       connectionFactory.setUsername("msk");
       //连接密码;默认为guest
       connectionFactory.setPassword("123456");
       //创建连接
       Connection connection = connectionFactory.newConnection();
       // 创建频道
       Channel channel = connection.createChannel();
       // 声明(创建)队列
       /**
        * 参数1:队列名称
        * 参数2:是否定义持久化队列
        * 参数3:是否独占本次连接
        * 参数4:是否在不使用的时候自动删除队列
        * 参数5:队列其它参数
        */
       channel.queueDeclare(QUEUE_NAME, true, false, false, null);
       // 要发送的信息
       String message = "你好;小兔子!";
       /**
        * 参数1:交换机名称,如果没有指定则使用默认Default Exchage
        * 参数2:路由key,简单模式可以传递队列名称
        * 参数3:消息其它属性
        * 参数4:消息内容
        */
       channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
       System.out.println("已发送消息:" + message);
       // 关闭资源
       channel.close();
       connection.close();
  }
}

在执行上述的消息发送之后;使用msk账号登录rabbitMQ的管理控制台,可以发现队列和其消息:

image-20211201164235117

image-20211201164247750

3、编写消费者

抽取创建connection的工具类com.lxs.rabbitmq.util.ConnectionUtil;

package com.lxs.rabbitmq.util;

import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
public class ConnectionUtil {
   public static Connection getConnection() throws Exception {
       //创建连接工厂
       ConnectionFactory connectionFactory = new ConnectionFactory();
       //主机地址;默认为 localhost
       connectionFactory.setHost("192.168.88.128");
       //连接端口;默认为 5672
       connectionFactory.setPort(5672);
       //虚拟主机名称;默认为 /
       connectionFactory.setVirtualHost("/msk");
       //连接用户名;默认为guest
       connectionFactory.setUsername("msk");
       //连接密码;默认为guest
       connectionFactory.setPassword("123456");
       //创建连接
       return connectionFactory.newConnection();
  }
}

编写消息的消费者com.lxs.rabbitmq.simple.Consumer

package com.lxs.rabbitmq.simple;

import com.lxs.rabbitmq.util.ConnectionUtil;
import com.rabbitmq.client.*;

import java.io.IOException;

public class Consumer {
   public static void main(String[] args) throws Exception {
       Connection connection = ConnectionUtil.getConnection();
       // 创建频道
       Channel channel = connection.createChannel();
       // 声明(创建)队列
       /**
        * 参数1:队列名称
        * 参数2:是否定义持久化队列
        * 参数3:是否独占本次连接
        * 参数4:是否在不使用的时候自动删除队列
        * 参数5:队列其它参数
        */
       channel.queueDeclare(Producer.QUEUE_NAME, true, false, false, null);
       //创建消费者;并设置消息处理
       DefaultConsumer consumer = new DefaultConsumer(channel) {
           @Override
       /**
        * consumerTag 消息者标签,在channel.basicConsume时候可以指定
        * envelope 消息包的内容,可从中获取消息id,消息routingkey,交换机,消息和重传标志(收到消息失败后是否需要重新发送)
        * properties 属性信息
        * body 消息
        */
           public void handleDelivery(String consumerTag, Envelope envelope,AMQP.BasicProperties properties, byte[] body) throws IOException {
               //路由key
               System.out.println("路由key为:" + envelope.getRoutingKey());
               //交换机
               System.out.println("交换机为:" + envelope.getExchange());
               //消息id
               System.out.println("消息id为:" + envelope.getDeliveryTag());
               //收到的消息
               System.out.println("接收到的消息为:" + new String(body, "utf-8"));
          }
      };
       //监听消息
       /**
        * 参数1:队列名称
        * 参数2:是否自动确认,设置为true为表示消息接收到自动向mq回复接收到了,mq接收到回复
        会删除消息,设置为false则需要手动确认
        * 参数3:消息接收到后回调
        */
       channel.basicConsume(Producer.QUEUE_NAME, true, consumer);
       //不关闭资源,应该一直监听消息
       //channel.close();
       //connection.close();
  }
}

4、小结

上述的入门案例中中其实使用的是如下的简单模式:

image-20211201164941666

在上图的模型中,有以下概念: P:生产者,也就是要发送消息的程序 C:消费者:消息的接受者,会一直等待消息到来。 queue:消息队列,图中红色部分。类似一个邮箱,可以缓存消息;生产者向其中投递消息,消费者从其中取出消息。

四、RabbitMQ工作模式

1、Work queues工作队列模式

①模式说明

image-20211201170556411

Work Queues 与入门程序的 简单模式 相比,多了一个或一些消费端,多个消费端共同消费同一个队列 中的消息。

应用场景:对于 任务过重或任务较多情况使用工作队列可以提高任务处理的速度。

②代码

Work Queues 与入门程序的 简单模式 的代码是几乎一样的;可以完全复制,并复制多一个消费者进行 多个消费者同时消费消息的测试。

1)生产者

package com.lxs.rabbitmq.work;

import com.lxs.rabbitmq.util.ConnectionUtil;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
public class Producer {
   static final String QUEUE_NAME = "work_queue";
   public static void main(String[] args) throws Exception {
       //创建连接
       Connection connection = ConnectionUtil.getConnection();
       // 创建频道
       Channel channel = connection.createChannel();
       // 声明(创建)队列
       /**
        * 参数1:队列名称
        * 参数2:是否定义持久化队列
        * 参数3:是否独占本次连接
        * 参数4:是否在不使用的时候自动删除队列
        * 参数5:队列其它参数
        */
       channel.queueDeclare(QUEUE_NAME, true, false, false, null);
       for (int i = 1; i <= 30; i++) {
           // 发送信息
           String message = "你好;小兔子!work模式--" + i;
           /**
            * 参数1:交换机名称,如果没有指定则使用默认Default Exchage
            * 参数2:路由key,简单模式可以传递队列名称
            * 参数3:消息其它属性
            * 参数4:消息内容
            */
           channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
           System.out.println("已发送消息:" + message);
      }
       // 关闭资源
       channel.close();
       connection.close();
  }
}

2)消费者1

package com.lxs.rabbitmq.work;

import com.lxs.rabbitmq.util.ConnectionUtil;
import com.rabbitmq.client.*;
import java.io.IOException;
public class Consumer1 {
   public static void main(String[] args) throws Exception {
       Connection connection = ConnectionUtil.getConnection();
       // 创建频道
       final Channel channel = connection.createChannel();
       // 声明(创建)队列
       /**
        * 参数1:队列名称
        * 参数2:是否定义持久化队列
        * 参数3:是否独占本次连接
        * 参数4:是否在不使用的时候自动删除队列
        * 参数5:队列其它参数
        */
       channel.queueDeclare(Producer.QUEUE_NAME, true, false, false, null);
       //一次只能接收并处理一个消息
       channel.basicQos(1);
       //创建消费者;并设置消息处理
       DefaultConsumer consumer = new DefaultConsumer(channel){
           @Override
           /**
            * consumerTag 消息者标签,在channel.basicConsume时候可以指定
            * envelope 消息包的内容,可从中获取消息id,消息routingkey,交换机,消息和重
            传标志(收到消息失败后是否需要重新发送)
            * properties 属性信息
            * body 消息
            */
           public void handleDelivery(String consumerTag, Envelope envelope,AMQP.BasicProperties properties, byte[] body) throws IOException {
               try {
                   //路由key
                   System.out.println("路由key为:" + envelope.getRoutingKey());
                   //交换机
                   System.out.println("交换机为:" + envelope.getExchange());
                   //消息id
                   System.out.println("消息id为:" + envelope.getDeliveryTag());
                   //收到的消息
                   System.out.println("消费者1-接收到的消息为:" + new String(body,"utf-8"));
                   Thread.sleep(1000);
                   //确认消息
                   channel.basicAck(envelope.getDeliveryTag(), false);
              } catch (InterruptedException e) {
                   e.printStackTrace();
              }
          }
      };
       //监听消息
       /**
        * 参数1:队列名称
        * 参数2:是否自动确认,设置为true为表示消息接收到自动向mq回复接收到了,mq接收到回复
        会删除消息,设置为false则需要手动确认
        * 参数3:消息接收到后回调
        */
       channel.basicConsume(Producer.QUEUE_NAME, false, consumer);
  }
}            

3)消费者2

package com.lxs.rabbitmq.work;

import com.lxs.rabbitmq.util.ConnectionUtil;
import com.rabbitmq.client.*;

import java.io.IOException;

public class Consumer2 {
   public static void main(String[] args) throws Exception {
       Connection connection = ConnectionUtil.getConnection();
       // 创建频道
       final Channel channel = connection.createChannel();
       // 声明(创建)队列
       /**
        * 参数1:队列名称
        * 参数2:是否定义持久化队列
        * 参数3:是否独占本次连接
        * 参数4:是否在不使用的时候自动删除队列
        * 参数5:队列其它参数
        */
       channel.queueDeclare(Producer.QUEUE_NAME, true, false, false, null);
       //一次只能接收并处理一个消息
       channel.basicQos(1);
       //创建消费者;并设置消息处理
       DefaultConsumer consumer = new DefaultConsumer(channel){
           @Override
           /**
            * consumerTag 消息者标签,在channel.basicConsume时候可以指定
            * envelope 消息包的内容,可从中获取消息id,消息routingkey,交换机,消息和重传标志(收到消息失败后是否需要重新发送)
            * properties 属性信息
            * body 消息
            */
           public void handleDelivery(String consumerTag, Envelope envelope,
                                      AMQP.BasicProperties properties, byte[] body) throws IOException {
               try {
                   //路由key
                   System.out.println("路由key为:" + envelope.getRoutingKey());
                   //交换机
                   System.out.println("交换机为:" + envelope.getExchange());
                   //消息id
                   System.out.println("消息id为:" + envelope.getDeliveryTag());
                   //收到的消息
                   System.out.println("消费者1-接收到的消息为:" + new String(body,"utf-8"));
                   Thread.sleep(1000);
                   //确认消息
                   channel.basicAck(envelope.getDeliveryTag(), false);
              } catch (InterruptedException e) {
                   e.printStackTrace();
              }
          }
      };
       //监听消息
       /**
        * 参数1:队列名称
        * 参数2:是否自动确认,设置为true为表示消息接收到自动向mq回复接收到了,mq接收到回复
        会删除消息,设置为false则需要手动确认
        * 参数3:消息接收到后回调
        */
       channel.basicConsume(Producer.QUEUE_NAME, false, consumer);
  }
}

③测试

启动两个消费者,然后再启动生产者发送消息;到IDEA的两个消费者对应的控制台查看是否竞争性的接 收到消息。

image-20211201171115769

image-20211201171127364

④小结

在一个队列中如果有多个消费者,那么消费者之间对于同一个消息的关系是竞争的关系。

2、订阅模式概述

订阅模式示例图:

image-20211201172313984

前面2个案例中,只有3个角色:

  • P:生产者,也就是要发送消息的程序

  • C:消费者:消息的接受者,会一直等待消息到来。

  • queue:消息队列,图中红色部分

而在订阅模型中,多了一个exchange角色,而且过程略有变化:

  • P:生产者,也就是要发送消息的程序,但是不再发送到队列中,而是发给X(交换机)

  • C:消费者,消息的接受者,会一直等待消息到来。

  • Queue:消息队列,接收消息、缓存消息。

  • Exchange:交换机,图中的X。一方面,接收生产者发送的消息。另一方面,知道如何处理消 息,例如递交给某个特别队列、递交给所有队列、或是将消息丢弃。到底如何操作,取决于 Exchange的类型。Exchange有常见以下3种类型:

    • Fanout:广播,将消息交给所有绑定到交换机的队列

    • Direct:定向,把消息交给符合指定routing key 的队列

    • Topic:通配符,把消息交给符合routing pattern(路由模式) 的队列

Exchange(交换机)只负责转发消息,不具备存储消息的能力,因此如果没有任何队列与Exchange绑 定,或者没有符合路由规则的队列,那么消息会丢失!

3、Publish/Subscribe发布与订阅模式

①模式说明

image-20211201172500743

发布订阅模式: 1、每个消费者监听自己的队列。 2、生产者将消息发给broker,由交换机将消息转发 到绑定此交换机的每个队列,每个绑定交换机的队列都将接收 到消息

②代码

1)生产者

package com.lxs.rabbitmq.ps;

import com.lxs.rabbitmq.util.ConnectionUtil;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
/**
* 发布与订阅使用的交换机类型为:fanout
*/
public class Producer {
   //交换机名称
   static final String FANOUT_EXCHAGE = "fanout_exchange";
   //队列名称
   static final String FANOUT_QUEUE_1 = "fanout_queue_1";
   //队列名称
   static final String FANOUT_QUEUE_2 = "fanout_queue_2";
   public static void main(String[] args) throws Exception {
       //创建连接
       Connection connection = ConnectionUtil.getConnection();
       // 创建频道
       Channel channel = connection.createChannel();
       /**
        * 声明交换机
        * 参数1:交换机名称
        * 参数2:交换机类型,fanout、topic、direct、headers
        */
       channel.exchangeDeclare(FANOUT_EXCHAGE, BuiltinExchangeType.FANOUT);
       // 声明(创建)队列
       /**
        * 参数1:队列名称
        * 参数2:是否定义持久化队列
        * 参数3:是否独占本次连接
        * 参数4:是否在不使用的时候自动删除队列
        * 参数5:队列其它参数
        */
       channel.queueDeclare(FANOUT_QUEUE_1, true, false, false, null);
       channel.queueDeclare(FANOUT_QUEUE_2, true, false, false, null);
       //队列绑定交换机
       channel.queueBind(FANOUT_QUEUE_1, FANOUT_EXCHAGE, "");
       channel.queueBind(FANOUT_QUEUE_2, FANOUT_EXCHAGE, "");
       for (int i = 1; i <= 10; i++) {
           // 发送信息
           String message = "你好;小兔子!发布订阅模式--" + i;
           /**
            * 参数1:交换机名称,如果没有指定则使用默认Default Exchage
            * 参数2:路由key,简单模式可以传递队列名称
            * 参数3:消息其它属性
            * 参数4:消息内容
            */
           channel.basicPublish(FANOUT_EXCHAGE, "", null, message.getBytes());
           System.out.println("已发送消息:" + message);
      }
       // 关闭资源
       channel.close();
       connection.close();
  }
}

2)消费者1

package com.lxs.rabbitmq.ps;

import com.lxs.rabbitmq.util.ConnectionUtil;
import com.rabbitmq.client.*;
import java.io.IOException;
public class Consumer1 {
    public static void main(String[] args) throws Exception {
        Connection connection = ConnectionUtil.getConnection();
        // 创建频道
        Channel channel = connection.createChannel();
        //声明交换机
        channel.exchangeDeclare(Producer.FANOUT_EXCHAGE,BuiltinExchangeType.FANOUT);
        // 声明(创建)队列
        /**
         * 参数1:队列名称
         * 参数2:是否定义持久化队列
         * 参数3:是否独占本次连接
         * 参数4:是否在不使用的时候自动删除队列
         * 参数5:队列其它参数
         */
        channel.queueDeclare(Producer.FANOUT_QUEUE_1, true, false, false, null);
        //队列绑定交换机
        channel.queueBind(Producer.FANOUT_QUEUE_1, Producer.FANOUT_EXCHAGE, "");
        //创建消费者;并设置消息处理
        DefaultConsumer consumer = new DefaultConsumer(channel){
            @Override
            /**
             * consumerTag 消息者标签,在channel.basicConsume时候可以指定
             * envelope 消息包的内容,可从中获取消息id,消息routingkey,交换机,消息和重
             传标志(收到消息失败后是否需要重新发送)
             * properties 属性信息
             * body 消息
             */
            public void handleDelivery(String consumerTag, Envelope envelope,AMQP.BasicProperties properties, byte[] body) throws IOException {
                //路由key
                System.out.println("路由key为:" + envelope.getRoutingKey());
                //交换机
                System.out.println("交换机为:" + envelope.getExchange());
                //消息id
                System.out.println("消息id为:" + envelope.getDeliveryTag());
                //收到的消息
                System.out.println("消费者1-接收到的消息为:" + new String(body,"utf-8"));
            }
        };
        //监听消息
        /**
         * 参数1:队列名称
         * 参数2:是否自动确认,设置为true为表示消息接收到自动向mq回复接收到了,mq接收到回复
         会删除消息,设置为false则需要手动确认
         * 参数3:消息接收到后回调
         */
        channel.basicConsume(Producer.FANOUT_QUEUE_1, true, consumer);
    }
}

3)消费者2

package com.lxs.rabbitmq.ps;

import com.lxs.rabbitmq.util.ConnectionUtil;
import com.rabbitmq.client.*;
import java.io.IOException;
public class Consumer2 {
   public static void main(String[] args) throws Exception {
       Connection connection = ConnectionUtil.getConnection();
       // 创建频道
       Channel channel = connection.createChannel();
       //声明交换机
       channel.exchangeDeclare(Producer.FANOUT_EXCHAGE,
               BuiltinExchangeType.FANOUT);
       // 声明(创建)队列
       /**
        * 参数1:队列名称
        * 参数2:是否定义持久化队列
        * 参数3:是否独占本次连接
        * 参数4:是否在不使用的时候自动删除队列
        * 参数5:队列其它参数
        */
       channel.queueDeclare(Producer.FANOUT_QUEUE_2, true, false, false, null);
       //队列绑定交换机
       channel.queueBind(Producer.FANOUT_QUEUE_2, Producer.FANOUT_EXCHAGE, "");
       //创建消费者;并设置消息处理
       DefaultConsumer consumer = new DefaultConsumer(channel){
           @Override
           /**
            * consumerTag 消息者标签,在channel.basicConsume时候可以指定
            * envelope 消息包的内容,可从中获取消息id,消息routingkey,交换机,消息和重
            传标志(收到消息失败后是否需要重新发送)
            * properties 属性信息
            * body 消息
            */
           public void handleDelivery(String consumerTag, Envelope envelope,
                                      AMQP.BasicProperties properties, byte[] body) throws IOException {
               //路由key
               System.out.println("路由key为:" + envelope.getRoutingKey());
               //交换机
               System.out.println("交换机为:" + envelope.getExchange());
               //消息id
               System.out.println("消息id为:" + envelope.getDeliveryTag());
               //收到的消息
               System.out.println("消费者2-接收到的消息为:" + new String(body,"utf-8"));
          }
      };
       //监听消息
       /**
        * 参数1:队列名称
        * 参数2:是否自动确认,设置为true为表示消息接收到自动向mq回复接收到了,mq接收到回复
        会删除消息,设置为false则需要手动确认
        * 参数3:消息接收到后回调
        */
       channel.basicConsume(Producer.FANOUT_QUEUE_2, true, consumer);
  }
}

③测试

启动所有消费者,然后使用生产者发送消息;在每个消费者对应的控制台可以查看到生产者发送的所有 消息;到达广播的效果。

在执行完测试代码后,其实到RabbitMQ的管理后台找到 Exchanges 选项卡,点击 fanout_exchange 的交换机,可以查看到如下的绑定:

image-20211201172930011

④小结

交换机需要与队列进行绑定,绑定之后;一个消息可以被多个消费者都收到。

发布订阅模式与工作队列模式的区别

1、工作队列模式不用定义交换机,而发布/订阅模式需要定义交换机。 2、发布/订阅模式的生产方是面向交换机发送消息,工作队列模式的生产方是面向队列发送消息(底层使 用默认交换机)。 3、发布/订阅模式需要设置队列和交换机的绑定,工作队列模式不需要设置,实际上工作队列模式会将 队列绑 定到默认的交换机 。

4、Routing路由模式

①模式说明

路由模式特点:

  • 队列与交换机的绑定,不能是任意绑定了,而是要指定一个 RoutingKey (路由key)

  • 消息的发送方在 向 Exchange发送消息时,也必须指定消息的 RoutingKey 。

  • Exchange不再把消息交给每一个绑定的队列,而是根据消息的 Routing Key 进行判断,只有队列的 Routingkey 与消息的 Routing key 完全一致,才会接收到消息

image-20211202111334736

图解:

  • P:生产者,向Exchange发送消息,发送消息时,会指定一个routing key。

  • X:Exchange(交换机),接收生产者的消息,然后把消息递交给 与routing key完全匹配的队列

  • C1:消费者,其所在队列指定了需要routing key 为 error 的消息

  • C2:消费者,其所在队列指定了需要routing key 为 info、error、warning 的消息

②代码

image-20211202111415328

在编码上与 Publish/Subscribe发布与订阅模式 的区别是交换机的类型为:Direct,还有队列绑定交换 机的时候需要指定routing key。

1)生产者

package com.lxs.rabbitmq.routing;

import com.lxs.rabbitmq.util.ConnectionUtil;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
/**
 * 路由模式的交换机类型为:direct
 */
public class Producer {
    //交换机名称
    static final String DIRECT_EXCHAGE = "direct_exchange";
    //队列名称
    static final String DIRECT_QUEUE_INSERT = "direct_queue_insert";
    //队列名称
    static final String DIRECT_QUEUE_UPDATE = "direct_queue_update";
    public static void main(String[] args) throws Exception {
        //创建连接
        Connection connection = ConnectionUtil.getConnection();
        // 创建频道
        Channel channel = connection.createChannel();
        /**
         * 声明交换机
         * 参数1:交换机名称
         * 参数2:交换机类型,fanout、topic、direct、headers
         */
        channel.exchangeDeclare(DIRECT_EXCHAGE, BuiltinExchangeType.DIRECT);
        // 声明(创建)队列
        /**
         * 参数1:队列名称
         * 参数2:是否定义持久化队列
         * 参数3:是否独占本次连接
         * 参数4:是否在不使用的时候自动删除队列
         * 参数5:队列其它参数
         */
        channel.queueDeclare(DIRECT_QUEUE_INSERT, true, false, false, null);
        channel.queueDeclare(DIRECT_QUEUE_UPDATE, true, false, false, null);
        //队列绑定交换机
        channel.queueBind(DIRECT_QUEUE_INSERT, DIRECT_EXCHAGE, "insert");
        channel.queueBind(DIRECT_QUEUE_UPDATE, DIRECT_EXCHAGE, "update");
        // 发送信息
        String message = "新增了商品。路由模式;routing key 为 insert " ;
        /**
         * 参数1:交换机名称,如果没有指定则使用默认Default Exchage
         * 参数2:路由key,简单模式可以传递队列名称
         * 参数3:消息其它属性
         * 参数4:消息内容
         */
        channel.basicPublish(DIRECT_EXCHAGE, "insert", null,message.getBytes());
        System.out.println("已发送消息:" + message);
        // 发送信息
        message = "修改了商品。路由模式;routing key 为 update" ;
        /**
         * 参数1:交换机名称,如果没有指定则使用默认Default Exchage
         * 参数2:路由key,简单模式可以传递队列名称
         * 参数3:消息其它属性
         * 参数4:消息内容
         */
        channel.basicPublish(DIRECT_EXCHAGE, "update", null,message.getBytes());
        System.out.println("已发送消息:" + message);
        // 关闭资源
        channel.close();
        connection.close();
    }
}

2)消费者1

package com.lxs.rabbitmq.routing;

import com.lxs.rabbitmq.util.ConnectionUtil;
import com.rabbitmq.client.*;

import java.io.IOException;

public class Consumer1 {
   public static void main(String[] args) throws Exception {
       Connection connection = ConnectionUtil.getConnection();
       // 创建频道
       Channel channel = connection.createChannel();
       //声明交换机
       channel.exchangeDeclare(Producer.DIRECT_EXCHAGE,BuiltinExchangeType.DIRECT);
       // 声明(创建)队列
       /**
        * 参数1:队列名称
        * 参数2:是否定义持久化队列
        * 参数3:是否独占本次连接
        * 参数4:是否在不使用的时候自动删除队列
        * 参数5:队列其它参数
        */
       channel.queueDeclare(Producer.DIRECT_QUEUE_INSERT, true, false, false,null);
       //队列绑定交换机
       channel.queueBind(Producer.DIRECT_QUEUE_INSERT, Producer.DIRECT_EXCHAGE,"insert");
       //创建消费者;并设置消息处理
       DefaultConsumer consumer = new DefaultConsumer(channel) {
           @Override
           /**
            * consumerTag 消息者标签,在channel.basicConsume时候可以指定
            * envelope 消息包的内容,可从中获取消息id,消息routingkey,交换机,消息和重
            传标志(收到消息失败后是否需要重新发送)
            * properties 属性信息
            * body 消息
            */
           public void handleDelivery(String consumerTag, Envelope envelope,
                                      AMQP.BasicProperties properties, byte[] body) throws IOException {
               //路由key
               System.out.println("路由key为:" + envelope.getRoutingKey());
               //交换机
               System.out.println("交换机为:" + envelope.getExchange());
               //消息id
               System.out.println("消息id为:" + envelope.getDeliveryTag());
               //收到的消息
               System.out.println("消费者1-接收到的消息为:" + new String(body,"utf-8"));
          }
      };
       //监听消息
       /**
        * 参数1:队列名称
        * 参数2:是否自动确认,设置为true为表示消息接收到自动向mq回复接收到了,mq接收到回复
        会删除消息,设置为false则需要手动确认
        * 参数3:消息接收到后回调
        */
       channel.basicConsume(Producer.DIRECT_QUEUE_INSERT, true, consumer);
  }
}

3)消费者2

package com.lxs.rabbitmq.routing;

import com.lxs.rabbitmq.util.ConnectionUtil;
import com.rabbitmq.client.*;

import java.io.IOException;

public class Consumer2 {
   public static void main(String[] args) throws Exception {
       Connection connection = ConnectionUtil.getConnection();
       // 创建频道
       Channel channel = connection.createChannel();
       //声明交换机
       channel.exchangeDeclare(Producer.DIRECT_EXCHAGE,
               BuiltinExchangeType.DIRECT);
       // 声明(创建)队列
       /**
        * 参数1:队列名称
        * 参数2:是否定义持久化队列
        * 参数3:是否独占本次连接
        * 参数4:是否在不使用的时候自动删除队列
        * 参数5:队列其它参数
        */
       channel.queueDeclare(Producer.DIRECT_QUEUE_UPDATE, true, false, false,
               null);
       //队列绑定交换机
       channel.queueBind(Producer.DIRECT_QUEUE_UPDATE, Producer.DIRECT_EXCHAGE,
               "update");
       //创建消费者;并设置消息处理
       DefaultConsumer consumer = new DefaultConsumer(channel) {
           @Override
           /**
            * consumerTag 消息者标签,在channel.basicConsume时候可以指定
            * envelope 消息包的内容,可从中获取消息id,消息routingkey,交换机,消息和重
            传标志(收到消息失败后是否需要重新发送)
            * properties 属性信息
            * body 消息
            */
           public void handleDelivery(String consumerTag, Envelope envelope,
                                      AMQP.BasicProperties properties, byte[] body) throws IOException {
               //路由key
               System.out.println("路由key为:" + envelope.getRoutingKey());
               //交换机
               System.out.println("交换机为:" + envelope.getExchange());
               //消息id
               System.out.println("消息id为:" + envelope.getDeliveryTag());
               //收到的消息
               System.out.println("消费者2-接收到的消息为:" + new String(body,
                       "utf-8"));
          }
      };
       //监听消息
       /**
        * 参数1:队列名称
        * 参数2:是否自动确认,设置为true为表示消息接收到自动向mq回复接收到了,mq接收到回复
        会删除消息,设置为false则需要手动确认
        * 参数3:消息接收到后回调
        */
       channel.basicConsume(Producer.DIRECT_QUEUE_UPDATE, true, consumer);
  }
}

③测试

启动所有消费者,然后使用生产者发送消息;在消费者对应的控制台可以查看到生产者发送对应 routing key对应队列的消息;到达按照需要接收的效果。

在执行完测试代码后,其实到RabbitMQ的管理后台找到 Exchanges 选项卡,点击 direct_exchange 的交换机,可以查看到如下的绑定:

image-20211202111906727

④小结

Routing模式要求队列在绑定交换机时要指定routing key,消息会转发到符合routing key的队列。

5、Topics通配符模式

①模式说明

Topic 类型与 Direct 相比,都是可以根据 RoutingKey 把消息路由到不同的队列。只不过 Topic 类型 Exchange 可以让队列在绑定 Routing key 的时候使用通配符!

Routingkey 一般都是有一个或多个单词组成,多个单词之间以”.”分割,例如: item.insert

通配符规则:

  • # :匹配一个或多个词

  • * :匹配不多不少恰好1个词

    举例:

  • item.# :能够匹配 item.insert.abc 或者 item.insert

  • item.* :只能匹配 item.insert

image-20211202153732735

image-20211202153746144

图解:

  • 红色Queue:绑定的是 usa.# ,因此凡是以 usa. 开头的 routing key 都会被匹配到

  • 黄色Queue:绑定的是 #.news ,因此凡是以 .news 结尾的 routing key 都会被匹配

②代码

image-20211202153827268

1)生产者

使用topic类型的Exchange,发送消息的routing key有3种: item.insert 、 item.update 、 item.delete :

package com.lxs.rabbitmq.topic;

import com.lxs.rabbitmq.util.ConnectionUtil;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;

/**
 * 通配符Topic的交换机类型为:topic
 */
public class Producer {
    //交换机名称
    static final String TOPIC_EXCHAGE = "topic_exchange";
    //队列名称
    static final String TOPIC_QUEUE_1 = "topic_queue_1";
    //队列名称
    static final String TOPIC_QUEUE_2 = "topic_queue_2";

    public static void main(String[] args) throws Exception {
        //创建连接
        Connection connection = ConnectionUtil.getConnection();
        // 创建频道
        Channel channel = connection.createChannel();
        /**
         * 声明交换机
         * 参数1:交换机名称
         * 参数2:交换机类型,fanout、topic、topic、headers
         */
        channel.exchangeDeclare(TOPIC_EXCHAGE, BuiltinExchangeType.TOPIC);
        // 发送信息
        String message = "新增了商品。Topic模式;routing key 为 item.insert ";
        channel.basicPublish(TOPIC_EXCHAGE, "item.insert", null,message.getBytes());
        System.out.println("已发送消息:" + message);
        // 发送信息
        message = "修改了商品。Topic模式;routing key 为 item.update";
        channel.basicPublish(TOPIC_EXCHAGE, "item.update", null,message.getBytes());
        System.out.println("已发送消息:" + message);
        // 发送信息
        message = "删除了商品。Topic模式;routing key 为 item.delete";
        channel.basicPublish(TOPIC_EXCHAGE, "item.delete", null,message.getBytes());
        System.out.println("已发送消息:" + message);
        // 关闭资源
        channel.close();
        connection.close();
    }
}

2)消费者1

接收两种类型的消息:更新商品和删除商品

package com.lxs.rabbitmq.topic;

import com.lxs.rabbitmq.util.ConnectionUtil;
import com.rabbitmq.client.*;

import java.io.IOException;

public class Consumer1 {
    public static void main(String[] args) throws Exception {
        Connection connection = ConnectionUtil.getConnection();
        // 创建频道
        Channel channel = connection.createChannel();
        //声明交换机
        channel.exchangeDeclare(Producer.TOPIC_EXCHAGE,BuiltinExchangeType.TOPIC);
        // 声明(创建)队列
        /**
         * 参数1:队列名称
         * 参数2:是否定义持久化队列
         * 参数3:是否独占本次连接
         * 参数4:是否在不使用的时候自动删除队列
         * 参数5:队列其它参数
         */
        channel.queueDeclare(Producer.TOPIC_QUEUE_1, true, false, false, null);
        //队列绑定交换机
        channel.queueBind(Producer.TOPIC_QUEUE_1, Producer.TOPIC_EXCHAGE,"item.update");
        channel.queueBind(Producer.TOPIC_QUEUE_1, Producer.TOPIC_EXCHAGE,"item.delete");
        //创建消费者;并设置消息处理
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            @Override
            /**
             * consumerTag 消息者标签,在channel.basicConsume时候可以指定
             * envelope 消息包的内容,可从中获取消息id,消息routingkey,交换机,消息和重
             传标志(收到消息失败后是否需要重新发送)
             * properties 属性信息
             * body 消息
             */
            public void handleDelivery(String consumerTag, Envelope envelope,
                                       AMQP.BasicProperties properties, byte[] body) throws IOException {
                //路由key
                System.out.println("路由key为:" + envelope.getRoutingKey());
                //交换机
                System.out.println("交换机为:" + envelope.getExchange());
                //消息id
                System.out.println("消息id为:" + envelope.getDeliveryTag());
                //收到的消息
                System.out.println("消费者1-接收到的消息为:" + new String(body,"utf-8"));
            }
        };
        //监听消息
        /**
         * 参数1:队列名称
         * 参数2:是否自动确认,设置为true为表示消息接收到自动向mq回复接收到了,mq接收到回复
         会删除消息,设置为false则需要手动确认
         * 参数3:消息接收到后回调
         */
        channel.basicConsume(Producer.TOPIC_QUEUE_1, true, consumer);
    }
}

3)消费者2

接收所有类型的消息:新增商品,更新商品和删除商品。

package com.lxs.rabbitmq.topic;

import com.lxs.rabbitmq.util.ConnectionUtil;
import com.rabbitmq.client.*;

import java.io.IOException;

public class Consumer2 {
   public static void main(String[] args) throws Exception {
       Connection connection = ConnectionUtil.getConnection();
       // 创建频道
       Channel channel = connection.createChannel();
       //声明交换机
       channel.exchangeDeclare(Producer.TOPIC_EXCHAGE,BuiltinExchangeType.TOPIC);
       // 声明(创建)队列
       /**
        * 参数1:队列名称
        * 参数2:是否定义持久化队列
        * 参数3:是否独占本次连接
        * 参数4:是否在不使用的时候自动删除队列
        * 参数5:队列其它参数
        */
       channel.queueDeclare(Producer.TOPIC_QUEUE_2, true, false, false, null);
       //队列绑定交换机
       channel.queueBind(Producer.TOPIC_QUEUE_2, Producer.TOPIC_EXCHAGE,"item.*");
       //创建消费者;并设置消息处理
       DefaultConsumer consumer = new DefaultConsumer(channel) {
           @Override
           /**
            * consumerTag 消息者标签,在channel.basicConsume时候可以指定
            * envelope 消息包的内容,可从中获取消息id,消息routingkey,交换机,消息和重
            传标志(收到消息失败后是否需要重新发送)
            * properties 属性信息
            * body 消息
            */
           public void handleDelivery(String consumerTag, Envelope envelope,
                                      AMQP.BasicProperties properties, byte[] body) throws IOException {
               //路由key
               System.out.println("路由key为:" + envelope.getRoutingKey());
               //交换机
               System.out.println("交换机为:" + envelope.getExchange());
               //消息id
               System.out.println("消息id为:" + envelope.getDeliveryTag());
               //收到的消息
               System.out.println("消费者2-接收到的消息为:" + new String(body,"utf-8"));
          }
      };
       //监听消息
       /**
        * 参数1:队列名称
        * 参数2:是否自动确认,设置为true为表示消息接收到自动向mq回复接收到了,mq接收到回复
        会删除消息,设置为false则需要手动确认
        * 参数3:消息接收到后回调
        */
       channel.basicConsume(Producer.TOPIC_QUEUE_2, true, consumer);
  }
}

③测试

启动所有消费者,然后使用生产者发送消息;在消费者对应的控制台可以查看到生产者发送对应 routing key对应队列的消息;到达按照需要接收的效果;并且这些routing key可以使用通配符。

在执行完测试代码后,其实到RabbitMQ的管理后台找到 Exchanges 选项卡,点击 topic_exchange 的交换机,可以查看到如下的绑定:

image-20211202154303662

④小结

Topic主题模式可以实现 Publish/Subscribe发布与订阅模式 和 Routing路由模式 的功能;只是Topic 在配置routing key 的时候可以使用通配符,显得更加灵活。

6、模式总结

RabbitMQ工作模式:

1、简单模式 HelloWorld 一个生产者、一个消费者,不需要设置交换机(使用 默认的交换机)

2、工作队列模式 Work Queue 一个生产者、多个消费者(竞争关系),不需要设置交换机(使用默认的交换机) 3、发布订阅模式 Publish/subscribe 需要设置类型为fanout的交换机,并且交换机和队列进行绑定,当发送消息到交换机后,交换机会将消息发送到绑定的队列 4、路由模式 Routing 需要设置类型为direct的交换机,交换机和队列进行绑定,并且指定routingkey,当发送消息到交换机后,交换机会根据routing key将消息发送到对应的队列 5、通配符模式 Topic 需要设置类型为topic的交换机,交换机和队列进行绑定,并且指定通配符方式的routing key,当发送消息到交换机后,交换机会根据routing key将消息发送到对应的队列

 

五、Spring 整合RabbitMQ

1、搭建生产者工程

①创建工程

image-20211210170506388

②添加依赖

修改pom.xml文件内容为如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.lxs</groupId>
    <artifactId>spring-rabbitmq-producer</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.1.7.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.amqp</groupId>
            <artifactId>spring-rabbit</artifactId>
            <version>2.1.8.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.1.7.RELEASE</version>
        </dependency>
    </dependencies>
</project>

③配置整合

\1. 创建 spring-rabbitmq-producer\src\main\resources\properties\rabbitmq.properties 连接参数等配置文件;

rabbitmq.host=192.168.88.128
rabbitmq.port=5672
rabbitmq.username=msk
rabbitmq.password=123456
rabbitmq.virtual-host=/msk

\2. 创建 spring-rabbitmq-producer\src\main\resources\spring\spring-rabbitmq.xml 整合 配置文件;

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:context="http://www.springframework.org/schema/context"
      xmlns:rabbit="http://www.springframework.org/schema/rabbit"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/rabbit
http://www.springframework.org/schema/rabbit/spring-rabbit.xsd">
   <!--加载配置文件-->
   <context:property-placeholder location="classpath:properties/rabbitmq.properties"/>
   <!-- 定义rabbitmq connectionFactory -->
   <rabbit:connection-factory id="connectionFactory" host="${rabbitmq.host}"
                              port="${rabbitmq.port}"
                              username="${rabbitmq.username}"
                              password="${rabbitmq.password}"
                              virtual-host="${rabbitmq.virtual-host}"/>
   <!--定义管理交换机、队列-->
   <rabbit:admin connection-factory="connectionFactory"/>
   <!--定义持久化队列,不存在则自动创建;不绑定到交换机则绑定到默认交换机
   默认交换机类型为direct,名字为:"",路由键为队列的名称
   -->
   <rabbit:queue id="spring_queue" name="spring_queue" auto-declare="true"/>
   <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~广播;所有队列都能收到消息
   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
   <!--定义广播交换机中的持久化队列,不存在则自动创建-->
   <rabbit:queue id="spring_fanout_queue_1" name="spring_fanout_queue_1" auto-declare="true"/>
   <!--定义广播交换机中的持久化队列,不存在则自动创建-->
   <rabbit:queue id="spring_fanout_queue_2" name="spring_fanout_queue_2" auto-declare="true"/>
   <!--定义广播类型交换机;并绑定上述两个队列-->
   <rabbit:fanout-exchange id="spring_fanout_exchange" name="spring_fanout_exchange" auto-declare="true">
       <rabbit:bindings>
           <rabbit:binding queue="spring_fanout_queue_1"/>
           <rabbit:binding queue="spring_fanout_queue_2"/>
       </rabbit:bindings>
   </rabbit:fanout-exchange>
   <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~通配符;*匹配一个单词,#匹配多个单词
   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
   <!--定义广播交换机中的持久化队列,不存在则自动创建-->
   <rabbit:queue id="spring_topic_queue_star" name="spring_topic_queue_star" auto-declare="true"/>
   <!--定义广播交换机中的持久化队列,不存在则自动创建-->
   <rabbit:queue id="spring_topic_queue_well" name="spring_topic_queue_well" auto-declare="true"/>
   <!--定义广播交换机中的持久化队列,不存在则自动创建-->
   <rabbit:queue id="spring_topic_queue_well2" name="spring_topic_queue_well2" auto-declare="true"/>
   <rabbit:topic-exchange id="spring_topic_exchange" name="spring_topic_exchange" auto-declare="true">
       <rabbit:bindings>
           <rabbit:binding pattern="lxs.*" queue="spring_topic_queue_star"/>
           <rabbit:binding pattern="lxs.#" queue="spring_topic_queue_well"/>
           <rabbit:binding pattern="xzk.#" queue="spring_topic_queue_well2"/>
       </rabbit:bindings>
   </rabbit:topic-exchange>
   <!--定义rabbitTemplate对象操作可以在代码中方便发送消息-->
   <rabbit:template id="rabbitTemplate" connection-factory="connectionFactory"/>
</beans>

④发送消息

创建测试文件 spring-rabbitmqproducer\src\test\java\com\lxs\rabbitmq\ProducerTest.java

package com.lxs.rabbitmq;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/spring-rabbitmq.xml")
public class ProducerTest {
   @Autowired
   private RabbitTemplate rabbitTemplate;

   /**
    * 只发队列消息
    * 默认交换机类型为 direct
    * 交换机的名称为空,路由键为队列的名称
    */
   @Test
   public void queueTest() {
       //路由键与队列同名
       rabbitTemplate.convertAndSend("spring_queue", "只发队列spring_queue的消息。");
  }

   /**
    * 发送广播
    * 交换机类型为 fanout
    * 绑定到该交换机的所有队列都能够收到消息
    */
   @Test
   public void fanoutTest() {
   /**
    * 参数1:交换机名称
    * 参数2:路由键名(广播设置为空)
    * 参数3:发送的消息内容
    */
       rabbitTemplate.convertAndSend("spring_fanout_exchange", "", "发送到spring_fanout_exchange交换机的广播消息");
  }

   /**
    * 通配符
    * 交换机类型为 topic
    * 匹配路由键的通配符,*表示一个单词,#表示多个单词
    * 绑定到该交换机的匹配队列能够收到对应消息
    */
   @Test
   public void topicTest() {
   /**
    * 参数1:交换机名称
    * 参数2:路由键名
    * 参数3:发送的消息内容
    */
       rabbitTemplate.convertAndSend("spring_topic_exchange", "lxs.bj", "发送到spring_topic_exchange交换机lxs.bj的消息");
       rabbitTemplate.convertAndSend("spring_topic_exchange", "lxs.bj.1", "发送到spring_topic_exchange交换机lxs.bj.1的消息");
       rabbitTemplate.convertAndSend("spring_topic_exchange", "lxs.bj.2", "发送到spring_topic_exchange交换机lxs.bj.2的消息");
       rabbitTemplate.convertAndSend("spring_topic_exchange", "xzk.cn", "发送到spring_topic_exchange交换机xzk.cn的消息");
  }
}

2、搭建消费者工程

①创建工程

image-20211210173157084

②添加依赖

修改pom.xml文件内容为如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.lxs</groupId>
    <artifactId>spring-rabbitmq-consumers</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.1.7.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.amqp</groupId>
            <artifactId>spring-rabbit</artifactId>
            <version>2.1.8.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.1.7.RELEASE</version>
        </dependency>
    </dependencies>
</project>

③配置整合

\1. 创建 spring-rabbitmq-consumer\src\main\resources\properties\rabbitmq.properties 连接参数等配置文件;

rabbitmq.host=192.168.88.128
rabbitmq.port=5672
rabbitmq.username=msk
rabbitmq.password=123456
rabbitmq.virtual-host=/msk

\2. 创建 spring-rabbitmq-consumer\src\main\resources\spring\spring-rabbitmq.xml 整合 配置文件;

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:rabbit="http://www.springframework.org/schema/rabbit"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/rabbit
http://www.springframework.org/schema/rabbit/spring-rabbit.xsd">
    <!--加载配置文件-->
    <context:property-placeholder location="classpath:properties/rabbitmq.properties"/>
    <!-- 定义rabbitmq connectionFactory -->
    <rabbit:connection-factory id="connectionFactory" host="${rabbitmq.host}"
                               port="${rabbitmq.port}"
                               username="${rabbitmq.username}"
                               password="${rabbitmq.password}"
                               virtual-host="${rabbitmq.virtual-host}"/>
    <bean id="springQueueListener" class="com.lxs.rabbitmq.listener.SpringQueueListener"/>
    <bean id="fanoutListener1" class="com.lxs.rabbitmq.listener.FanoutListener1"/>
    <bean id="fanoutListener2" class="com.lxs.rabbitmq.listener.FanoutListener2"/>
    <bean id="topicListenerStar" class="com.lxs.rabbitmq.listener.TopicListenerStar"/>
    <bean id="topicListenerWell" class="com.lxs.rabbitmq.listener.TopicListenerWell"/>
    <bean id="topicListenerWell2" class="com.lxs.rabbitmq.listener.TopicListenerWell2"/>
    <rabbit:listener-container connection-factory="connectionFactory" auto-declare="true">
        <rabbit:listener ref="springQueueListener" queue-names="spring_queue"/>
        <rabbit:listener ref="fanoutListener1" queue-names="spring_fanout_queue_1"/>
        <rabbit:listener ref="fanoutListener2" queue-names="spring_fanout_queue_2"/>
        <rabbit:listener ref="topicListenerStar" queue-names="spring_topic_queue_star"/>
        <rabbit:listener ref="topicListenerWell" queue-names="spring_topic_queue_well"/>
        <rabbit:listener ref="topicListenerWell2" queue-names="spring_topic_queue_well2"/>
    </rabbit:listener-container>
</beans>

④消息监听器

1)队列监听器

创建 spring-rabbitmqconsumer\src\main\java\com\lxs\rabbitmq\listener\SpringQueueListener.java

package com.lxs.rabbitmq.listener;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;

public class SpringQueueListener implements MessageListener {
    public void onMessage(Message message) {
        try {
            String msg = new String(message.getBody(), "utf-8");
            System.out.printf("接收路由名称为:%s,路由键为:%s,队列名为:%s的消息:%s\n",
                    message.getMessageProperties().getReceivedExchange(),
                    message.getMessageProperties().getReceivedRoutingKey(),
                    message.getMessageProperties().getConsumerQueue(),
                    msg);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

2)广播监听器1

创建 spring-rabbitmqconsumer\src\main\java\com\lxs\rabbitmq\listener\FanoutListener1.java

package com.lxs.rabbitmq.listener;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;

public class FanoutListener1 implements MessageListener {
    public void onMessage(Message message) {
        try {
            String msg = new String(message.getBody(), "utf-8");
            System.out.printf("广播监听器1:接收路由名称为:%s,路由键为:%s,队列名为:%s的消息:%s \n",
                    message.getMessageProperties().getReceivedExchange(),
                    message.getMessageProperties().getReceivedRoutingKey(),
                    message.getMessageProperties().getConsumerQueue(),
                    msg);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

3)广播监听器2

创建 spring-rabbitmqconsumer\src\main\java\com\lxs\rabbitmq\listener\FanoutListener2.java

package com.lxs.rabbitmq.listener;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;

public class FanoutListener2 implements MessageListener {
    public void onMessage(Message message) {
        try {
            String msg = new String(message.getBody(), "utf-8");
            System.out.printf("广播监听器2:接收路由名称为:%s,路由键为:%s,队列名为:%s的消息:%s \n",
                    message.getMessageProperties().getReceivedExchange(),
                    message.getMessageProperties().getReceivedRoutingKey(),
                    message.getMessageProperties().getConsumerQueue(),
                    msg);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

4)星号通配符监听器

创建 spring-rabbitmqconsumer\src\main\java\com\lxs\rabbitmq\listener\TopicListenerStar.java

package com.lxs.rabbitmq.listener;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;

public class TopicListenerStar implements MessageListener {
    public void onMessage(Message message) {
        try {
            String msg = new String(message.getBody(), "utf-8");
            System.out.printf("通配符*监听器:接收路由名称为:%s,路由键为:%s,队列名为:%s的消息:%s \n",
                    message.getMessageProperties().getReceivedExchange(),
                    message.getMessageProperties().getReceivedRoutingKey(),
                    message.getMessageProperties().getConsumerQueue(),
                    msg);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

5)井号通配符监听器

创建 spring-rabbitmqconsumer\src\main\java\com\lxs\rabbitmq\listener\TopicListenerWell.java

package com.lxs.rabbitmq.listener;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;

public class TopicListenerWell implements MessageListener {
    public void onMessage(Message message) {
        try {
            String msg = new String(message.getBody(), "utf-8");
            System.out.printf("通配符#监听器:接收路由名称为:%s,路由键为:%s,队列名为:%s的消息:%s \n",
                    message.getMessageProperties().getReceivedExchange(),
                    message.getMessageProperties().getReceivedRoutingKey(),
                    message.getMessageProperties().getConsumerQueue(),
                    msg);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

6)井号通配符监听器2

创建 spring-rabbitmqconsumer\src\main\java\com\lxs\rabbitmq\listener\TopicListenerWell2.java

package com.lxs.rabbitmq.listener;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;

public class TopicListenerWell2 implements MessageListener {
   public void onMessage(Message message) {
       try {
           String msg = new String(message.getBody(), "utf-8");
           System.out.printf("通配符#监听器2:接收路由名称为:%s,路由键为:%s,队列名为:%s的消息:%s \n",
                   message.getMessageProperties().getReceivedExchange(),
                   message.getMessageProperties().getReceivedRoutingKey(),
                   message.getMessageProperties().getConsumerQueue(),
                   msg);
      } catch (Exception e) {
           e.printStackTrace();
      }
  }
}

⑤添加测试

package com.lxs.rabbitmq;

import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/spring-rabbitmq.xml")
public class ConsumerTest {
   public void test(){
       while (true){

      }
  }
}

六、Spring Boot整合RabbitMQ

1、简介

在Spring项目中,可以使用Spring-Rabbit去操作RabbitMQ https://github.com/spring-projects/spring-amqp 尤其是在spring boot项目中只需要引入对应的amqp启动器依赖即可,方便的使用RabbitTemplate发送消息,使用注解接收消息。

一般在开发过程中: 生产者工程:

  • application.yml文件配置RabbitMQ相关信息;

  • 在生产者工程中编写配置类,用于创建交换机和队列,并进行绑定

  • 注入RabbitTemplate对象,通过RabbitTemplate对象发送消息到交换机

消费者工程:

  • application.yml文件配置RabbitMQ相关信息

  • 创建消息处理类,用于接收队列中的消息并进行处理

2、搭建生产者工程

①创建工程

创建生产者工程springboot-rabbitmq-producer

image-20211210180925299

②添加依赖

修改pom.xml文件内容为如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.lxs</groupId>
    <artifactId>springboot-rabbitmq-producer</artifactId>
    <version>1.0-SNAPSHOT</version>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.RELEASE</version>
    </parent>
    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
    </dependencies>
</project>

③启动类

package com.lxs.rabbitmq;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ProducerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ProducerApplication.class, args);
    }
}

④配置RabbitMQ

1)配置文件 创建application.yml,内容如下:

spring:
  rabbitmq:
    host: 192.168.88.128
    port: 5672
    virtual-host: /msk
    username: msk
    password: 123456

2)绑定交换机和队列 创建RabbitMQ队列与交换机绑定的配置类com.lxs.rabbitmq.config.RabbitMQConfig

package com.lxs.rabbitmq.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitMQConfig {
   //交换机名称
   public static final String ITEM_TOPIC_EXCHANGE = "springboot_item_topic_exchange";
   //队列名称
   public static final String ITEM_QUEUE = "springboot_item_queue";

   //声明交换机
   @Bean("itemTopicExchange")
   public Exchange topicExchange() {
       return ExchangeBuilder.topicExchange(ITEM_TOPIC_EXCHANGE).durable(true).build();
  }

   //声明队列
   @Bean("itemQueue")
   public Queue itemQueue() {
       return QueueBuilder.durable(ITEM_QUEUE).build();
  }

   //绑定队列和交换机
   @Bean
   public Binding itemQueueExchange(@Qualifier("itemQueue") Queue queue, @Qualifier("itemTopicExchange") Exchange exchange) {
       return BindingBuilder.bind(queue).to(exchange).with("item.#").noargs();
  }
}

⑤测试

在生产者工程springboot-rabbitmq-producer中创建测试类,发送消息:

package com.lxs.rabbitmq;

import com.lxs.rabbitmq.config.RabbitMQConfig;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class RabbitMQTest {
   @Autowired
   private RabbitTemplate rabbitTemplate;

   @Test
   public void test() {
       rabbitTemplate.convertAndSend(RabbitMQConfig.ITEM_TOPIC_EXCHANGE, "item.insert", "商品新增,routing key 为item.insert");
       rabbitTemplate.convertAndSend(RabbitMQConfig.ITEM_TOPIC_EXCHANGE, "item.update", "商品修改,routing key 为item.update");
       rabbitTemplate.convertAndSend(RabbitMQConfig.ITEM_TOPIC_EXCHANGE, "item.delete", "商品删除,routing key 为item.delete");
  }
}

先运行上述测试程序(交换机和队列才能先被声明和绑定),然后启动消费者;在消费者工程 springboot-rabbitmq-consumer中控制台查看是否接收到对应消息。

另外;也可以在RabbitMQ的管理控制台中查看到交换机与队列的绑定:

image-20211210181604583

3、搭建消费者工程

①创建工程

创建消费者工程springboot-rabbitmq-consumer

image-20211210181707889

②添加依赖

修改pom.xml文件内容为如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.lxs</groupId>
    <artifactId>springboot-rabbitmq-consumer</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
    </dependencies>
</project>

③启动类

package com.lxs.rabbitmq;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ConsumerApplication {
   public static void main(String[] args) {
       SpringApplication.run(ConsumerApplication.class, args);
  }
}

④配置RabbitMQ

创建application.yml,内容如下:

spring:
rabbitmq:
  host: 192.168.88.128
  port: 5672
  virtual-host: /msk
  username: msk
  password: 123456

⑤消息监听处理类

编写消息监听器com.lxs.rabbitmq.listener.MyListener

package com.lxs.rabbitmq.listener;

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

@Component
public class MyListener {
   /**
    * 监听某个队列的消息
    *
    * @param message 接收到的消息
    */
   @RabbitListener(queues = "springboot_item_queue")
   public void myListener1(String message) {
       System.out.println("消费者接收到的消息为:" + message);
  }
}

⑥添加测试

package com.lxs.rabbitmq;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class RabbitMQTest {
   @Test
   public void test(){
       while (true){

      }
  }
}

七、高级特性

1、消息的可靠投递

在使用 RabbitMQ 的时候,作为消息发送方希望杜绝任何消息丢失或者投递失败场景。RabbitMQ 为我 们提供了两种方式用来控制消息的投递可靠性模式。

  • confirm 确认模式

  • return 退回模式

rabbitmq 整个消息投递的路径为:producer--->rabbitmq broker--->exchange--->queue--->consumer

  • 消息从 producer 到 exchange 则会返回一个 confirmCallback 。

  • 消息从 exchange-->queue 投递失败则会返回一个 returnCallback 。

我们将利用这两个 callback 控制消息的可靠性投递

①确认模式

在Spring整合RabbitMQ的Producer基础上修改spring-rabbitmq.xml的内容

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:context="http://www.springframework.org/schema/context"
      xmlns:rabbit="http://www.springframework.org/schema/rabbit"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/rabbit
http://www.springframework.org/schema/rabbit/spring-rabbit.xsd">
   <!--加载配置文件-->
   <context:property-placeholder location="classpath:properties/rabbitmq.properties"/>
   <!-- 定义rabbitmq connectionFactory -->
   <rabbit:connection-factory id="connectionFactory" host="192.168.88.128"
                              port="${rabbitmq.port}"
                              username="${rabbitmq.username}"
                              password="${rabbitmq.password}"
                              virtual-host="${rabbitmq.virtual-host}"
                             
                             
   <!--新增内容-->                          
                              publisher-confirms="true"
                              publisher-returns="true"
                             
                             
  />
   <!--定义管理交换机、队列-->
   <rabbit:admin connection-factory="connectionFactory"/>
   <!--定义持久化队列,不存在则自动创建;不绑定到交换机则绑定到默认交换机
   默认交换机类型为direct,名字为:"",路由键为队列的名称
   -->
   <rabbit:queue id="spring_queue" name="spring_queue" auto-declare="true"/>
   <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~广播;所有队列都能收到消息
   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
   <!--定义广播交换机中的持久化队列,不存在则自动创建-->
   <rabbit:queue id="spring_fanout_queue_1" name="spring_fanout_queue_1" auto-declare="true"/>
   <!--定义广播交换机中的持久化队列,不存在则自动创建-->
   <rabbit:queue id="spring_fanout_queue_2" name="spring_fanout_queue_2" auto-declare="true"/>
   <!--定义广播类型交换机;并绑定上述两个队列-->
   <rabbit:fanout-exchange id="spring_fanout_exchange" name="spring_fanout_exchange" auto-declare="true">
       <rabbit:bindings>
           <rabbit:binding queue="spring_fanout_queue_1"/>
           <rabbit:binding queue="spring_fanout_queue_2"/>
       </rabbit:bindings>
   </rabbit:fanout-exchange>
   <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~通配符;*匹配一个单词,#匹配多个单词
   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
   <!--定义广播交换机中的持久化队列,不存在则自动创建-->
   <rabbit:queue id="spring_topic_queue_star" name="spring_topic_queue_star" auto-declare="true"/>
   <!--定义广播交换机中的持久化队列,不存在则自动创建-->
   <rabbit:queue id="spring_topic_queue_well" name="spring_topic_queue_well" auto-declare="true"/>
   <!--定义广播交换机中的持久化队列,不存在则自动创建-->
   <rabbit:queue id="spring_topic_queue_well2" name="spring_topic_queue_well2" auto-declare="true"/>
   <rabbit:topic-exchange id="spring_topic_exchange" name="spring_topic_exchange" auto-declare="true">
       <rabbit:bindings>
           <rabbit:binding pattern="lxs.*" queue="spring_topic_queue_star"/>
           <rabbit:binding pattern="lxs.#" queue="spring_topic_queue_well"/>
           <rabbit:binding pattern="xzk.#" queue="spring_topic_queue_well2"/>
       </rabbit:bindings>
   </rabbit:topic-exchange>
   <!--定义rabbitTemplate对象操作可以在代码中方便发送消息-->
   <rabbit:template id="rabbitTemplate" connection-factory="connectionFactory"/>
   
   <!--新增内容-->
   <!--消息可靠性投递(生产端)-->
   <rabbit:queue id="test_queue_confirm" name="test_queue_confirm"></rabbit:queue>
   <rabbit:direct-exchange name="test_exchange_confirm">
       <rabbit:bindings>
           <rabbit:binding queue="test_queue_confirm" key="confirm"></rabbit:binding>
       </rabbit:bindings>
   </rabbit:direct-exchange>
   
   
</beans>

添加测试方法

package com.lxs.rabbitmq;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/spring-rabbitmq.xml")
public class ProducerTest {
   @Autowired
   private RabbitTemplate rabbitTemplate;

   /**
    * 只发队列消息
    * 默认交换机类型为 direct
    * 交换机的名称为空,路由键为队列的名称
    */
   @Test
   public void queueTest() {
       //路由键与队列同名
       rabbitTemplate.convertAndSend("spring_queue", "只发队列spring_queue的消息。");
  }

   /**
    * 发送广播
    * 交换机类型为 fanout
    * 绑定到该交换机的所有队列都能够收到消息
    */
   @Test
   public void fanoutTest() {
   /**
    * 参数1:交换机名称
    * 参数2:路由键名(广播设置为空)
    * 参数3:发送的消息内容
    */
       rabbitTemplate.convertAndSend("spring_fanout_exchange", "", "发送到spring_fanout_exchange交换机的广播消息");
  }

   /**
    * 通配符
    * 交换机类型为 topic
    * 匹配路由键的通配符,*表示一个单词,#表示多个单词
    * 绑定到该交换机的匹配队列能够收到对应消息
    */
   @Test
   public void topicTest() {
   /**
    * 参数1:交换机名称
    * 参数2:路由键名
    * 参数3:发送的消息内容
    */
       rabbitTemplate.convertAndSend("spring_topic_exchange", "lxs.bj", "发送到spring_topic_exchange交换机lxs.bj的消息");
       rabbitTemplate.convertAndSend("spring_topic_exchange", "lxs.bj.1", "发送到spring_topic_exchange交换机lxs.bj.1的消息");
       rabbitTemplate.convertAndSend("spring_topic_exchange", "lxs.bj.2", "发送到spring_topic_exchange交换机lxs.bj.2的消息");
       rabbitTemplate.convertAndSend("spring_topic_exchange", "xzk.cn", "发送到spring_topic_exchange交换机xzk.cn的消息");
  }
   /**
    * 确认模式:
    * 步骤:
    * 1. 确认模式开启:ConnectionFactory中开启publisher-confirms="true"
    * 2. 在rabbitTemplate定义ConfirmCallBack回调函数
    */
   @Test
   public void testConfirm() {
       //2. 定义回调
       rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
           /**
            *
            * @param correlationData 相关配置信息
            * @param ack exchange交换机 是否成功收到了消息。true 成功,false代表失败
            * @param cause 失败原因
            */
           @Override
           public void confirm(CorrelationData correlationData, boolean ack, String cause) {
               System.out.println("confirm方法被执行了....");
               if (ack) {
                   //接收成功
                   System.out.println("接收成功消息" + cause);
              } else {
                   //接收失败
                   System.out.println("接收失败消息" + cause);
                   //做一些处理,让消息再次发送。
              }
          }
      });
       //3. 发送消息
       rabbitTemplate.convertAndSend("test_exchange_confirm", "confirm", "message confirm....");
  }
}

消息从 producer 到 exchange 则会返回一个 confirmCallback

image-20211211183543925

修改发送消息的exchange为test_exchange_confirm2,再次运行

image-20211211183646770

②退回模式

消息从 exchange-->queue 投递失败则会返回一个 returnCallback

添加测试方法

package com.lxs.rabbitmq;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/spring-rabbitmq.xml")
public class ProducerTest {
   @Autowired
   private RabbitTemplate rabbitTemplate;

   /**
    * 只发队列消息
    * 默认交换机类型为 direct
    * 交换机的名称为空,路由键为队列的名称
    */
   @Test
   public void queueTest() {
       //路由键与队列同名
       rabbitTemplate.convertAndSend("spring_queue", "只发队列spring_queue的消息。");
  }

   /**
    * 发送广播
    * 交换机类型为 fanout
    * 绑定到该交换机的所有队列都能够收到消息
    */
   @Test
   public void fanoutTest() {
   /**
    * 参数1:交换机名称
    * 参数2:路由键名(广播设置为空)
    * 参数3:发送的消息内容
    */
       rabbitTemplate.convertAndSend("spring_fanout_exchange", "", "发送到spring_fanout_exchange交换机的广播消息");
  }

   /**
    * 通配符
    * 交换机类型为 topic
    * 匹配路由键的通配符,*表示一个单词,#表示多个单词
    * 绑定到该交换机的匹配队列能够收到对应消息
    */
   @Test
   public void topicTest() {
   /**
    * 参数1:交换机名称
    * 参数2:路由键名
    * 参数3:发送的消息内容
    */
       rabbitTemplate.convertAndSend("spring_topic_exchange", "lxs.bj", "发送到spring_topic_exchange交换机lxs.bj的消息");
       rabbitTemplate.convertAndSend("spring_topic_exchange", "lxs.bj.1", "发送到spring_topic_exchange交换机lxs.bj.1的消息");
       rabbitTemplate.convertAndSend("spring_topic_exchange", "lxs.bj.2", "发送到spring_topic_exchange交换机lxs.bj.2的消息");
       rabbitTemplate.convertAndSend("spring_topic_exchange", "xzk.cn", "发送到spring_topic_exchange交换机xzk.cn的消息");
  }
   /**
    * 确认模式:
    * 步骤:
    * 1. 确认模式开启:ConnectionFactory中开启publisher-confirms="true"
    * 2. 在rabbitTemplate定义ConfirmCallBack回调函数
    */
   @Test
   public void testConfirm() {
       //2. 定义回调
       rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
           /**
            *
            * @param correlationData 相关配置信息
            * @param ack exchange交换机 是否成功收到了消息。true 成功,false代表失败
            * @param cause 失败原因
            */
           @Override
           public void confirm(CorrelationData correlationData, boolean ack, String cause) {
               System.out.println("confirm方法被执行了....");
               if (ack) {
                   //接收成功
                   System.out.println("接收成功消息" + cause);
              } else {
                   //接收失败
                   System.out.println("接收失败消息" + cause);
                   //做一些处理,让消息再次发送。
              }
          }
      });
       //3. 发送消息
       rabbitTemplate.convertAndSend("test_exchange_confirm2", "confirm", "message confirm....");
  }
   /**
    * 回退模式: 当消息发送给Exchange后,Exchange路由到Queue失败是 才会执行 ReturnCallBack
    * 步骤:
    * 1. 开启回退模式:publisher-returns="true"
    * 2. 设置ReturnCallBack
    * 3. 设置Exchange处理消息失败的模式:setMandatory
    * 1. 如果消息没有路由到Queue,则丢弃消息(默认)
    * 2. 如果消息没有路由到Queue,返回给消息发送方ReturnCallBack
    */
   @Test
   public void testReturn() {
       //设置交换机处理失败消息的模式
       rabbitTemplate.setMandatory(true);
       //2.设置ReturnCallBack
       rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
           /**
            *
            * @param message 消息对象
            * @param replyCode 错误码
            * @param replyText 错误信息
            * @param exchange 交换机
            * @param routingKey 路由键
            */
           @Override
           public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
               System.out.println("return 执行了....");
               System.out.println(message);
               System.out.println(replyCode);
               System.out.println(replyText);
               System.out.println(exchange);
               System.out.println(routingKey);
               //处理
          }
      });
       //3. 发送消息
       rabbitTemplate.convertAndSend("test_exchange_confirm", "confirm", "message confirm....");
  }
}

image-20211211184342050

修改发送消息的routingKey为confirm123,再次运行测试方法

image-20211211184438814

2、Consumer Ack

ack指Acknowledge,确认。 表示消费端收到消息后的确认方式。

有三种确认方式:

  • 自动确认:acknowledge="none"

  • 手动确认:acknowledge="manual"

  • 根据异常情况确认:acknowledge="auto",(这种方式使用麻烦,不作讲解)

其中自动确认是指,当消息一旦被Consumer接收到,则自动确认收到,并将相应 message 从 RabbitMQ 的消息缓存中移除。但是在实际业务处理中,很可能消息接收到,业务处理出现异常,那么 该消息就会丢失。如果设置了手动确认方式,则需要在业务处理成功后,调用channel.basicAck(),手 动签收,如果出现异常,则调用channel.basicNack()方法,让其自动重新发送消息。

在Spring整合RabbitMQ的Consumer的基础上修改spring-rabbitmq.xml的内容

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:context="http://www.springframework.org/schema/context"
      xmlns:rabbit="http://www.springframework.org/schema/rabbit"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/rabbit
http://www.springframework.org/schema/rabbit/spring-rabbit.xsd">
   <!--加载配置文件-->
   <context:property-placeholder location="classpath:properties/rabbitmq.properties"/>
   <!-- 定义rabbitmq connectionFactory -->
   <rabbit:connection-factory id="connectionFactory" host="${rabbitmq.host}"
                              port="${rabbitmq.port}"
                              username="${rabbitmq.username}"
                              password="${rabbitmq.password}"
                              virtual-host="${rabbitmq.virtual-host}"/>
   <bean id="springQueueListener" class="com.lxs.rabbitmq.listener.SpringQueueListener"/>
   <bean id="fanoutListener1" class="com.lxs.rabbitmq.listener.FanoutListener1"/>
   <bean id="fanoutListener2" class="com.lxs.rabbitmq.listener.FanoutListener2"/>
   <bean id="topicListenerStar" class="com.lxs.rabbitmq.listener.TopicListenerStar"/>
   <bean id="topicListenerWell" class="com.lxs.rabbitmq.listener.TopicListenerWell"/>
   <bean id="topicListenerWell2" class="com.lxs.rabbitmq.listener.TopicListenerWell2"/>
   <rabbit:listener-container connection-factory="connectionFactory" auto-declare="true">
       <rabbit:listener ref="springQueueListener" queue-names="spring_queue"/>
       <rabbit:listener ref="fanoutListener1" queue-names="spring_fanout_queue_1"/>
       <rabbit:listener ref="fanoutListener2" queue-names="spring_fanout_queue_2"/>
       <rabbit:listener ref="topicListenerStar" queue-names="spring_topic_queue_star"/>
       <rabbit:listener ref="topicListenerWell" queue-names="spring_topic_queue_well"/>
       <rabbit:listener ref="topicListenerWell2" queue-names="spring_topic_queue_well2"/>
   </rabbit:listener-container>

<!-- 新增内容-->
   <context:component-scan base-package="com.lxs.listener"/>
   <rabbit:listener-container connection-factory="connectionFactory" acknowledge="manual">
       <rabbit:listener ref="ackListener" queue-names="test_queue_confirm"></rabbit:listener>
   </rabbit:listener-container>
</beans>

新建AckListener类

package com.lxs.listener;

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

@Component
public class AckListener implements ChannelAwareMessageListener {

   @Override
   public void onMessage(Message message, Channel channel) throws Exception {
       long deliverTag = message.getMessageProperties().getDeliveryTag();

       try {
           System.out.println(new String(message.getBody()));
           System.out.println("处理业务逻辑");

//           int i = 3/0;//模拟业务处理异常

           channel.basicAck(deliverTag, true);
      } catch (Exception e) {
           e.printStackTrace();

           //拒绝签收
           //requeue:true:表示重回队列
           channel.basicNack(deliverTag, true, true);
//           channel.basicReject(deliverTag, true);
      }
  }
}

运行测试类

image-20211211190507312

Producer端重发消息,将int i=3/0解除注释,再次运行测试类

image-20211211190656451

3、消费端限流

image-20211211190742538

 

修改Consumer的spring-rabbitmq.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:context="http://www.springframework.org/schema/context"
      xmlns:rabbit="http://www.springframework.org/schema/rabbit"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/rabbit
http://www.springframework.org/schema/rabbit/spring-rabbit.xsd">
   <!--加载配置文件-->
   <context:property-placeholder location="classpath:properties/rabbitmq.properties"/>
   <!-- 定义rabbitmq connectionFactory -->
   <rabbit:connection-factory id="connectionFactory" host="${rabbitmq.host}"
                              port="${rabbitmq.port}"
                              username="${rabbitmq.username}"
                              password="${rabbitmq.password}"
                              virtual-host="${rabbitmq.virtual-host}"/>
   <bean id="springQueueListener" class="com.lxs.rabbitmq.listener.SpringQueueListener"/>
   <bean id="fanoutListener1" class="com.lxs.rabbitmq.listener.FanoutListener1"/>
   <bean id="fanoutListener2" class="com.lxs.rabbitmq.listener.FanoutListener2"/>
   <bean id="topicListenerStar" class="com.lxs.rabbitmq.listener.TopicListenerStar"/>
   <bean id="topicListenerWell" class="com.lxs.rabbitmq.listener.TopicListenerWell"/>
   <bean id="topicListenerWell2" class="com.lxs.rabbitmq.listener.TopicListenerWell2"/>
   <rabbit:listener-container connection-factory="connectionFactory" auto-declare="true">
       <rabbit:listener ref="springQueueListener" queue-names="spring_queue"/>
       <rabbit:listener ref="fanoutListener1" queue-names="spring_fanout_queue_1"/>
       <rabbit:listener ref="fanoutListener2" queue-names="spring_fanout_queue_2"/>
       <rabbit:listener ref="topicListenerStar" queue-names="spring_topic_queue_star"/>
       <rabbit:listener ref="topicListenerWell" queue-names="spring_topic_queue_well"/>
       <rabbit:listener ref="topicListenerWell2" queue-names="spring_topic_queue_well2"/>
   </rabbit:listener-container>


   <context:component-scan base-package="com.lxs.listener"/>
<!-- 新增内容 -->
   <rabbit:listener-container connection-factory="connectionFactory" acknowledge="manual" prefetch="1">
       <rabbit:listener ref="qosListener" queue-names="test_queue_confirm"></rabbit:listener>
   </rabbit:listener-container>
</beans>

新增QosListener

package com.lxs.listener;

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

/**
* Consumer 限流机制
* 1. 确保ack机制为手动确认。
* 2. listener-container配置属性
*     perfetch = 1,表示消费端每次从mq拉去一条消息来消费,直到手动确认消费完毕后,才会继续拉去下一条消息。
*/

@Component
public class QosListener implements ChannelAwareMessageListener {

   @Override
   public void onMessage(Message message, Channel channel) throws Exception {

       Thread.sleep(1000);
       //1.获取消息
       System.out.println(new String(message.getBody()));

       //2. 处理业务逻辑

       //3. 签收
       channel.basicAck(message.getMessageProperties().getDeliveryTag(),true);

  }
}

Producer端新增测试方法

package com.lxs.rabbitmq;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/spring-rabbitmq.xml")
public class ProducerTest {
   @Autowired
   private RabbitTemplate rabbitTemplate;

   /**
    * 只发队列消息
    * 默认交换机类型为 direct
    * 交换机的名称为空,路由键为队列的名称
    */
   @Test
   public void queueTest() {
       //路由键与队列同名
       rabbitTemplate.convertAndSend("spring_queue", "只发队列spring_queue的消息。");
  }

   /**
    * 发送广播
    * 交换机类型为 fanout
    * 绑定到该交换机的所有队列都能够收到消息
    */
   @Test
   public void fanoutTest() {
   /**
    * 参数1:交换机名称
    * 参数2:路由键名(广播设置为空)
    * 参数3:发送的消息内容
    */
       rabbitTemplate.convertAndSend("spring_fanout_exchange", "", "发送到spring_fanout_exchange交换机的广播消息");
  }

   /**
    * 通配符
    * 交换机类型为 topic
    * 匹配路由键的通配符,*表示一个单词,#表示多个单词
    * 绑定到该交换机的匹配队列能够收到对应消息
    */
   @Test
   public void topicTest() {
   /**
    * 参数1:交换机名称
    * 参数2:路由键名
    * 参数3:发送的消息内容
    */
       rabbitTemplate.convertAndSend("spring_topic_exchange", "lxs.bj", "发送到spring_topic_exchange交换机lxs.bj的消息");
       rabbitTemplate.convertAndSend("spring_topic_exchange", "lxs.bj.1", "发送到spring_topic_exchange交换机lxs.bj.1的消息");
       rabbitTemplate.convertAndSend("spring_topic_exchange", "lxs.bj.2", "发送到spring_topic_exchange交换机lxs.bj.2的消息");
       rabbitTemplate.convertAndSend("spring_topic_exchange", "xzk.cn", "发送到spring_topic_exchange交换机xzk.cn的消息");
  }
   /**
    * 确认模式:
    * 步骤:
    * 1. 确认模式开启:ConnectionFactory中开启publisher-confirms="true"
    * 2. 在rabbitTemplate定义ConfirmCallBack回调函数
    */
   @Test
   public void testConfirm() {
       //2. 定义回调
       rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
           /**
            *
            * @param correlationData 相关配置信息
            * @param ack exchange交换机 是否成功收到了消息。true 成功,false代表失败
            * @param cause 失败原因
            */
           @Override
           public void confirm(CorrelationData correlationData, boolean ack, String cause) {
               System.out.println("confirm方法被执行了....");
               if (ack) {
                   //接收成功
                   System.out.println("接收成功消息" + cause);
              } else {
                   //接收失败
                   System.out.println("接收失败消息" + cause);
                   //做一些处理,让消息再次发送。
              }
          }
      });
       //3. 发送消息
       rabbitTemplate.convertAndSend("test_exchange_confirm2", "confirm", "message confirm....");
  }
   /**
    * 回退模式: 当消息发送给Exchange后,Exchange路由到Queue失败是 才会执行 ReturnCallBack
    * 步骤:
    * 1. 开启回退模式:publisher-returns="true"
    * 2. 设置ReturnCallBack
    * 3. 设置Exchange处理消息失败的模式:setMandatory
    * 1. 如果消息没有路由到Queue,则丢弃消息(默认)
    * 2. 如果消息没有路由到Queue,返回给消息发送方ReturnCallBack
    */
   @Test
   public void testReturn() {
       //设置交换机处理失败消息的模式
       rabbitTemplate.setMandatory(true);
       //2.设置ReturnCallBack
       rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
           /**
            *
            * @param message 消息对象
            * @param replyCode 错误码
            * @param replyText 错误信息
            * @param exchange 交换机
            * @param routingKey 路由键
            */
           @Override
           public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
               System.out.println("return 执行了....");
               System.out.println(message);
               System.out.println(replyCode);
               System.out.println(replyText);
               System.out.println(exchange);
               System.out.println(routingKey);
               //处理
          }
      });
       //3. 发送消息
       rabbitTemplate.convertAndSend("test_exchange_confirm", "confirm", "message confirm....");
  }
   
   //新增方法
   @Test
   public void testSend() {
       for (int i = 0; i < 10; i++) {
           rabbitTemplate.convertAndSend("test_exchange_confirm", "confirm", "message confirm...." + i);
      }
  }
}

运行testSend方法和ConsumerTest方法

image-20211211192039575

 

4、TTL

Time To Live,消息过期时间设置

管控台中设置队列TTL

image-20211211193607256

image-20211211193651600

image-20211211193754719

image-20211211193832809

查看消息是否10s后过期

代码实现

修改Producer的sping-rabbitmq.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:context="http://www.springframework.org/schema/context"
      xmlns:rabbit="http://www.springframework.org/schema/rabbit"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/rabbit
http://www.springframework.org/schema/rabbit/spring-rabbit.xsd">
   <!--加载配置文件-->
   <context:property-placeholder location="classpath:properties/rabbitmq.properties"/>
   <!-- 定义rabbitmq connectionFactory -->
   <rabbit:connection-factory id="connectionFactory" host="192.168.88.128"
                              port="${rabbitmq.port}"
                              username="${rabbitmq.username}"
                              password="${rabbitmq.password}"
                              virtual-host="${rabbitmq.virtual-host}"
                              publisher-confirms="true"
                              publisher-returns="true"
   />
   <!--定义管理交换机、队列-->
   <rabbit:admin connection-factory="connectionFactory"/>
   <!--定义持久化队列,不存在则自动创建;不绑定到交换机则绑定到默认交换机
   默认交换机类型为direct,名字为:"",路由键为队列的名称
   -->
   <rabbit:queue id="spring_queue" name="spring_queue" auto-declare="true"/>
   <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~广播;所有队列都能收到消息
   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
   <!--定义广播交换机中的持久化队列,不存在则自动创建-->
   <rabbit:queue id="spring_fanout_queue_1" name="spring_fanout_queue_1" auto-declare="true"/>
   <!--定义广播交换机中的持久化队列,不存在则自动创建-->
   <rabbit:queue id="spring_fanout_queue_2" name="spring_fanout_queue_2" auto-declare="true"/>
   <!--定义广播类型交换机;并绑定上述两个队列-->
   <rabbit:fanout-exchange id="spring_fanout_exchange" name="spring_fanout_exchange" auto-declare="true">
       <rabbit:bindings>
           <rabbit:binding queue="spring_fanout_queue_1"/>
           <rabbit:binding queue="spring_fanout_queue_2"/>
       </rabbit:bindings>
   </rabbit:fanout-exchange>
   <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~通配符;*匹配一个单词,#匹配多个单词
   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
   <!--定义广播交换机中的持久化队列,不存在则自动创建-->
   <rabbit:queue id="spring_topic_queue_star" name="spring_topic_queue_star" auto-declare="true"/>
   <!--定义广播交换机中的持久化队列,不存在则自动创建-->
   <rabbit:queue id="spring_topic_queue_well" name="spring_topic_queue_well" auto-declare="true"/>
   <!--定义广播交换机中的持久化队列,不存在则自动创建-->
   <rabbit:queue id="spring_topic_queue_well2" name="spring_topic_queue_well2" auto-declare="true"/>
   <rabbit:topic-exchange id="spring_topic_exchange" name="spring_topic_exchange" auto-declare="true">
       <rabbit:bindings>
           <rabbit:binding pattern="lxs.*" queue="spring_topic_queue_star"/>
           <rabbit:binding pattern="lxs.#" queue="spring_topic_queue_well"/>
           <rabbit:binding pattern="xzk.#" queue="spring_topic_queue_well2"/>
       </rabbit:bindings>
   </rabbit:topic-exchange>
   <!--定义rabbitTemplate对象操作可以在代码中方便发送消息-->
   <rabbit:template id="rabbitTemplate" connection-factory="connectionFactory"/>
   <!--消息可靠性投递(生产端)-->
   <rabbit:queue id="test_queue_confirm" name="test_queue_confirm"></rabbit:queue>
   <rabbit:direct-exchange name="test_exchange_confirm">
       <rabbit:bindings>
           <rabbit:binding queue="test_queue_confirm" key="confirm"></rabbit:binding>
       </rabbit:bindings>
   </rabbit:direct-exchange>

   <!--ttl-->
   <rabbit:queue name="test_queue_ttl" id="test_queue_ttl">
       <rabbit:queue-arguments>
           <entry key="x-message-ttl" value="100000" value-type="java.lang.Integer"></entry>
       </rabbit:queue-arguments>
   </rabbit:queue>
<!-- 新增内容 -->
   <rabbit:topic-exchange name="test_exchange_ttl">
       <rabbit:bindings>
           <rabbit:binding pattern="ttl.#" queue="test_queue_ttl"></rabbit:binding>
       </rabbit:bindings>
   </rabbit:topic-exchange>
</beans>

添加测试方法

package com.lxs.rabbitmq;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/spring-rabbitmq.xml")
public class ProducerTest {
   @Autowired
   private RabbitTemplate rabbitTemplate;

   /**
    * 只发队列消息
    * 默认交换机类型为 direct
    * 交换机的名称为空,路由键为队列的名称
    */
   @Test
   public void queueTest() {
       //路由键与队列同名
       rabbitTemplate.convertAndSend("spring_queue", "只发队列spring_queue的消息。");
  }

   /**
    * 发送广播
    * 交换机类型为 fanout
    * 绑定到该交换机的所有队列都能够收到消息
    */
   @Test
   public void fanoutTest() {
   /**
    * 参数1:交换机名称
    * 参数2:路由键名(广播设置为空)
    * 参数3:发送的消息内容
    */
       rabbitTemplate.convertAndSend("spring_fanout_exchange", "", "发送到spring_fanout_exchange交换机的广播消息");
  }

   /**
    * 通配符
    * 交换机类型为 topic
    * 匹配路由键的通配符,*表示一个单词,#表示多个单词
    * 绑定到该交换机的匹配队列能够收到对应消息
    */
   @Test
   public void topicTest() {
   /**
    * 参数1:交换机名称
    * 参数2:路由键名
    * 参数3:发送的消息内容
    */
       rabbitTemplate.convertAndSend("spring_topic_exchange", "lxs.bj", "发送到spring_topic_exchange交换机lxs.bj的消息");
       rabbitTemplate.convertAndSend("spring_topic_exchange", "lxs.bj.1", "发送到spring_topic_exchange交换机lxs.bj.1的消息");
       rabbitTemplate.convertAndSend("spring_topic_exchange", "lxs.bj.2", "发送到spring_topic_exchange交换机lxs.bj.2的消息");
       rabbitTemplate.convertAndSend("spring_topic_exchange", "xzk.cn", "发送到spring_topic_exchange交换机xzk.cn的消息");
  }
   /**
    * 确认模式:
    * 步骤:
    * 1. 确认模式开启:ConnectionFactory中开启publisher-confirms="true"
    * 2. 在rabbitTemplate定义ConfirmCallBack回调函数
    */
   @Test
   public void testConfirm() {
       //2. 定义回调
       rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
           /**
            *
            * @param correlationData 相关配置信息
            * @param ack exchange交换机 是否成功收到了消息。true 成功,false代表失败
            * @param cause 失败原因
            */
           @Override
           public void confirm(CorrelationData correlationData, boolean ack, String cause) {
               System.out.println("confirm方法被执行了....");
               if (ack) {
                   //接收成功
                   System.out.println("接收成功消息" + cause);
              } else {
                   //接收失败
                   System.out.println("接收失败消息" + cause);
                   //做一些处理,让消息再次发送。
              }
          }
      });
       //3. 发送消息
       rabbitTemplate.convertAndSend("test_exchange_confirm2", "confirm", "message confirm....");
  }
   /**
    * 回退模式: 当消息发送给Exchange后,Exchange路由到Queue失败是 才会执行 ReturnCallBack
    * 步骤:
    * 1. 开启回退模式:publisher-returns="true"
    * 2. 设置ReturnCallBack
    * 3. 设置Exchange处理消息失败的模式:setMandatory
    * 1. 如果消息没有路由到Queue,则丢弃消息(默认)
    * 2. 如果消息没有路由到Queue,返回给消息发送方ReturnCallBack
    */
   @Test
   public void testReturn() {
       //设置交换机处理失败消息的模式
       rabbitTemplate.setMandatory(true);
       //2.设置ReturnCallBack
       rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
           /**
            *
            * @param message 消息对象
            * @param replyCode 错误码
            * @param replyText 错误信息
            * @param exchange 交换机
            * @param routingKey 路由键
            */
           @Override
           public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
               System.out.println("return 执行了....");
               System.out.println(message);
               System.out.println(replyCode);
               System.out.println(replyText);
               System.out.println(exchange);
               System.out.println(routingKey);
               //处理
          }
      });
       //3. 发送消息
       rabbitTemplate.convertAndSend("test_exchange_confirm", "confirm", "message confirm....");
  }
   @Test
   public void testSend() {
       for (int i = 0; i < 10; i++) {
           rabbitTemplate.convertAndSend("test_exchange_confirm", "confirm", "message confirm...." + i);
      }
  }
   /**
    * TTL:过期时间
    * 1. 队列统一过期
    *
    * 2. 消息单独过期
    *
    *
    * 如果设置了消息的过期时间,也设置了队列的过期时间,它以时间短的为准。
    * 队列过期后,会将队列所有消息全部移除。
    * 消息过期后,只有消息在队列顶端,才会判断其是否过期(移除掉)
    *
    */
   @Test
   public void testTtl() {

       for (int i = 0; i < 10; i++) {
           // 发送消息
           rabbitTemplate.convertAndSend("test_exchange_ttl", "ttl.hehe", "message ttl....");
      }

//       // 消息后处理对象,设置一些消息的参数信息
//       MessagePostProcessor messagePostProcessor = new MessagePostProcessor() {
//
//           @Override
//           public Message postProcessMessage(Message message) throws AmqpException {
//               //1.设置message的信息
//               message.getMessageProperties().setExpiration("5000");//消息的过期时间
//               //2.返回该消息
//               return message;
//           }
//       };
//       //消息单独过期
//       rabbitTemplate.convertAndSend("test_exchange_ttl", "ttl.hehe", "message ttl....", messagePostProcessor);


//       for (int i = 0; i < 10; i++) {
//           if(i == 5){
//               //消息单独过期
//               rabbitTemplate.convertAndSend("test_exchange_ttl", "ttl.hehe", "message ttl....",messagePostProcessor);
//           }else{
//               //不过期的消息
//               rabbitTemplate.convertAndSend("test_exchange_ttl", "ttl.hehe", "message ttl....");
//
//           }
//
//       }
  }
}

5、死信队列

死信队列,英文缩写:DLX 。Dead Letter Exchange(死信交换机),当消息成为Dead message后,可以被重新发送到另一个交换机,这个交换机就是DLX。

image-20211212085239108

消息成为死信的三种情况:

  1. 队列消息长度到达限制;

  2. 消费者拒接消费消息,basicNack/basicReject,并且不把消息重新放入原目标队列,requeue=false;

  3. 原队列存在消息过期设置,消息到达超时时间未被消费;

队列绑定死信交换机:

给队列设置参数: x-dead-letter-exchange 和 x-dead-letter-routing-key

image-20211212085334068

管控台配置死信队列

添加死信队列

image-20211212085507677

添加死信交换机

image-20211212085631437

死信交换机绑定死信队列

image-20211212085747685

添加正常队列

image-20211212085907845

添加正常交换机

image-20211212085948188

正常队列绑定正常交换机

image-20211212090037701

在正常交换机发送消息

image-20211212090128429

查看queues界面变化

代码实现

修改spring-producer的spring-rabbitmq.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:context="http://www.springframework.org/schema/context"
      xmlns:rabbit="http://www.springframework.org/schema/rabbit"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/rabbit
http://www.springframework.org/schema/rabbit/spring-rabbit.xsd">
   <!--加载配置文件-->
   <context:property-placeholder location="classpath:properties/rabbitmq.properties"/>
   <!-- 定义rabbitmq connectionFactory -->
   <rabbit:connection-factory id="connectionFactory" host="192.168.88.128"
                              port="${rabbitmq.port}"
                              username="${rabbitmq.username}"
                              password="${rabbitmq.password}"
                              virtual-host="${rabbitmq.virtual-host}"
                              publisher-confirms="true"
                              publisher-returns="true"
   />
   <!--定义管理交换机、队列-->
   <rabbit:admin connection-factory="connectionFactory"/>
   <!--定义持久化队列,不存在则自动创建;不绑定到交换机则绑定到默认交换机
   默认交换机类型为direct,名字为:"",路由键为队列的名称
   -->
   <rabbit:queue id="spring_queue" name="spring_queue" auto-declare="true"/>
   <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~广播;所有队列都能收到消息
   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
   <!--定义广播交换机中的持久化队列,不存在则自动创建-->
   <rabbit:queue id="spring_fanout_queue_1" name="spring_fanout_queue_1" auto-declare="true"/>
   <!--定义广播交换机中的持久化队列,不存在则自动创建-->
   <rabbit:queue id="spring_fanout_queue_2" name="spring_fanout_queue_2" auto-declare="true"/>
   <!--定义广播类型交换机;并绑定上述两个队列-->
   <rabbit:fanout-exchange id="spring_fanout_exchange" name="spring_fanout_exchange" auto-declare="true">
       <rabbit:bindings>
           <rabbit:binding queue="spring_fanout_queue_1"/>
           <rabbit:binding queue="spring_fanout_queue_2"/>
       </rabbit:bindings>
   </rabbit:fanout-exchange>
   <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~通配符;*匹配一个单词,#匹配多个单词
   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
   <!--定义广播交换机中的持久化队列,不存在则自动创建-->
   <rabbit:queue id="spring_topic_queue_star" name="spring_topic_queue_star" auto-declare="true"/>
   <!--定义广播交换机中的持久化队列,不存在则自动创建-->
   <rabbit:queue id="spring_topic_queue_well" name="spring_topic_queue_well" auto-declare="true"/>
   <!--定义广播交换机中的持久化队列,不存在则自动创建-->
   <rabbit:queue id="spring_topic_queue_well2" name="spring_topic_queue_well2" auto-declare="true"/>
   <rabbit:topic-exchange id="spring_topic_exchange" name="spring_topic_exchange" auto-declare="true">
       <rabbit:bindings>
           <rabbit:binding pattern="lxs.*" queue="spring_topic_queue_star"/>
           <rabbit:binding pattern="lxs.#" queue="spring_topic_queue_well"/>
           <rabbit:binding pattern="xzk.#" queue="spring_topic_queue_well2"/>
       </rabbit:bindings>
   </rabbit:topic-exchange>
   <!--定义rabbitTemplate对象操作可以在代码中方便发送消息-->
   <rabbit:template id="rabbitTemplate" connection-factory="connectionFactory"/>
   <!--消息可靠性投递(生产端)-->
   <rabbit:queue id="test_queue_confirm" name="test_queue_confirm"></rabbit:queue>
   <rabbit:direct-exchange name="test_exchange_confirm">
       <rabbit:bindings>
           <rabbit:binding queue="test_queue_confirm" key="confirm"></rabbit:binding>
       </rabbit:bindings>
   </rabbit:direct-exchange>

   <!--ttl-->
   <rabbit:queue name="test_queue_ttl" id="test_queue_ttl">
       <rabbit:queue-arguments>
           <entry key="x-message-ttl" value="100000" value-type="java.lang.Integer"></entry>
       </rabbit:queue-arguments>
   </rabbit:queue>

   <rabbit:topic-exchange name="test_exchange_ttl">
       <rabbit:bindings>
           <rabbit:binding pattern="ttl.#" queue="test_queue_ttl"></rabbit:binding>
       </rabbit:bindings>
   </rabbit:topic-exchange>
   
   <!-- 添加内容 -->

   <!--
       1. 声明正常的队列(test_queue_dlx)和交换机(test_exchange_dlx)
   -->
   <rabbit:queue name="test_queue_dlx" id="test_queue_dlx">
       <!--3. 正常队列绑定死信交换机-->
       <rabbit:queue-arguments>
           <!--3.1 x-dead-letter-exchange:死信交换机名称-->
           <entry key="x-dead-letter-exchange" value="exchange_dlx" />

           <!--3.2 x-dead-letter-routing-key:发送给死信交换机的routingkey-->
           <entry key="x-dead-letter-routing-key" value="dlx.hehe" />

           <!--4.1 设置队列的过期时间 ttl-->
           <entry key="x-message-ttl" value="10000" value-type="java.lang.Integer" />
           <!--4.2 设置队列的长度限制 max-length -->
           <entry key="x-max-length" value="10" value-type="java.lang.Integer" />
       </rabbit:queue-arguments>
   </rabbit:queue>
   <rabbit:topic-exchange name="test_exchange_dlx">
       <rabbit:bindings>
           <rabbit:binding pattern="test.dlx.#" queue="test_queue_dlx"></rabbit:binding>
       </rabbit:bindings>
   </rabbit:topic-exchange>

   <!--
      2. 声明死信队列(queue_dlx)和死信交换机(exchange_dlx)
    -->
   <rabbit:queue name="queue_dlx" id="queue_dlx"></rabbit:queue>

   <rabbit:topic-exchange name="exchange_dlx">
       <rabbit:bindings>
           <rabbit:binding pattern="dlx.#" queue="queue_dlx"></rabbit:binding>
       </rabbit:bindings>
   </rabbit:topic-exchange>
</beans>

ProducerTest添加测试方法

package com.lxs.rabbitmq;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/spring-rabbitmq.xml")
public class ProducerTest {
   @Autowired
   private RabbitTemplate rabbitTemplate;

   /**
    * 只发队列消息
    * 默认交换机类型为 direct
    * 交换机的名称为空,路由键为队列的名称
    */
   @Test
   public void queueTest() {
       //路由键与队列同名
       rabbitTemplate.convertAndSend("spring_queue", "只发队列spring_queue的消息。");
  }

   /**
    * 发送广播
    * 交换机类型为 fanout
    * 绑定到该交换机的所有队列都能够收到消息
    */
   @Test
   public void fanoutTest() {
       /**
        * 参数1:交换机名称
        * 参数2:路由键名(广播设置为空)
        * 参数3:发送的消息内容
        */
       rabbitTemplate.convertAndSend("spring_fanout_exchange", "", "发送到spring_fanout_exchange交换机的广播消息");
  }

   /**
    * 通配符
    * 交换机类型为 topic
    * 匹配路由键的通配符,*表示一个单词,#表示多个单词
    * 绑定到该交换机的匹配队列能够收到对应消息
    */
   @Test
   public void topicTest() {
       /**
        * 参数1:交换机名称
        * 参数2:路由键名
        * 参数3:发送的消息内容
        */
       rabbitTemplate.convertAndSend("spring_topic_exchange", "lxs.bj", "发送到spring_topic_exchange交换机lxs.bj的消息");
       rabbitTemplate.convertAndSend("spring_topic_exchange", "lxs.bj.1", "发送到spring_topic_exchange交换机lxs.bj.1的消息");
       rabbitTemplate.convertAndSend("spring_topic_exchange", "lxs.bj.2", "发送到spring_topic_exchange交换机lxs.bj.2的消息");
       rabbitTemplate.convertAndSend("spring_topic_exchange", "xzk.cn", "发送到spring_topic_exchange交换机xzk.cn的消息");
  }

   /**
    * 确认模式:
    * 步骤:
    * 1. 确认模式开启:ConnectionFactory中开启publisher-confirms="true"
    * 2. 在rabbitTemplate定义ConfirmCallBack回调函数
    */
   @Test
   public void testConfirm() {
       //2. 定义回调
       rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
           /**
            *
            * @param correlationData 相关配置信息
            * @param ack exchange交换机 是否成功收到了消息。true 成功,false代表失败
            * @param cause 失败原因
            */
           @Override
           public void confirm(CorrelationData correlationData, boolean ack, String cause) {
               System.out.println("confirm方法被执行了....");
               if (ack) {
                   //接收成功
                   System.out.println("接收成功消息" + cause);
              } else {
                   //接收失败
                   System.out.println("接收失败消息" + cause);
                   //做一些处理,让消息再次发送。
              }
          }
      });
       //3. 发送消息
       rabbitTemplate.convertAndSend("test_exchange_confirm2", "confirm", "message confirm....");
  }

   /**
    * 回退模式: 当消息发送给Exchange后,Exchange路由到Queue失败是 才会执行 ReturnCallBack
    * 步骤:
    * 1. 开启回退模式:publisher-returns="true"
    * 2. 设置ReturnCallBack
    * 3. 设置Exchange处理消息失败的模式:setMandatory
    * 1. 如果消息没有路由到Queue,则丢弃消息(默认)
    * 2. 如果消息没有路由到Queue,返回给消息发送方ReturnCallBack
    */
   @Test
   public void testReturn() {
       //设置交换机处理失败消息的模式
       rabbitTemplate.setMandatory(true);
       //2.设置ReturnCallBack
       rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
           /**
            *
            * @param message 消息对象
            * @param replyCode 错误码
            * @param replyText 错误信息
            * @param exchange 交换机
            * @param routingKey 路由键
            */
           @Override
           public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
               System.out.println("return 执行了....");
               System.out.println(message);
               System.out.println(replyCode);
               System.out.println(replyText);
               System.out.println(exchange);
               System.out.println(routingKey);
               //处理
          }
      });
       //3. 发送消息
       rabbitTemplate.convertAndSend("test_exchange_confirm", "confirm", "message confirm....");
  }

   @Test
   public void testSend() {
       for (int i = 0; i < 10; i++) {
           rabbitTemplate.convertAndSend("test_exchange_confirm", "confirm", "message confirm...." + i);
      }
  }

   /**
    * TTL:过期时间
    * 1. 队列统一过期
    * <p>
    * 2. 消息单独过期
    * <p>
    * <p>
    * 如果设置了消息的过期时间,也设置了队列的过期时间,它以时间短的为准。
    * 队列过期后,会将队列所有消息全部移除。
    * 消息过期后,只有消息在队列顶端,才会判断其是否过期(移除掉)
    */
   @Test
   public void testTtl() {

       for (int i = 0; i < 10; i++) {
           // 发送消息
           rabbitTemplate.convertAndSend("test_exchange_ttl", "ttl.hehe", "message ttl....");
      }

//       // 消息后处理对象,设置一些消息的参数信息
//       MessagePostProcessor messagePostProcessor = new MessagePostProcessor() {
//
//           @Override
//           public Message postProcessMessage(Message message) throws AmqpException {
//               //1.设置message的信息
//               message.getMessageProperties().setExpiration("5000");//消息的过期时间
//               //2.返回该消息
//               return message;
//           }
//       };
//       //消息单独过期
//       rabbitTemplate.convertAndSend("test_exchange_ttl", "ttl.hehe", "message ttl....", messagePostProcessor);


//       for (int i = 0; i < 10; i++) {
//           if(i == 5){
//               //消息单独过期
//               rabbitTemplate.convertAndSend("test_exchange_ttl", "ttl.hehe", "message ttl....",messagePostProcessor);
//           }else{
//               //不过期的消息
//               rabbitTemplate.convertAndSend("test_exchange_ttl", "ttl.hehe", "message ttl....");
//
//           }
//
//       }
  }

   //添加内容
   /**
    * 发送测试死信消息:
    * 1. 过期时间
    * 2. 长度限制
    * 3. 消息拒收
    */
   @Test
   public void testDlx() {
       //1. 测试过期时间,死信消息
//       rabbitTemplate.convertAndSend("test_exchange_dlx", "test.dlx.haha", "我是一条消息,我会死吗?");
       //2. 测试长度限制后,消息死信
//       for (int i = 0; i < 20; i++) {
//           rabbitTemplate.convertAndSend("test_exchange_dlx", "test.dlx.haha", "我是一条消息,我会死吗?");
//       }
//       //3. 测试消息拒收
       rabbitTemplate.convertAndSend("test_exchange_dlx", "test.dlx.haha", "我是一条消息,我会死吗?");
  }
}

先进行1和2的测试,测试完毕后在spring-consumer端添加DlsListener

package com.lxs.listener;

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

@Component
public class DlxListener implements ChannelAwareMessageListener {
   @Override
   public void onMessage(Message message, Channel channel) throws Exception {
       long deliveryTag = message.getMessageProperties().getDeliveryTag();
       try {
           //1.接收转换消息
           System.out.println(new String(message.getBody()));
           //2. 处理业务逻辑
           System.out.println("处理业务逻辑...");
           int i = 3 / 0;//出现错误
           //3. 手动签收
           channel.basicAck(deliveryTag, true);
      } catch (Exception e) {
           //e.printStackTrace();
           System.out.println("出现异常,拒绝接受");
           //4.拒绝签收,不重回队列 requeue=false
           channel.basicNack(deliveryTag, true, false);
      }
  }
}

修改spring-consumer的sping-rabbitmq.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:context="http://www.springframework.org/schema/context"
      xmlns:rabbit="http://www.springframework.org/schema/rabbit"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/rabbit
http://www.springframework.org/schema/rabbit/spring-rabbit.xsd">
   <!--加载配置文件-->
   <context:property-placeholder location="classpath:properties/rabbitmq.properties"/>
   <!-- 定义rabbitmq connectionFactory -->
   <rabbit:connection-factory id="connectionFactory" host="${rabbitmq.host}"
                              port="${rabbitmq.port}"
                              username="${rabbitmq.username}"
                              password="${rabbitmq.password}"
                              virtual-host="${rabbitmq.virtual-host}"/>
   <bean id="springQueueListener" class="com.lxs.rabbitmq.listener.SpringQueueListener"/>
   <bean id="fanoutListener1" class="com.lxs.rabbitmq.listener.FanoutListener1"/>
   <bean id="fanoutListener2" class="com.lxs.rabbitmq.listener.FanoutListener2"/>
   <bean id="topicListenerStar" class="com.lxs.rabbitmq.listener.TopicListenerStar"/>
   <bean id="topicListenerWell" class="com.lxs.rabbitmq.listener.TopicListenerWell"/>
   <bean id="topicListenerWell2" class="com.lxs.rabbitmq.listener.TopicListenerWell2"/>
   <rabbit:listener-container connection-factory="connectionFactory" auto-declare="true">
       <rabbit:listener ref="springQueueListener" queue-names="spring_queue"/>
       <rabbit:listener ref="fanoutListener1" queue-names="spring_fanout_queue_1"/>
       <rabbit:listener ref="fanoutListener2" queue-names="spring_fanout_queue_2"/>
       <rabbit:listener ref="topicListenerStar" queue-names="spring_topic_queue_star"/>
       <rabbit:listener ref="topicListenerWell" queue-names="spring_topic_queue_well"/>
       <rabbit:listener ref="topicListenerWell2" queue-names="spring_topic_queue_well2"/>
   </rabbit:listener-container>


   <context:component-scan base-package="com.lxs.listener"/>

   <!-- 添加内容 -->
   <rabbit:listener-container connection-factory="connectionFactory" acknowledge="manual">
       <!--       <rabbit:listener ref="ackListener" queue-names="test_queue_confirm"></rabbit:listener>-->
       <!--       <rabbit:listener ref="qosListener" queue-names="test_queue_confirm"></rabbit:listener>-->
       <rabbit:listener ref="dlxListener" queue-names="test_queue_dlx"></rabbit:listener>
       <!--       <rabbit:listener ref="orderListener" queue-names="order_queue_dlx"></rabbit:listener>-->
   </rabbit:listener-container>
</beans>

先启动消费端的ConsumerTest测试,再启动生产端的第三种测试

6、延迟队列

延迟队列,即消息进入队列后不会立即被消费,只有到达指定时间后,才会被消费。

需求:

  • 下单后,30分钟未支付,取消订单,回滚库存。

  • 新用户注册成功7天后,发送短信问候。

实现方式:

  • 定时器

  • 延迟队列

image-20211212092752725

很可惜,在RabbitMQ中并未提供延迟队列功能。但是可以使用:TTL+死信队列 组合实现延迟队列的效果。

image-20211212092816580

代码实现

修改Producer的spring-rabbitmq.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:context="http://www.springframework.org/schema/context"
      xmlns:rabbit="http://www.springframework.org/schema/rabbit"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/rabbit
http://www.springframework.org/schema/rabbit/spring-rabbit.xsd">
   <!--加载配置文件-->
   <context:property-placeholder location="classpath:properties/rabbitmq.properties"/>
   <!-- 定义rabbitmq connectionFactory -->
   <rabbit:connection-factory id="connectionFactory" host="192.168.88.128"
                              port="${rabbitmq.port}"
                              username="${rabbitmq.username}"
                              password="${rabbitmq.password}"
                              virtual-host="${rabbitmq.virtual-host}"
                              publisher-confirms="true"
                              publisher-returns="true"
   />
   <!--定义管理交换机、队列-->
   <rabbit:admin connection-factory="connectionFactory"/>
   <!--定义持久化队列,不存在则自动创建;不绑定到交换机则绑定到默认交换机
   默认交换机类型为direct,名字为:"",路由键为队列的名称
   -->
   <rabbit:queue id="spring_queue" name="spring_queue" auto-declare="true"/>
   <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~广播;所有队列都能收到消息
   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
   <!--定义广播交换机中的持久化队列,不存在则自动创建-->
   <rabbit:queue id="spring_fanout_queue_1" name="spring_fanout_queue_1" auto-declare="true"/>
   <!--定义广播交换机中的持久化队列,不存在则自动创建-->
   <rabbit:queue id="spring_fanout_queue_2" name="spring_fanout_queue_2" auto-declare="true"/>
   <!--定义广播类型交换机;并绑定上述两个队列-->
   <rabbit:fanout-exchange id="spring_fanout_exchange" name="spring_fanout_exchange" auto-declare="true">
       <rabbit:bindings>
           <rabbit:binding queue="spring_fanout_queue_1"/>
           <rabbit:binding queue="spring_fanout_queue_2"/>
       </rabbit:bindings>
   </rabbit:fanout-exchange>
   <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~通配符;*匹配一个单词,#匹配多个单词
   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
   <!--定义广播交换机中的持久化队列,不存在则自动创建-->
   <rabbit:queue id="spring_topic_queue_star" name="spring_topic_queue_star" auto-declare="true"/>
   <!--定义广播交换机中的持久化队列,不存在则自动创建-->
   <rabbit:queue id="spring_topic_queue_well" name="spring_topic_queue_well" auto-declare="true"/>
   <!--定义广播交换机中的持久化队列,不存在则自动创建-->
   <rabbit:queue id="spring_topic_queue_well2" name="spring_topic_queue_well2" auto-declare="true"/>
   <rabbit:topic-exchange id="spring_topic_exchange" name="spring_topic_exchange" auto-declare="true">
       <rabbit:bindings>
           <rabbit:binding pattern="lxs.*" queue="spring_topic_queue_star"/>
           <rabbit:binding pattern="lxs.#" queue="spring_topic_queue_well"/>
           <rabbit:binding pattern="xzk.#" queue="spring_topic_queue_well2"/>
       </rabbit:bindings>
   </rabbit:topic-exchange>
   <!--定义rabbitTemplate对象操作可以在代码中方便发送消息-->
   <rabbit:template id="rabbitTemplate" connection-factory="connectionFactory"/>
   <!--消息可靠性投递(生产端)-->
   <rabbit:queue id="test_queue_confirm" name="test_queue_confirm"></rabbit:queue>
   <rabbit:direct-exchange name="test_exchange_confirm">
       <rabbit:bindings>
           <rabbit:binding queue="test_queue_confirm" key="confirm"></rabbit:binding>
       </rabbit:bindings>
   </rabbit:direct-exchange>

   <!--ttl-->
   <rabbit:queue name="test_queue_ttl" id="test_queue_ttl">
       <rabbit:queue-arguments>
           <entry key="x-message-ttl" value="100000" value-type="java.lang.Integer"></entry>
       </rabbit:queue-arguments>
   </rabbit:queue>

   <rabbit:topic-exchange name="test_exchange_ttl">
       <rabbit:bindings>
           <rabbit:binding pattern="ttl.#" queue="test_queue_ttl"></rabbit:binding>
       </rabbit:bindings>
   </rabbit:topic-exchange>

   <!--
       1. 声明正常的队列(test_queue_dlx)和交换机(test_exchange_dlx)
   -->
   <rabbit:queue name="test_queue_dlx" id="test_queue_dlx">
       <!--3. 正常队列绑定死信交换机-->
       <rabbit:queue-arguments>
           <!--3.1 x-dead-letter-exchange:死信交换机名称-->
           <entry key="x-dead-letter-exchange" value="exchange_dlx" />

           <!--3.2 x-dead-letter-routing-key:发送给死信交换机的routingkey-->
           <entry key="x-dead-letter-routing-key" value="dlx.hehe" />

           <!--4.1 设置队列的过期时间 ttl-->
           <entry key="x-message-ttl" value="10000" value-type="java.lang.Integer" />
           <!--4.2 设置队列的长度限制 max-length -->
           <entry key="x-max-length" value="10" value-type="java.lang.Integer" />
       </rabbit:queue-arguments>
   </rabbit:queue>
   <rabbit:topic-exchange name="test_exchange_dlx">
       <rabbit:bindings>
           <rabbit:binding pattern="test.dlx.#" queue="test_queue_dlx"></rabbit:binding>
       </rabbit:bindings>
   </rabbit:topic-exchange>

   <!--
      2. 声明死信队列(queue_dlx)和死信交换机(exchange_dlx)
    -->
   <rabbit:queue name="queue_dlx" id="queue_dlx"></rabbit:queue>

   <rabbit:topic-exchange name="exchange_dlx">
       <rabbit:bindings>
           <rabbit:binding pattern="dlx.#" queue="queue_dlx"></rabbit:binding>
       </rabbit:bindings>
   </rabbit:topic-exchange>
   
   <!-- 新增内容 -->

   <!--
      延迟队列:
          1. 定义正常交换机(order_exchange)和队列(order_queue)
          2. 定义死信交换机(order_exchange_dlx)和队列(order_queue_dlx)
          3. 绑定,设置正常队列过期时间为30分钟
  -->
   <!-- 1. 定义正常交换机(order_exchange)和队列(order_queue)-->
   <rabbit:queue id="order_queue" name="order_queue">
       <!-- 3. 绑定,设置正常队列过期时间为30分钟-->
       <rabbit:queue-arguments>
           <entry key="x-dead-letter-exchange" value="order_exchange_dlx" />
           <entry key="x-dead-letter-routing-key" value="dlx.order.cancel" />
           <entry key="x-message-ttl" value="10000" value-type="java.lang.Integer" />
       </rabbit:queue-arguments>
   </rabbit:queue>
   <rabbit:topic-exchange name="order_exchange">
       <rabbit:bindings>
           <rabbit:binding pattern="order.#" queue="order_queue"></rabbit:binding>
       </rabbit:bindings>
   </rabbit:topic-exchange>

   <!-- 2. 定义死信交换机(order_exchange_dlx)和队列(order_queue_dlx)-->
   <rabbit:queue id="order_queue_dlx" name="order_queue_dlx"></rabbit:queue>

   <rabbit:topic-exchange name="order_exchange_dlx">
       <rabbit:bindings>
           <rabbit:binding pattern="dlx.order.#" queue="order_queue_dlx"></rabbit:binding>
       </rabbit:bindings>
   </rabbit:topic-exchange>

</beans>

在ProducerTest添加测试方法

package com.lxs.rabbitmq;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:spring/spring-rabbitmq.xml")
public class ProducerTest {
   @Autowired
   private RabbitTemplate rabbitTemplate;

   /**
    * 只发队列消息
    * 默认交换机类型为 direct
    * 交换机的名称为空,路由键为队列的名称
    */
   @Test
   public void queueTest() {
       //路由键与队列同名
       rabbitTemplate.convertAndSend("spring_queue", "只发队列spring_queue的消息。");
  }

   /**
    * 发送广播
    * 交换机类型为 fanout
    * 绑定到该交换机的所有队列都能够收到消息
    */
   @Test
   public void fanoutTest() {
       /**
        * 参数1:交换机名称
        * 参数2:路由键名(广播设置为空)
        * 参数3:发送的消息内容
        */
       rabbitTemplate.convertAndSend("spring_fanout_exchange", "", "发送到spring_fanout_exchange交换机的广播消息");
  }

   /**
    * 通配符
    * 交换机类型为 topic
    * 匹配路由键的通配符,*表示一个单词,#表示多个单词
    * 绑定到该交换机的匹配队列能够收到对应消息
    */
   @Test
   public void topicTest() {
       /**
        * 参数1:交换机名称
        * 参数2:路由键名
        * 参数3:发送的消息内容
        */
       rabbitTemplate.convertAndSend("spring_topic_exchange", "lxs.bj", "发送到spring_topic_exchange交换机lxs.bj的消息");
       rabbitTemplate.convertAndSend("spring_topic_exchange", "lxs.bj.1", "发送到spring_topic_exchange交换机lxs.bj.1的消息");
       rabbitTemplate.convertAndSend("spring_topic_exchange", "lxs.bj.2", "发送到spring_topic_exchange交换机lxs.bj.2的消息");
       rabbitTemplate.convertAndSend("spring_topic_exchange", "xzk.cn", "发送到spring_topic_exchange交换机xzk.cn的消息");
  }

   /**
    * 确认模式:
    * 步骤:
    * 1. 确认模式开启:ConnectionFactory中开启publisher-confirms="true"
    * 2. 在rabbitTemplate定义ConfirmCallBack回调函数
    */
   @Test
   public void testConfirm() {
       //2. 定义回调
       rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
           /**
            *
            * @param correlationData 相关配置信息
            * @param ack exchange交换机 是否成功收到了消息。true 成功,false代表失败
            * @param cause 失败原因
            */
           @Override
           public void confirm(CorrelationData correlationData, boolean ack, String cause) {
               System.out.println("confirm方法被执行了....");
               if (ack) {
                   //接收成功
                   System.out.println("接收成功消息" + cause);
              } else {
                   //接收失败
                   System.out.println("接收失败消息" + cause);
                   //做一些处理,让消息再次发送。
              }
          }
      });
       //3. 发送消息
       rabbitTemplate.convertAndSend("test_exchange_confirm2", "confirm", "message confirm....");
  }

   /**
    * 回退模式: 当消息发送给Exchange后,Exchange路由到Queue失败是 才会执行 ReturnCallBack
    * 步骤:
    * 1. 开启回退模式:publisher-returns="true"
    * 2. 设置ReturnCallBack
    * 3. 设置Exchange处理消息失败的模式:setMandatory
    * 1. 如果消息没有路由到Queue,则丢弃消息(默认)
    * 2. 如果消息没有路由到Queue,返回给消息发送方ReturnCallBack
    */
   @Test
   public void testReturn() {
       //设置交换机处理失败消息的模式
       rabbitTemplate.setMandatory(true);
       //2.设置ReturnCallBack
       rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
           /**
            *
            * @param message 消息对象
            * @param replyCode 错误码
            * @param replyText 错误信息
            * @param exchange 交换机
            * @param routingKey 路由键
            */
           @Override
           public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
               System.out.println("return 执行了....");
               System.out.println(message);
               System.out.println(replyCode);
               System.out.println(replyText);
               System.out.println(exchange);
               System.out.println(routingKey);
               //处理
          }
      });
       //3. 发送消息
       rabbitTemplate.convertAndSend("test_exchange_confirm", "confirm", "message confirm....");
  }

   @Test
   public void testSend() {
       for (int i = 0; i < 10; i++) {
           rabbitTemplate.convertAndSend("test_exchange_confirm", "confirm", "message confirm...." + i);
      }
  }

   /**
    * TTL:过期时间
    * 1. 队列统一过期
    * <p>
    * 2. 消息单独过期
    * <p>
    * <p>
    * 如果设置了消息的过期时间,也设置了队列的过期时间,它以时间短的为准。
    * 队列过期后,会将队列所有消息全部移除。
    * 消息过期后,只有消息在队列顶端,才会判断其是否过期(移除掉)
    */
   @Test
   public void testTtl() {

       for (int i = 0; i < 10; i++) {
           // 发送消息
           rabbitTemplate.convertAndSend("test_exchange_ttl", "ttl.hehe", "message ttl....");
      }

//       // 消息后处理对象,设置一些消息的参数信息
//       MessagePostProcessor messagePostProcessor = new MessagePostProcessor() {
//
//           @Override
//           public Message postProcessMessage(Message message) throws AmqpException {
//               //1.设置message的信息
//               message.getMessageProperties().setExpiration("5000");//消息的过期时间
//               //2.返回该消息
//               return message;
//           }
//       };
//       //消息单独过期
//       rabbitTemplate.convertAndSend("test_exchange_ttl", "ttl.hehe", "message ttl....", messagePostProcessor);


//       for (int i = 0; i < 10; i++) {
//           if(i == 5){
//               //消息单独过期
//               rabbitTemplate.convertAndSend("test_exchange_ttl", "ttl.hehe", "message ttl....",messagePostProcessor);
//           }else{
//               //不过期的消息
//               rabbitTemplate.convertAndSend("test_exchange_ttl", "ttl.hehe", "message ttl....");
//
//           }
//
//       }
  }

   /**
    * 发送测试死信消息:
    * 1. 过期时间
    * 2. 长度限制
    * 3. 消息拒收
    */
   @Test
   public void testDlx() {
       //1. 测试过期时间,死信消息
//       rabbitTemplate.convertAndSend("test_exchange_dlx", "test.dlx.haha", "我是一条消息,我会死吗?");
       //2. 测试长度限制后,消息死信
//       for (int i = 0; i < 20; i++) {
//           rabbitTemplate.convertAndSend("test_exchange_dlx", "test.dlx.haha", "我是一条消息,我会死吗?");
//       }
//       //3. 测试消息拒收
       rabbitTemplate.convertAndSend("test_exchange_dlx", "test.dlx.haha", "我是一条消息,我会死吗?");
  }

   // 新增内容
   @Test
   public void testDelay() throws InterruptedException {
       //1.发送订单消息。 将来是在订单系统中,下单成功后,发送消息
       rabbitTemplate.convertAndSend("order_exchange", "order.msg", "订单信息:id=1,time=2019年8月17日16:41:47");
       //2.打印倒计时10秒
       for (int i = 10; i > 0; i--) {
           System.out.println(i + "...");
           Thread.sleep(1000);
      }
  }

}

消费端新增OrderListener

package com.lxs.listener;

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

@Component
public class OrderListener implements ChannelAwareMessageListener {
   @Override
   public void onMessage(Message message, Channel channel) throws Exception {
       long deliveryTag = message.getMessageProperties().getDeliveryTag();
       try {
           //1.接收转换消息
           System.out.println(new String(message.getBody()));
           //2. 处理业务逻辑
           System.out.println("处理业务逻辑...");
           System.out.println("根据订单id查询其状态...");
           System.out.println("判断状态是否为支付成功");
           System.out.println("取消订单,回滚库存....");
           //3. 手动签收
           channel.basicAck(deliveryTag, true);
      } catch (Exception e) {
           //e.printStackTrace();
           System.out.println("出现异常,拒绝接受");
           //4.拒绝签收,不重回队列 requeue=false
           channel.basicNack(deliveryTag, true, false);
      }
  }
}

修改消费端的spring-rabbitmq.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:context="http://www.springframework.org/schema/context"
      xmlns:rabbit="http://www.springframework.org/schema/rabbit"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/rabbit
http://www.springframework.org/schema/rabbit/spring-rabbit.xsd">
   <!--加载配置文件-->
   <context:property-placeholder location="classpath:properties/rabbitmq.properties"/>
   <!-- 定义rabbitmq connectionFactory -->
   <rabbit:connection-factory id="connectionFactory" host="${rabbitmq.host}"
                              port="${rabbitmq.port}"
                              username="${rabbitmq.username}"
                              password="${rabbitmq.password}"
                              virtual-host="${rabbitmq.virtual-host}"/>
   <bean id="springQueueListener" class="com.lxs.rabbitmq.listener.SpringQueueListener"/>
   <bean id="fanoutListener1" class="com.lxs.rabbitmq.listener.FanoutListener1"/>
   <bean id="fanoutListener2" class="com.lxs.rabbitmq.listener.FanoutListener2"/>
   <bean id="topicListenerStar" class="com.lxs.rabbitmq.listener.TopicListenerStar"/>
   <bean id="topicListenerWell" class="com.lxs.rabbitmq.listener.TopicListenerWell"/>
   <bean id="topicListenerWell2" class="com.lxs.rabbitmq.listener.TopicListenerWell2"/>
   <rabbit:listener-container connection-factory="connectionFactory" auto-declare="true">
       <rabbit:listener ref="springQueueListener" queue-names="spring_queue"/>
       <rabbit:listener ref="fanoutListener1" queue-names="spring_fanout_queue_1"/>
       <rabbit:listener ref="fanoutListener2" queue-names="spring_fanout_queue_2"/>
       <rabbit:listener ref="topicListenerStar" queue-names="spring_topic_queue_star"/>
       <rabbit:listener ref="topicListenerWell" queue-names="spring_topic_queue_well"/>
       <rabbit:listener ref="topicListenerWell2" queue-names="spring_topic_queue_well2"/>
   </rabbit:listener-container>


   <context:component-scan base-package="com.lxs.listener"/>
<!-- 新增内容 -->
   <rabbit:listener-container connection-factory="connectionFactory" acknowledge="manual">
       <!--       <rabbit:listener ref="ackListener" queue-names="test_queue_confirm"></rabbit:listener>-->
       <!--       <rabbit:listener ref="qosListener" queue-names="test_queue_confirm"></rabbit:listener>-->
       <!--       <rabbit:listener ref="dlxListener" queue-names="test_queue_dlx"></rabbit:listener>-->
       <rabbit:listener ref="orderListener" queue-names="order_queue_dlx"></rabbit:listener>
   </rabbit:listener-container>
</beans>

先启动消费端的ConsumerTest,再启动生产端的ProducerTest

image-20211212093543603

image-20211212093601913

十、面试题

1、vhost是什么?起什么作用?

vhost 可以理解为虚拟 broker ,即 mini-RabbitMQ server。其内部均含有独⽴的 queue、 exchange 和 binding 等,但最最重要的是,其拥有独⽴的权限系统,可以做到 vhost 范围的 ⽤户控制。当然,从 RabbitMQ 的全局⻆度,vhost 可以作为不同权限隔离的⼿段(⼀个典型 的例⼦就是不同的应⽤可以跑 在不同的 vhost 中)。

2、RabbitMQ有几种广播类型?

三种⼴播模式: ①fanout:所有bind到此exchange的queue都可以接收消息(纯⼴播,绑定到RabbitMQ的接 受者都能收到消息); ②direct:通过routingKey和exchange决定的那个唯⼀的queue可以接收消息; ③topic:所有符合routingKey(此时可以是⼀个表达式)的routingKey所bind的queue可以接 收消息;

3、要保证消息持久化成功的条件有哪些?

①声明队列必须设置持久化durable设置为 true。 ②消息推送投递模式必须设置持久化,deliveryMode设置为2(持久)。

③消息已经到达持久化交换器。 ④消息已经到达持久化队列。 以上四个条件都满⾜才能保证消息持久化成功。

4、如何确保消息正确地发送至RabbitMQ?如何确保消息接收方消费了消息?

1、发送⽅确认模式 ①将信道设置成confirm模式(发送⽅确认模式),则所有在信道上发布的消息都会被指派⼀个 唯⼀的ID。 ②⼀旦消息被投递到⽬的队列后,或者消息被写⼊磁盘后(可持久化的消息),信道会发送⼀个 确认给⽣产者(包含消息唯⼀ ID)。 ③如果RabbitMQ发⽣内部错误从⽽导致消息丢失,会发送⼀条 nack(notacknowledged, 未确认)消息。 ④发送⽅确认模式是异步的,⽣产者应⽤程序在等待确认的同时,可以继续发送消息。当确认 消息到达⽣产者应⽤程序,⽣产者应⽤程序的回调⽅法就会被触发来处理确认消息。 2、接收⽅确认机制 ①消费者接收每⼀条消息后都必须进⾏确认(消息接收和消息确认是两个不同操作)。只有消费 者确认了消息,RabbitMQ 才能安全地把消息从队列中删除。 ②这⾥并没有⽤到超时机制,RabbitMQ仅通过Consumer的连接中断来确认是否需要重新发 送消息。也就是说,只要连接不中断,RabbitMQ给了Consumer⾜够⻓的时间来处理消息。 保证数据的最终⼀致性。 3、下⾯罗列⼏种特殊情况 ①如果消费者接收到消息,在确认之前断开了连接或取消订阅,RabbitMQ会认为消息没有被 分发,然后重新分发给下⼀个订阅的消费者。(可能存在消息重复消费的隐患,需要去重) ②如果消费者接收到消息却没有确认消息,连接也未断开,则RabbitMQ认为该消费者繁忙, 将不会给该消费者分发更多的消息。

5、RabbitMQ有哪些重要的角色?

RabbitMQ中重要的⻆⾊有:⽣产者、消费者和代理: ①⽣产者:消息的创建者,负责创建和推送数据到消息服务器; ②消费者:消息的接收⽅,⽤于处理数据和确认消息; ③代理:就是RabbitMQ本身,⽤于扮演“快递”的⻆⾊,本身不⽣产消息,只是扮演“快递”的 ⻆⾊

6、RabbitMQ的使用场景有哪些?

①跨系统的异步通信,所有需要异步交互的地⽅都可以使⽤消息队列。就像我们除了打电话(同 步)以外,还需要发短信,发电⼦邮件(异步)的通讯⽅式。 ②多个应⽤之间的耦合,由于消息是平台⽆关和语⾔⽆关的,⽽且语义上也不再是函数调⽤, 因此更适合作为多个应⽤之间的松耦合的接⼝。基于消息队列的耦合,不需要发送⽅和接收⽅ 同时在线。在企业应⽤集成(EAI)中,⽂件传输,共享数据库,消息队列,远程过程调⽤都可 以作为集成的⽅法。 ③应⽤内的同步变异步,⽐如订单处理,就可以由前端应⽤将订单信息放到队列,后端应⽤从 队列⾥依次获得消息处理,⾼峰时的⼤量订单可以积压在队列⾥慢慢处理掉。由于同步通常意 味着阻塞,⽽⼤量线程的阻塞会降低计算机的性能。 ④消息驱动的架构(EDA),系统分解为消息队列,和消息制造者和消息消费者,⼀个处理流程 可以根据需要拆成多个阶段(Stage),阶段之间⽤队列连接起来,前⼀个阶段处理的结果放⼊ 队列,后⼀个阶段从队列中获取消息继续处理。 ⑤应⽤需要更灵活的耦合⽅式,如发布订阅,⽐如可以指定路由规则。 ⑥跨局域⽹,甚⾄跨城市的通讯(CDN⾏业),⽐如北京机房与⼴州机房的应⽤程序的通信

7、RabbitMQ如何避免消息丢失?

①消息持久化; ②ACK确认机制; ③设置集群镜像模式; ④消息补偿机制。

8、RabbitMQ的消失是怎么发送的?

⾸先客户端必须连接到 RabbitMQ 服务器才能发布和消费消息,客户端和 rabbit server 之间 会创建⼀ 个 tcp 连接,⼀旦 tcp 打开并通过了认证(认证就是你发送给 rabbit 服务器的⽤户名 和密码),你的 客户端和 RabbitMQ 就创建了⼀条 amqp 信道(channel),信道是创建在 “真实” tcp 上的虚拟连接, amqp 命令都是通过信道发送出去的,每个信道都会有⼀个唯⼀的 id,不论是发布消息,订阅队列都是 通过这个信道完成的。

9、若cluster中拥有某个queue的owner node失效了,且 该queue 被声明具有 durable属性,是否能够成功从其他 node上重新声明该 queue ?

不能,在这种情况下,将得到404 NOT_FOUND错误。只能等queue所 属的node恢复后才能 使⽤该 queue。但若该queue本身不具有durable 属性,则可在其他node上重新声明。

10、客户端连接到cluster中的任意node上是否都能正常⼯ 作?

是的。客户端感觉不到有何不同。

11、在单node系统和多node构成的cluster系统中声明 queue、exchange,以及进⾏ binding会有什么不同?

当你在单node上声明queue时,只要该node上相关元数据进⾏了变 更,你就会得到 Queue.Declareok回应;⽽在cluster上声明queue,则要 求cluster上的全部node都要进⾏ 元数据成功更新,才会得到 Queue.Declare-ok回应。另外,若node类型为RAM node则变更 的数据 仅保存在内存中,若类型为 disk node则还要变更保存在磁盘上的数据。

12、什么是元数据?元数据分为哪些类型?包括哪些内容? 与cluster相关的元数据有哪 些?元数据是如何保存的? 元数据在cluster中是如何分布的?

在⾮cluster模式下,元数据主要分为Queue元数据(queue名字和属性 等)、Exchange元数 据(exchange名字、类型和属性等)、Binding元数据 (存放路由关系的查找表)、Vhost 元数据(vhost范围内针对前三者的名字空 间约束和安全属性设置)。 在cluster模式下,还包括cluster中node位置信息和node关系信息。元数据按照erlang node 的类型确定是仅保存于RAM中,还是同时保存在RAM和disk上。元数据在cluster中是全 node 分布的。

13、RabbitMQ有什么优缺点?

优点:解耦、异步、削峰; 缺点:降低了系统的稳定性:本来系统运⾏好好的,现在你⾮要加⼊个消息队列进去,那消息 队列挂了,你的系统不是呵呵了。因此,系统可⽤性会降低; 增加了系统的复杂性:加⼊了消息队列,要多考虑很多⽅⾯的问题,⽐如:⼀致性问题、如何 保证消息不被重复消费、如何保证消息可靠性传输等。因此,需要考虑的东⻄更多,复杂性增 ⼤。

14、什么是RabbitMQ?为什么使用RabbitMQ?

RabbitMQ是⼀款开源的,Erlang编写的,基于AMQP协议的,消息中间件; 可以⽤它来:解耦、异步、削峰。

15、死信队列和延迟队列的使用

死信消息: 消息被拒绝(Basic.Reject或Basic.Nack)并且设置 requeue 参数的值为 false 消息过期了 队列达到最⼤的⻓度 过期消息: 在 rabbitmq 中存在2种⽅可设置消息的过期时间,第⼀种通过对队列进⾏设置,这种设置 后,该队列中所有的消息都存在相同的过期时间,第⼆种通过对消息本身进⾏设置,那么每条 消息的过期时间都不⼀样。如果同时使⽤这2种⽅法,那么以过期时间⼩的那个数值为准。当 消息达到过期时间还没有被消费,那么那个消息就成为了⼀个 死信 消息。 队列设置:在队列申明的时候使⽤ x-message-ttl 参数,单位为 毫秒

单个消息设置:是设置消息属性的 expiration 参数的值,单位为 毫秒 延时队列:在rabbitmq中不存在延时队列,但是我们可以通过设置消息的过期时间和死信队 列来模拟出延时队列。消费者监听死信交换器绑定的队列,⽽不要监听消息发送的队列。 有了以上的基础知识,我们完成以下需求: 需求:⽤户在系统中创建⼀个订单,如果超过时间⽤户没有进⾏⽀付,那么⾃动取消订单。 分析: 1、上⾯这个情况,我们就适合使⽤延时队列来实现,那么延时队列如何创建 2、延时队列可以由 过期消息+死信队列 来时间 3、过期消息通过队列中设置 x-message-ttl 参数实现 4、死信队列通过在队列申明时,给队列设置 x-dead-letter-exchange 参数,然后另外申明 ⼀个队列绑 定x-dead-letter-exchange对应的交换器。

ConnectionFactory factory = new ConnectionFactory();
factory.setHost("127.0.0.1");
factory.setPort(AMQP.PROTOCOL.PORT);
factory.setUsername("guest");
factory.setPassword("guest");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
// 声明⼀个接收被删除的消息的交换机和队列 String EXCHANGE_DEAD_NAME =
"exchange.dead"; String QUEUE_DEAD_NAME = "queue_dead";
channel.exchangeDeclare(EXCHANGE_DEAD_NAME, BuiltinExchangeType.DIRECT);
channel.queueDeclare(QUEUE_DEAD_NAME, false, false, false, null);
channel.queueBind(QUEUE_DEAD_NAME, EXCHANGE_DEAD_NAME, "routingkey.dead");
String EXCHANGE_NAME = "exchange.fanout";
String QUEUE_NAME = "queue_name";
channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.FANOUT);
Map<String, Object> arguments = new HashMap<String, Object>();
// 统⼀设置队列中的所有消息的过期时间 arguments.put("x-message-ttl", 30000); // 设
置超过多少毫秒没有消费者来访问队列,就删除队列的时间 arguments.put("x-expires",
20000); // 设置队列的最新的N条消息,如果超过N条,前⾯的消息将从队列中移除掉
arguments.put("x-max-length", 4); // 设置队列的内容的最⼤空间,超过该阈值就删除之前
的消息 arguments.put("x-max-length-bytes", 1024); // 将删除的消息推送到指定的交换
机,⼀般x-dead-letter-exchange和x-dead-letterrouting-key需要同时设置
arguments.put("x-dead-letter-exchange", "exchange.dead"); // 将删除的消息推送到
指定的交换机对应的路由键 arguments.put("x-dead-letter-routing-key",
"routingkey.dead"); // 设置消息的优先级,优先级⼤的优先被消费 arguments.put("x-maxpriority", 10); channel.queueDeclare(QUEUE_NAME, false, false, false,
arguments); channel.queueBind(QUEUE_NAME, EXCHANGE_NAME, ""); String message
= "Hello RabbitMQ: ";
for (int i = 1; i <= 5; i++) {
 // expiration: 设置单条消息的过期时间 AMQP.BasicProperties.Builder properties
= new AMQP.BasicProperties().builder() .priority(i).expiration( i * 1000 +
"");
 channel.basicPublish(EXCHANGE_NAME, "", properties.build(), (message +
i).getBytes("UTF-8"));
}
channel.close();
connection.close();

16、如何避免消息重复投递或重复消费?

在消息⽣产时,MQ内部针对每条⽣产者发送的消息⽣成⼀个inner-msg-id,作为去重和幂 等的依据 (消息投递失败并重传),避免重复的消息进⼊队列;在消息消费时,要求消息体中 必须要有⼀个 bizId(对于同⼀业务全局唯⼀,如⽀付ID、订单ID、帖⼦ID等)作为去重和幂 等的依据,避免同⼀条 消息被重复消费。

这个问题针对业务场景来答分以下⼏点: 1.⽐如,你拿到这个消息做数据库的insert操作。那就容易了,给这个消息做⼀个唯⼀主键, 那么就算出现重复消费的情况,就会导致主键冲突,避免数据库出现脏数据。 2.再⽐如,你拿到这个消息做redis的set的操作,那就容易了,不⽤解决,因为你⽆论set⼏次 结果都是⼀样的,set操作本来就算幂等操作。 3.如果上⾯两种情况还不⾏,上⼤招。准备⼀个第三⽅介质,来做消费记录。以redis为例,给 消息分配⼀个全局id,只要消费过该消息,将<id,message>以K-V形式写⼊redis。那消费者 开始消费前,先去redis中查询有没消费记录即可。

17、如何确保消息接收⽅消费了消息?

接收⽅消息确认机制:消费者接收每⼀条消息后都必须进⾏确认(消息接收和消息确认是两个 不同操 作)。只有消费者确认了消息,RabbitMQ才能安全地把消息从队列中删除。这⾥并没 有⽤到超时机 制,RabbitMQ仅通过Consumer的连接中断来确认是否需要重新发送消息。也 就是说,只要连接不中 断,RabbitMQ给了Consumer⾜够⻓的时间来处理消息。

下⾯罗列⼏种特殊情况:

如果消费者接收到消息,在确认之前断开了连接或取消订阅,RabbitMQ会认为消息没有被分 发,然后 重新分发给下⼀个订阅的消费者。(可能存在消息重复消费的隐患,需要根据bizId 去重) 如果消费者 接收到消息却没有确认消息,连接也未断开,则RabbitMQ认为该消费者繁忙,将 不会给该消费者分发 更多的消息。

18、消息怎么路由?

从概念上来说,消息路由必须有三部分:交换器、路由、绑定。⽣产者把消息发布到交换器 上;绑定决 定了消息如何从路由器路由到特定的队列;消息最终到达队列,并被消费者接收。 消息发布到交换器 时,消息将拥有⼀个路由键(routing key),在消息创建时设定。 通过队列路由键,可以把队列绑定到 交换器上。 消息到达交换器后,RabbitMQ会将消息的路由键与队列的路由键进⾏匹配(针对不同的交 换 器有不同的路由规则)。如果能够匹配到队列,则消息会投递到相应队列中;如果不能匹配到 任何 队列,消息将进⼊ “⿊洞”。 常⽤的交换器主要分为⼀下三种:

direct:如果路由键完全匹配,消息就被投递到相应的队列 fanout:如果交换器收到消息,将会⼴播到 所有绑定的队列上 topic:可以使来⾃不同源头的消息能够到达同⼀个队列。 使⽤topic交换器时,可以 使⽤通配 符,⽐如:“*” 匹配特定位置的任意⽂本, “.” 把路由键分为了⼏部分,“#” 匹配所有规则 等。 特别注意:发往topic交换器的消息不能随意的设置选择键(routing_key),必须是 由"."隔开的⼀系列 的标识符组成。

19、消息如何分发?

若该队列⾄少有⼀个消费者订阅,消息将以循环(round-robin)的⽅式发送给消费者。每条 消息只会 分发给⼀个订阅的消费者(前提是消费者能够正常处理消息并进⾏确认)。

20、消息基于什么传输?

由于TCP连接的创建和销毁开销较⼤,且并发数受系统资源限制,会造成性能瓶颈。 RabbitMQ使⽤信 道的⽅式来传输数据。信道是建⽴在真实的TCP连接内的虚拟连接,且每条 TCP连接上的信道数量没有 限制。

posted @ 2021-12-12 09:37  马世凯  阅读(182)  评论(0)    收藏  举报