1.MQ简介

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

2.为什么要用 MQ

1.流量消峰

没使用MQ



使用了MQ

2.应用解耦

3.异步处理

没使用MQ



使用了MQ

3.常见的MQ对比

先学习RabbitMQ,后面可以再学学RocketMQ和Kafka

4.RabbitMQ的安装(linux:centos7环境,我使用的是docker容器进行安装的,也可以使用其他方式 >>>> 非docker方式安装RabbitMQ)

一、下载镜像

docker search RabbitMQ

进入docker hub镜像仓库地址:https://hub.docker.com/

搜索rabbitMq,进入官方的镜像,可以看到以下几种类型的镜像;我们选择带有“mangement”的版本(包含web管理页面);

拉取镜像

  1. docker pull rabbitmq:management

二、安装和web界面启动

镜像创建和启动容器

  1. docker run -d -p 5672:5672 -p 15672:15672 --name rabbitmq rabbitmq:management

说明:

  • -d 后台运行容器;
  • --name 指定容器名;
  • -p 指定服务运行的端口(5672:应用访问端口;15672:控制台Web端口号);
  • --hostname 主机名(RabbitMQ的一个重要注意事项是它根据所谓的 “节点名称” 存储数据,默认为主机名);

查看所有正在运行容器

  1. docker ps -a

删除指定容器

  1. docker rm ID/NAME

删除所有闲置容器

  1. docker container prune

重启docker

  1. systemctl restart docker

重启启动RabbitMQ

  1. docker run -d -p 5672:5672 -p 15672:15672 --name rabbitmq rabbitmq:management

开启防火墙15672端口

  1. firewall-cmd --zone=public --add-port=15672/tcp --permanent
  2. firewall-cmd --reload

停止RabbitMQ容器

  1. - 命令: docker stop rabbitmq

启动RabbitMQ容器

  1. - 命令:docker start rabbitmq

重启RabbitMQ容器

  1. - 命令:docker restart rabbitmq

三、测试

http://linuxip地址:15672,这里的用户名和密码默认都是guest

四、进入rabbitmq容器

  1. docker exec -it rabbitmq /bin/bash

五、添加新的用户

创建账号

  1. rabbitmqctl add_user 【用户名】 【密码】

设置用户角色

  1. rabbitmqctl set_user_tags admin administrator

设置用户权限

  1. rabbitmqctl set_permissions -p "/" qbb ".*"".*"".*"

查看当前用户角色、权限

  1. rabbitmqctl list_users

安装好RabbitMQ后如果需要熟悉里面的操作,大家可以参考官方网站

5.RabbitMQ提供了7种工作模式

6.RabbitMQ入门之简单模式(Java操作RabbitMQ)

1.创建一个普通的maven项目



2.在pom.xml中导入相关依赖

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6. <groupId>com.qbb</groupId>
  7. <artifactId>java-mq-producer</artifactId>
  8. <version>1.0-SNAPSHOT</version>
  9. <dependencies>
  10. <dependency>
  11. <groupId>com.rabbitmq</groupId>
  12. <artifactId>amqp-client</artifactId>
  13. <version>5.14.2</version>
  14. </dependency>
  15. </dependencies>
  16. </project>

3.编写生产者发送消息

  1. package com.qbb.simple;
  2. import com.rabbitmq.client.Channel;
  3. import com.rabbitmq.client.Connection;
  4. import com.rabbitmq.client.ConnectionFactory;
  5. /**
  6. * @author QiuQiu&LL (个人博客:https://www.cnblogs.com/qbbit)
  7. * @version 1.0
  8. * @date 2022-03-28 16:25
  9. * @Description:生产者
  10. */
  11. public class SimpleProducer {
  12. public static void main(String[] args) {
  13. try {
  14. // 创建连接工厂
  15. ConnectionFactory factory = new ConnectionFactory();
  16. factory.setHost("192.168.137.72");
  17. factory.setPort(5672);
  18. factory.setUsername("qbb");
  19. factory.setPassword("qbb");
  20. factory.setVirtualHost("/");
  21. // 获取连接对象
  22. Connection connection = factory.newConnection();
  23. // 获取channel
  24. Channel channel = connection.createChannel();
  25. // 我们将消息发送到队列中,前提是我们要有一个队列,所以先声明一个队列
  26. /**
  27. * String queue : 队列名称
  28. * boolean durable : 队列是否持久化
  29. * boolean exclusive : 是否独占本次连接,默认true
  30. * boolean autoDelete : 是否自动删除,最后一个消费者断开连接以后,该队列是否自动删除
  31. * Map<String, Object> arguments : 队列其它参数
  32. */
  33. channel.queueDeclare("simple-queue", false, false, false, null);
  34. // 发送消息
  35. /**
  36. * String exchange : 交换机名称,发送到哪个交换机
  37. * String routingKey : 路由key是哪个
  38. * BasicProperties props : 其他参数信息
  39. * byte[] body : 要发送的消息
  40. */
  41. String message = "hello QiuQiu RabbitMQ";
  42. channel.basicPublish("", "simple-queue", null, message.getBytes());
  43. System.out.println("消息发送完毕");
  44. // 释放资源
  45. channel.close();
  46. connection.close();
  47. } catch (Exception e) {
  48. e.printStackTrace();
  49. }
  50. }
  51. }

4.编写消费者接收消息

  1. package com.qbb.simple;
  2. import com.rabbitmq.client.*;
  3. import java.io.IOException;
  4. import java.util.concurrent.TimeoutException;
  5. /**
  6. * @author QiuQiu&LL (个人博客:https://www.cnblogs.com/qbbit)
  7. * @version 1.0
  8. * @date 2022-03-28 18:11
  9. * @Description:消费者
  10. */
  11. public class SimpleConsumer {
  12. public static void main(String[] args) {
  13. try {
  14. // 创建连接工厂
  15. ConnectionFactory factory = new ConnectionFactory();
  16. factory.setHost("192.168.137.72");
  17. factory.setPort(5672);
  18. factory.setUsername("qbb");
  19. factory.setPassword("qbb");
  20. factory.setVirtualHost("/");
  21. // 获取连接对象
  22. Connection connection = factory.newConnection();
  23. // 获取channel通道
  24. Channel channel = connection.createChannel();
  25. // 声明队列
  26. /**
  27. * String queue,
  28. * boolean autoAck,
  29. * Consumer callback
  30. */
  31. Consumer consumer = new DefaultConsumer(channel) {
  32. @Override
  33. public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
  34. String msg = new String(body);
  35. System.out.println(msg);
  36. }
  37. };
  38. //监听队列,第二个参数false,手动进行ACK
  39. channel.basicConsume("simple-queue", true, consumer);
  40. // 注意消费者端不要释放资源,需要一直监控着队列中的消息
  41. } catch (Exception e) {
  42. e.printStackTrace();
  43. }
  44. }
  45. }

注意:我们可以看到控制台报了一个错,应该是少了个slf4j的依赖,我们导入就好了

  1. <dependency>
  2. <groupId>org.slf4j</groupId>
  3. <artifactId>slf4j-simple</artifactId>
  4. <version>1.7.25</version>
  5. <scope>compile</scope>
  6. </dependency>

7.消息确认机制

我们查询图形化界面发现消息一经消费,就被删除了.

那么RabbitMQ怎么知道消息已经被我们消费了呢?

如果消费者领取消息后,还没执行操作就挂掉了呢?

或者抛出了异常?消息消费失败,但是 RabbitMQ 无从得知,这样消息就丢失了!

因此,RabbitMQ 有一个 ACK 机制。

当消费者获取消息后,会向 RabbitMQ 发送回执 ACK, 告知消息已经被接收。

不过这种回执 ACK 分两种情况:

  • 自动 ACK:消息一旦被接收,消费者自动发送 ACK
  • 手动 ACK:消息接收后,不会发送 ACK,需要手动调用
  • 如果消息不太重要,丢失也没有影响,那么自动 ACK 会比较方便
  • 如果消息非常重要,不容丢失。那么最好在消费完成后手动 ACK,否则接收消息后 就自动 ACK,RabbitMQ 就会把消息从队列中删除。如果此时消费者宕机,那么消 息就丢失了。

手动在consumer中制造一个异常,发现消息依旧被消费了

测试一下手动ACK

  1. // 修改consumer端的代码
  2. Consumer consumer = new DefaultConsumer(channel) {
  3. @Override
  4. public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
  5. String msg = new String(body);
  6. int a = 1 / 0;
  7. System.out.println(msg);
  8. //手动进行ACK
  9. channel.basicAck(envelope.getDeliveryTag(), false);
  10. }
  11. };
  12. //监听队列,第二个参数false,手动进行ACK
  13. channel.basicConsume("simple-queue", false, consumer);

可以看出即使出现了异常消息依旧不会被消费丢失



去掉异常重新启动consumer发现消息又被消费了

8.RabbitMQ入门之工作队列模式(Java操作RabbitMQ)

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

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

在前面的工程基础上创建两个包,继续编写代码

我们把获取connection对象抽取一个utils工具类

1.编写生产者发送消息

  1. package com.qbb.workqueue;
  2. import com.qbb.utils.MQUtil;
  3. import com.rabbitmq.client.Channel;
  4. import com.rabbitmq.client.Connection;
  5. /**
  6. * @author QiuQiu&LL (个人博客:https://www.cnblogs.com/qbbit)
  7. * @version 1.0
  8. * @date 2022-03-28 19:09
  9. * @Description:
  10. */
  11. public class WorkQueueProducer {
  12. public static void main(String[] args) {
  13. try {
  14. Connection connection = MQUtil.getConnection();
  15. Channel channel = connection.createChannel();
  16. channel.queueDeclare("work-queue", false, false, false, null);
  17. // 发送消息
  18. for (int i = 0; i < 20; i++) {
  19. String message = "hello QiuQiu work-queue:"+i;
  20. channel.basicPublish("", "work-queue", null, message.getBytes());
  21. }
  22. // 释放资源
  23. channel.close();
  24. connection.close();
  25. } catch (Exception e) {
  26. e.printStackTrace();
  27. }
  28. }
  29. }

2.编写消费者接收消息

  1. **消费者1**
  2. package com.qbb.workqueue;
  3. import com.qbb.utils.MQUtil;
  4. import com.rabbitmq.client.*;
  5. import java.io.IOException;
  6. import java.util.Timer;
  7. import java.util.TimerTask;
  8. import java.util.concurrent.TimeUnit;
  9. /**
  10. * @author QiuQiu&LL (个人博客:https://www.cnblogs.com/qbbit)
  11. * @version 1.0
  12. * @date 2022-03-28 19:21
  13. * @Description:
  14. */
  15. public class WorkQueueConsumer1 {
  16. public static void main(String[] args) {
  17. try {
  18. Connection connection = MQUtil.getConnection();
  19. Channel channel = connection.createChannel();
  20. channel.queueDeclare("work-queue", false, false, false, null);
  21. Consumer consumer = new DefaultConsumer(channel) {
  22. @Override
  23. public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
  24. // 消费者1消费消息
  25. try {
  26. // 睡50ms秒模拟,此服务性能差一点
  27. Thread.sleep(50);
  28. } catch (InterruptedException e) {
  29. e.printStackTrace();
  30. }
  31. String msg = new String(body);
  32. System.out.println("消费者1消费消息 = " + msg);
  33. channel.basicAck(envelope.getDeliveryTag(), false);
  34. }
  35. };
  36. channel.basicConsume("work-queue", false, consumer);
  37. } catch (Exception e) {
  38. e.printStackTrace();
  39. }
  40. }
  41. }
  1. **消费者2**
  2. package com.qbb.workqueue;
  3. import com.qbb.utils.MQUtil;
  4. import com.rabbitmq.client.*;
  5. import java.io.IOException;
  6. import java.util.concurrent.TimeUnit;
  7. /**
  8. * @author QiuQiu&LL (个人博客:https://www.cnblogs.com/qbbit)
  9. * @version 1.0
  10. * @date 2022-03-28 19:21
  11. * @Description:
  12. */
  13. public class WorkQueueConsumer2 {
  14. public static void main(String[] args) {
  15. try {
  16. Connection connection = MQUtil.getConnection();
  17. Channel channel = connection.createChannel();
  18. channel.queueDeclare("work-queue", false, false, false, null);
  19. Consumer consumer = new DefaultConsumer(channel) {
  20. @Override
  21. public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
  22. // 消费者2消费消息
  23. String msg = new String(body);
  24. System.out.println("消费者2消费消息 = " + msg);
  25. channel.basicAck(envelope.getDeliveryTag(), false);
  26. }
  27. };
  28. channel.basicConsume("work-queue", false, consumer);
  29. } catch (Exception e) {
  30. e.printStackTrace();
  31. }
  32. }
  33. }



可以发现,两个消费者各自消费了 25 条消息,而且各不相同,这就实现了任务的分发。

但是我现在想让性能差一点的服务器少处理点消息,实现能者多劳怎么办呢? 好办

在比较慢的消费者创建队列后我们可以使用 basicQos 方法和 prefetchCount = n ,告诉RabbitMQ每次给我发送一个消息等我处理完这个消息再给我发一个,一次一个的发消息

  1. ... WorkQueueConsumer1.java ...
  2. // 设置每次拉取一条消息消费
  3. channel.basicQos(1);



这样就解决了服务器性能差异问题

8.RabbitMQ入门之发布订阅模式|Publish/Subscribe(Java操作RabbitMQ)

一次同时向多个消费者发送消息,一条消息可以被多个消费者消费

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

  • P:生产者,也就是要发送消息的程序,但是不再发送到队列中,而是发给 X(交换机)
  • C:消费者,消息的接受者,会一直等待消息到来。
  • Queue:消息队列,接收消息、缓存消息。
  • Exchange:交换机,图中的 X。

    一方面,接收生产者发送的消息。另一方面,知道如 何处理消息,例如递交给某个特别队列、递交给所有队列、或是将消息丢弃。到底如何 操作,取决于 Exchange 的类型。

Exchange 有常见以下 3 种类型:

  • Fanout:广播,将消息交给所有绑定到交换机的队列
  • Direct:定向,把消息交给符合指定 routing key 的队列
  • Topic:通配符,把消息交给符合 routing pattern(路由模式) 的队列 Exchange(交换机)只负责转发消息,不具备存储消息的能力,因此如果没有任何队列与 Exchange 绑定,或者没有符合路由规则的队列,那么消息会丢失!

在广播模式下,消息发送流程是这样的:

  • 可以有多个消费者 -每个消费者有自己的 queue(队列)
  • 每个队列都要绑定到 Exchange(交换机)
  • 生产者发送的消息,只能发送到交换机,交换机来决定要发给哪个队列,生产者无法决定
  • 交换机把消息发送给绑定过的所有队列
  • 队列的消费者都能拿到消息。实现一条消息被多个消费者消费

Fanout 交换机

1.队列在绑定到交换机的时候不需要指定 routing key

2.发送消息的时候也不需要指定 routing key

3.凡是发送给交换机的消息都会广播发送到所有与交换机绑定的队列中。

1.编写生产者发送消息

  1. package com.qbb.pubsub;
  2. import com.qbb.utils.MQUtil;
  3. import com.rabbitmq.client.Channel;
  4. import com.rabbitmq.client.Connection;
  5. /**
  6. * @author QiuQiu&LL (个人博客:https://www.cnblogs.com/qbbit)
  7. * @version 1.0
  8. * @date 2022-03-28 19:56
  9. * @Description:发布订阅模式
  10. */
  11. public class PubSubProducer {
  12. public static void main(String[] args) {
  13. try {
  14. Connection connection = MQUtil.getConnection();
  15. Channel channel = connection.createChannel();
  16. // 声明交换机
  17. /**
  18. * 参数1:交换机名
  19. * 参数2:交换机类型
  20. */
  21. channel.exchangeDeclare("fanout-exchange","fanout");
  22. String message = "hello QiuQiu pubsub";
  23. channel.basicPublish("fanout-exchange", "pubsub-queue", null, message.getBytes());
  24. channel.close();
  25. connection.close();
  26. } catch (Exception e) {
  27. e.printStackTrace();
  28. }
  29. }
  30. }

2.编写消费者接收消息

  1. **消费者1**
  2. package com.qbb.pubsub;
  3. import com.qbb.utils.MQUtil;
  4. import com.rabbitmq.client.*;
  5. import java.io.IOException;
  6. /**
  7. * @author QiuQiu&LL (个人博客:https://www.cnblogs.com/qbbit)
  8. * @version 1.0
  9. * @date 2022-03-28 20:02
  10. * @Description:发布订阅消费者
  11. */
  12. public class PubSubConsumer1 {
  13. public static void main(String[] args) {
  14. try {
  15. // 获取连接
  16. Connection connection = MQUtil.getConnection();
  17. // 获取channel通道
  18. Channel channel = connection.createChannel();
  19. // 声明队列
  20. channel.queueDeclare("fanout-queue1", false, false, false, null);
  21. // 将队列绑定到交换机
  22. /**
  23. * 参数1:队列名称
  24. * 参数2:交换机名称
  25. * 参数3:路由key
  26. */
  27. channel.queueBind("fanout-queue1", "fanout-exchange", "pubsub-queue");
  28. Consumer consumer = new DefaultConsumer(channel) {
  29. @Override
  30. public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
  31. System.out.println("消费者唯一标识 = " + consumerTag);
  32. System.out.println("交换机名称 = " + envelope.getExchange());
  33. System.out.println("消息唯一标识 = " + envelope.getDeliveryTag());
  34. System.out.println("路由key = " + envelope.getRoutingKey());
  35. System.out.println("消费者1消费消息Message = " + new String(body));
  36. // 手动ACK
  37. channel.basicAck(envelope.getDeliveryTag(), false);
  38. }
  39. };
  40. channel.basicConsume("fanout-queue1", false, consumer);
  41. } catch (Exception e) {
  42. e.printStackTrace();
  43. }
  44. }
  45. }
  1. **消费者2**
  2. package com.qbb.pubsub;
  3. import com.qbb.utils.MQUtil;
  4. import com.rabbitmq.client.*;
  5. import java.io.IOException;
  6. /**
  7. * @author QiuQiu&LL (个人博客:https://www.cnblogs.com/qbbit)
  8. * @version 1.0
  9. * @date 2022-03-28 20:02
  10. * @Description:发布订阅消费者
  11. */
  12. public class PubSubConsumer2 {
  13. public static void main(String[] args) {
  14. try {
  15. // 获取连接
  16. Connection connection = MQUtil.getConnection();
  17. // 获取channel通道
  18. Channel channel = connection.createChannel();
  19. // 声明队列
  20. channel.queueDeclare("fanout-queue2", false, false, false, null);
  21. // 将队列绑定到交换机
  22. /**
  23. * 参数1:队列名称
  24. * 参数2:交换机名称
  25. * 参数3:路由key
  26. */
  27. channel.queueBind("fanout-queue2", "fanout-exchange", "pubsub-queue");
  28. Consumer consumer = new DefaultConsumer(channel) {
  29. @Override
  30. public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
  31. System.out.println("消费者唯一标识 = " + consumerTag);
  32. System.out.println("交换机名称 = " + envelope.getExchange());
  33. System.out.println("消息唯一标识 = " + envelope.getDeliveryTag());
  34. System.out.println("路由key = " + envelope.getRoutingKey());
  35. System.out.println("消费者2消费消息Message = " + new String(body));
  36. // 手动ACK
  37. channel.basicAck(envelope.getDeliveryTag(), false);
  38. }
  39. };
  40. channel.basicConsume("fanout-queue2", false, consumer);
  41. } catch (Exception e) {
  42. e.printStackTrace();
  43. }
  44. }
  45. }

测试结果:



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

1、工作队列模式不用定义交换机,而发布/订阅模式需要定义交换机。

2、发布/订阅模式的生产方是面向交换机发送消息,工作队列模式的生产方是面向队列发 送消息(底层使用默认交换机)。

3、发布/订阅模式需要设置队列和交换机的绑定,工作队列模式不需要设置,实际上工作 队列模式会将队列绑 定到默认的交换机 。

9.RabbitMQ入门之Routing 路由模式(Java操作RabbitMQ)

有选择性的接收消息

  • 在某些场景下,我们希望不同的消息被不同的队列消费。这时就要用到 Direct 类 型的 Exchange。

路由模式特点:

  • 队列与交换机的绑定,不能是任意绑定了,而是要指定一个RoutingKey(路由 key)
  • 消息的发送方在 向 Exchange 发送消息时,也必须指定消息的 RoutingKey
  • Exchange 不再把消息交给每一个绑定的队列,而是根据消息的Routing Key进行 判断,只有队列的Routingkey与消息的 Routing key完全一致,才会接收到消息

  • P:生产者,向 Exchange 发送消息,发送消息时,会指定一个 routing key。
  • X:Exchange(交换机),接收生产者的消息,然后把消息递交给 与 routing key 完全匹配的队列
  • C1:消费者,其所在队列指定了需要 routing key 为 error 的消息
  • C2:消费者,其所在队列指定了需要 routing key 为 info、error、warning 的 消息

可以看出routing模式和发布订阅模式没多大区别,只是交换机不同而已

1.编写生产者发送消息(发送增 删 改消息)

  1. package com.qbb.routing;
  2. import com.qbb.utils.MQUtil;
  3. import com.rabbitmq.client.Channel;
  4. import com.rabbitmq.client.Connection;
  5. /**
  6. * @author QiuQiu&LL (个人博客:https://www.cnblogs.com/qbbit)
  7. * @version 1.0
  8. * @date 2022-03-28 20:39
  9. * @Description:
  10. */
  11. public class RoutingProducer {
  12. public static void main(String[] args) {
  13. try {
  14. Connection connection = MQUtil.getConnection();
  15. Channel channel = connection.createChannel();
  16. // 声明交换机
  17. /**
  18. * 参数1:交换机名
  19. * 参数2:交换机类型
  20. */
  21. channel.exchangeDeclare("routing-exchange", "direct");
  22. String message = "hello QiuQiu 添加商品";
  23. channel.basicPublish("routing-exchange", "insert", null, message.getBytes());
  24. // String message1 = "hello QiuQiu 删除商品";
  25. // channel.basicPublish("routing-exchange", "delete", null, message1.getBytes());
  26. // String message2 = "hello QiuQiu 修改商品";
  27. // channel.basicPublish("routing-exchange", "update", null, message2.getBytes());
  28. channel.close();
  29. connection.close();
  30. } catch (Exception e) {
  31. e.printStackTrace();
  32. }
  33. }
  34. }

2.编写消费者接收消息

  1. **消费者1**
  2. package com.qbb.routing;
  3. import com.qbb.utils.MQUtil;
  4. import com.rabbitmq.client.*;
  5. import java.io.IOException;
  6. /**
  7. * @author QiuQiu&LL (个人博客:https://www.cnblogs.com/qbbit)
  8. * @version 1.0
  9. * @date 2022-03-28 20:36
  10. * @Description:routing模式
  11. */
  12. public class RoutingComsumer1 {
  13. public static void main(String[] args) {
  14. try {
  15. // 获取连接
  16. Connection connection = MQUtil.getConnection();
  17. // 获取channel通道
  18. Channel channel = connection.createChannel();
  19. // 声明队列
  20. channel.queueDeclare("routing-queue1", false, false, false, null);
  21. // 将队列绑定到交换机
  22. /**
  23. * 参数1:队列名称
  24. * 参数2:交换机名称
  25. * 参数3:路由key
  26. */
  27. channel.queueBind("routing-queue1", "routing-exchange", "insert");
  28. Consumer consumer = new DefaultConsumer(channel) {
  29. @Override
  30. public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
  31. System.out.println("消费者唯一标识 = " + consumerTag);
  32. System.out.println("交换机名称 = " + envelope.getExchange());
  33. System.out.println("消息唯一标识 = " + envelope.getDeliveryTag());
  34. System.out.println("路由key = " + envelope.getRoutingKey());
  35. System.out.println("消费者1消费消息Message = " + new String(body));
  36. }
  37. };
  38. channel.basicConsume("routing-queue1", true, consumer);
  39. } catch (Exception e) {
  40. e.printStackTrace();
  41. }
  42. }
  43. }
  1. **消费者2**
  2. package com.qbb.routing;
  3. import com.qbb.utils.MQUtil;
  4. import com.rabbitmq.client.*;
  5. import java.io.IOException;
  6. /**
  7. * @author QiuQiu&LL (个人博客:https://www.cnblogs.com/qbbit)
  8. * @version 1.0
  9. * @date 2022-03-28 20:36
  10. * @Description:
  11. */
  12. public class RoutingComsumer2 {
  13. public static void main(String[] args) {
  14. try {
  15. // 获取连接
  16. Connection connection = MQUtil.getConnection();
  17. // 获取channel通道
  18. Channel channel = connection.createChannel();
  19. // 声明队列
  20. channel.queueDeclare("routing-queue2", false, false, false, null);
  21. // 将队列绑定到交换机
  22. /**
  23. * 参数1:队列名称
  24. * 参数2:交换机名称
  25. * 参数3:路由key
  26. */
  27. channel.queueBind("routing-queue2", "routing-exchange", "insert");
  28. channel.queueBind("routing-queue2", "routing-exchange", "delete");
  29. channel.queueBind("routing-queue2", "routing-exchange", "update");
  30. Consumer consumer = new DefaultConsumer(channel) {
  31. @Override
  32. public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
  33. System.out.println("消费者唯一标识 = " + consumerTag);
  34. System.out.println("交换机名称 = " + envelope.getExchange());
  35. System.out.println("消息唯一标识 = " + envelope.getDeliveryTag());
  36. System.out.println("路由key = " + envelope.getRoutingKey());
  37. System.out.println("消费者2消费消息Message = " + new String(body));
  38. }
  39. };
  40. channel.basicConsume("routing-queue2", true, consumer);
  41. } catch (Exception e) {
  42. e.printStackTrace();
  43. }
  44. }
  45. }

测试结果:

10.RabbitMQ入门之Topics通配符模式(Java操作RabbitMQ)

Topic 类型与 Direct 相比,都是可以根据RoutingKey把消息路由到不同的队列。只 不过Topic类型Exchange可以让队列在绑定Routing key 的时候使用通配符! Routingkey 一般都是有一个或多个单词组成,多个单词之间以”.”分割

通配符规则:

#:匹配一个或多个词

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



1.编写生产者发送消息(发送消息的 routing key 有 3 种: item.insertitem.updateitem.delete)

  1. package com.qbb.topic;
  2. import com.qbb.utils.MQUtil;
  3. import com.rabbitmq.client.Channel;
  4. import com.rabbitmq.client.Connection;
  5. /**
  6. * @author QiuQiu&LL (个人博客:https://www.cnblogs.com/qbbit)
  7. * @version 1.0
  8. * @date 2022-03-28 20:39
  9. * @Description:
  10. */
  11. public class TopicProducer {
  12. public static void main(String[] args) {
  13. try {
  14. Connection connection = MQUtil.getConnection();
  15. Channel channel = connection.createChannel();
  16. // 声明交换机
  17. /**
  18. * 参数1:交换机名
  19. * 参数2:交换机类型
  20. */
  21. channel.exchangeDeclare("topic-exchange", "topic");
  22. // String message = "hello QiuQiu 添加商品";
  23. // channel.basicPublish("topic-exchange", "item.insert", null, message.getBytes());
  24. // String message1 = "hello QiuQiu 删除商品";
  25. // channel.basicPublish("topic-exchange", "item.delete", null, message1.getBytes());
  26. String message2 = "hello QiuQiu 修改商品";
  27. channel.basicPublish("topic-exchange", "item.update.do", null, message2.getBytes());
  28. channel.close();
  29. connection.close();
  30. } catch (Exception e) {
  31. e.printStackTrace();
  32. }
  33. }
  34. }

2.编写消费者接收消息

  1. **消费者1**
  2. package com.qbb.topic;
  3. import com.qbb.utils.MQUtil;
  4. import com.rabbitmq.client.*;
  5. import java.io.IOException;
  6. /**
  7. * @author QiuQiu&LL (个人博客:https://www.cnblogs.com/qbbit)
  8. * @version 1.0
  9. * @date 2022-03-28 20:36
  10. * @Description:routing模式
  11. */
  12. public class TopicConsumer1 {
  13. public static void main(String[] args) {
  14. try {
  15. // 获取连接
  16. Connection connection = MQUtil.getConnection();
  17. // 获取channel通道
  18. Channel channel = connection.createChannel();
  19. // 声明队列
  20. channel.queueDeclare("topic-queue1", false, false, false, null);
  21. // 将队列绑定到交换机
  22. /**
  23. * 参数1:队列名称
  24. * 参数2:交换机名称
  25. * 参数3:路由key
  26. */
  27. channel.queueBind("topic-queue1", "topic-exchange", "#.insert");
  28. channel.queueBind("topic-queue1", "topic-exchange", "#.update.#");
  29. Consumer consumer = new DefaultConsumer(channel) {
  30. @Override
  31. public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
  32. System.out.println("消费者唯一标识 = " + consumerTag);
  33. System.out.println("交换机名称 = " + envelope.getExchange());
  34. System.out.println("消息唯一标识 = " + envelope.getDeliveryTag());
  35. System.out.println("路由key = " + envelope.getRoutingKey());
  36. System.out.println("消费者1消费消息Message = " + new String(body));
  37. }
  38. };
  39. channel.basicConsume("topic-queue1", true, consumer);
  40. } catch (Exception e) {
  41. e.printStackTrace();
  42. }
  43. }
  44. }
  1. **消费者2**
  2. package com.qbb.topic;
  3. import com.qbb.utils.MQUtil;
  4. import com.rabbitmq.client.*;
  5. import java.io.IOException;
  6. /**
  7. * @author QiuQiu&LL (个人博客:https://www.cnblogs.com/qbbit)
  8. * @version 1.0
  9. * @date 2022-03-28 20:36
  10. * @Description:
  11. */
  12. public class TopicConsumer2 {
  13. public static void main(String[] args) {
  14. try {
  15. // 获取连接
  16. Connection connection = MQUtil.getConnection();
  17. // 获取channel通道
  18. Channel channel = connection.createChannel();
  19. // 声明队列
  20. channel.queueDeclare("topic-queue2", false, false, false, null);
  21. // 将队列绑定到交换机
  22. /**
  23. * 参数1:队列名称
  24. * 参数2:交换机名称
  25. * 参数3:路由key
  26. */
  27. channel.queueBind("topic-queue2", "topic-exchange", "item.*");
  28. channel.queueBind("topic-queue2", "topic-exchange", "#.delete");
  29. Consumer consumer = new DefaultConsumer(channel) {
  30. @Override
  31. public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
  32. System.out.println("消费者唯一标识 = " + consumerTag);
  33. System.out.println("交换机名称 = " + envelope.getExchange());
  34. System.out.println("消息唯一标识 = " + envelope.getDeliveryTag());
  35. System.out.println("路由key = " + envelope.getRoutingKey());
  36. System.out.println("消费者2消费消息Message = " + new String(body));
  37. }
  38. };
  39. channel.basicConsume("topic-queue2", true, consumer);
  40. } catch (Exception e) {
  41. e.printStackTrace();
  42. }
  43. }
  44. }

测试结果:

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

11.持久化(避免消息丢失)

为了避免消息丢失,我们可以将消息持久化!如何持久化消息呢?

要将消息持久化,前提是:队列、Exchange 都持久化

1.持久化交换机

  1. /**
  2. * 参数1:交换机名
  3. * 参数2:交换机类型
  4. * 参数3:是否持久化
  5. */
  6. channel.exchangeDeclare("topic-exchange", "topic",true);

2.持久化队列

  1. // 声明队列
  2. channel.queueDeclare("topic-queue1", true, false, false, null);

3.持久化消息

  1. channel.basicPublish("topic-exchange", "item.update.do", MessageProperties.PERSISTENT_TEXT_PLAIN, message2.getBytes());

12.RabbitMQ 工作模式总结

  • 1、简单模式 HelloWorld 一个生产者、一个消费者,不需要设置交换机(使用默认的交换机)
  • 2、工作队列模式 Work Queue 一个生产者、多个消费者(竞争关系),不需要设置交换机(使用默认的交换机)
  • 3、发布订阅模式 Publish/subscribe 需要设置类型为 fanout 的交换机,并且交换机和队列进行绑定,当发送消息到交换机后, 交换机会将消息发送到绑定的队列
  • 4、路由模式 Routing 需要设置类型为 direct 的交换机,交换机和队列进行绑定,并且指定 routing key,当 发送消息到交换机后,交换机会根据 routing key 将消息发送到对应的队列
  • 5、通配符模式 Topic 需要设置类型为 topic 的交换机,交换机和队列进行绑定,并且指定通配符方式的 routing key,当发送消息到交换机后,交换机会根据 routing key 将消息发送到对应 的队列 消息的可靠性投递 RabbitMQ 集群 消息百分百投递(confirm 和 return、消费者确认 ack 机制)

13.Spring 整合 RabbitMQ(简单模式)

前面我们使用java代码操作了RabbitMQ,其实操作起来感觉还是有点繁琐,下面使用Spring来整合RabbitMQ,看看能否有不一样的体验

先写producer消息提供方

1.创建一个maven项目

2.导入相关依赖

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6. <groupId>com.qbb</groupId>
  7. <artifactId>spring-mq-producer</artifactId>
  8. <version>1.0-SNAPSHOT</version>
  9. <dependencies>
  10. <dependency>
  11. <groupId>org.springframework</groupId>
  12. <artifactId>spring-context</artifactId>
  13. <version>5.3.16</version>
  14. </dependency>
  15. <dependency>
  16. <groupId>org.springframework.amqp</groupId>
  17. <artifactId>spring-rabbit</artifactId>
  18. <version>2.4.2</version>
  19. </dependency>
  20. <dependency>
  21. <groupId>junit</groupId>
  22. <artifactId>junit</artifactId>
  23. <version>4.13.2</version>
  24. </dependency>
  25. <dependency>
  26. <groupId>org.springframework</groupId>
  27. <artifactId>spring-test</artifactId>
  28. <version>5.3.16</version>
  29. </dependency>
  30. </dependencies>
  31. </project>

3.编写rabbitmq.properties配置文件

  1. rabbitmq.host=192.168.137.72
  2. rabbitmq.port=5672
  3. rabbitmq.username=qbb
  4. rabbitmq.password=qbb
  5. rabbitmq.virtual-host=/

4.编写spring-rabbitmq-producer.xml配置文件

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:rabbit="http://www.springframework.org/schema/rabbit"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/rabbit http://www.springframework.org/schema/rabbit/spring-rabbit.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
  6. <!--加载rabbitmq.properties-->
  7. <context:property-placeholder location="classpath:rabbitmq.properties"/>
  8. <!--配置连接工厂-->
  9. <rabbit:connection-factory
  10. id="connectionFactory"
  11. host="${rabbitmq.host}"
  12. port="${rabbitmq.port}"
  13. username="${rabbitmq.username}"
  14. password="${rabbitmq.password}"
  15. virtual-host="${rabbitmq.virtual-host}"/>
  16. <!--配置监听器-->
  17. <bean id="simpleListener" class="com.qbb.listener.SimpleListener"/>
  18. <!--将监听器放入rabbit容器-->
  19. <rabbit:listener-container connection-factory="connectionFactory">
  20. <rabbit:listener ref="simpleListener" queue-names="spring-simple-queue"/>
  21. </rabbit:listener-container>
  22. </beans>

5.在test测试包下创建测试类

  1. package com.qbb;
  2. import org.junit.Test;
  3. import org.junit.runner.RunWith;
  4. import org.springframework.amqp.rabbit.core.RabbitTemplate;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.test.context.ContextConfiguration;
  7. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
  8. /**
  9. * @author QiuQiu&LL (个人博客:https://www.cnblogs.com/qbbit)
  10. * @version 1.0
  11. * @date 2022-03-28 23:56
  12. * @Description:
  13. */
  14. @RunWith(SpringJUnit4ClassRunner.class)
  15. @ContextConfiguration(locations = "classpath:spring-rabbitmq-producer.xml")
  16. public class MQTest {
  17. @Autowired
  18. private RabbitTemplate rabbitTemplate;
  19. @Test
  20. public void testSimple() {
  21. rabbitTemplate.convertAndSend("spring-simple-queue", "hello QiuQiu Spring-MQ-Simple");
  22. }
  23. }

再写consumer消息消费方

1.创建一个maven项目

2.导入相关依赖

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6. <groupId>com.qbb</groupId>
  7. <artifactId>spring-mq-producer</artifactId>
  8. <version>1.0-SNAPSHOT</version>
  9. <dependencies>
  10. <dependency>
  11. <groupId>org.springframework</groupId>
  12. <artifactId>spring-context</artifactId>
  13. <version>5.3.16</version>
  14. </dependency>
  15. <dependency>
  16. <groupId>org.springframework.amqp</groupId>
  17. <artifactId>spring-rabbit</artifactId>
  18. <version>2.4.2</version>
  19. </dependency>
  20. <dependency>
  21. <groupId>junit</groupId>
  22. <artifactId>junit</artifactId>
  23. <version>4.13.2</version>
  24. </dependency>
  25. <dependency>
  26. <groupId>org.springframework</groupId>
  27. <artifactId>spring-test</artifactId>
  28. <version>5.3.16</version>
  29. </dependency>
  30. </dependencies>
  31. </project>

3.编写rabbitmq.properties配置文件

  1. rabbitmq.host=192.168.137.72
  2. rabbitmq.port=5672
  3. rabbitmq.username=qbb
  4. rabbitmq.password=qbb
  5. rabbitmq.virtual-host=/

4.编写spring-rabbitmq-producer.xml配置文件

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:rabbit="http://www.springframework.org/schema/rabbit"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/rabbit http://www.springframework.org/schema/rabbit/spring-rabbit.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
  6. <!--加载rabbitmq.properties-->
  7. <context:property-placeholder location="classpath:rabbitmq.properties"/>
  8. <!--配置连接工厂-->
  9. <rabbit:connection-factory
  10. id="connectionFactory"
  11. host="${rabbitmq.host}"
  12. port="${rabbitmq.port}"
  13. username="${rabbitmq.username}"
  14. password="${rabbitmq.password}"
  15. virtual-host="${rabbitmq.virtual-host}"/>
  16. <!--RabbitAdmin 用于远程创建、管理交换机、队列-->
  17. <rabbit:admin connection-factory="connectionFactory"/>
  18. <!--声明队列:
  19. id 属性方便下面引用(当然 id 属性可以省略,通过 name 属性引用也行)
  20. name 属性执行创建队列的名称(name 属性不可省略,否则无法定义队列名称),
  21. auto-declare 属性为 true 表示不存在则自动创建-->
  22. <rabbit:queue id="spring-queue" name="spring-queue" auto-declare="true"></rabbit:queue>
  23. <!--定义 rabbitTemplate 对象操作可以在代码中方便发送消息-->
  24. <rabbit:template connection-factory="connectionFactory" id="rabbitTemplate"/>
  25. <!--==================简单模式==================-->
  26. <rabbit:queue id="spring-simple-queue" name="spring-simple-queue" durable="false" auto-delete="false" auto-declare="true"/>
  27. </beans>

5.创建一个SimpleListener监听类实现MessageListener监听消息

  1. package com.qbb.listener;
  2. import org.springframework.amqp.core.Message;
  3. import org.springframework.amqp.core.MessageListener;
  4. /**
  5. * @author QiuQiu&LL (个人博客:https://www.cnblogs.com/qbbit)
  6. * @version 1.0
  7. * @date 2022-03-29 0:09
  8. * @Description:简单模式
  9. */
  10. public class SimpleListener implements MessageListener {
  11. @Override
  12. public void onMessage(Message message) {
  13. System.out.println("消费者唯一标识 =" + message.getMessageProperties().getConsumerTag());
  14. System.out.println("消息唯一标识 =" + message.getMessageProperties().getDeliveryTag());
  15. System.out.println("交换机名称 =" + message.getMessageProperties().getReceivedExchange());
  16. System.out.println("路由key =" + message.getMessageProperties().getReceivedRoutingKey());
  17. System.out.println("消息 =" + new String(message.getBody()));
  18. }
  19. }

6.在test测试包下创建测试类

  1. package com.qbb;
  2. import org.junit.Test;
  3. import org.junit.runner.RunWith;
  4. import org.springframework.test.context.ContextConfiguration;
  5. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
  6. /**
  7. * @author QiuQiu&LL (个人博客:https://www.cnblogs.com/qbbit)
  8. * @version 1.0
  9. * @date 2022-03-29 0:14
  10. * @Description:
  11. */
  12. @RunWith(SpringJUnit4ClassRunner.class)
  13. @ContextConfiguration(locations = "classpath:spring-rabbitmq-consumer.xml")
  14. public class MQTest {
  15. @Test
  16. public void test01() {
  17. while (true) {
  18. }
  19. }
  20. }

测试结果:

13.Spring 整合 RabbitMQ(工作队列模式)

1.修改spring-rabbitmq-producer.xml配置文件

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:rabbit="http://www.springframework.org/schema/rabbit"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/rabbit http://www.springframework.org/schema/rabbit/spring-rabbit.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
  6. <!--加载rabbitmq.properties-->
  7. <context:property-placeholder location="classpath:rabbitmq.properties"/>
  8. <!--配置连接工厂-->
  9. <rabbit:connection-factory
  10. id="connectionFactory"
  11. host="${rabbitmq.host}"
  12. port="${rabbitmq.port}"
  13. username="${rabbitmq.username}"
  14. password="${rabbitmq.password}"
  15. virtual-host="${rabbitmq.virtual-host}"/>
  16. <!--RabbitAdmin 用于远程创建、管理交换机、队列-->
  17. <rabbit:admin connection-factory="connectionFactory"/>
  18. <!--声明队列:
  19. id 属性方便下面引用(当然 id 属性可以省略,通过 name 属性引用也行)
  20. name 属性执行创建队列的名称(name 属性不可省略,否则无法定义队列名称),
  21. auto-declare 属性为 true 表示不存在则自动创建-->
  22. <rabbit:queue id="spring-queue" name="spring-queue" auto-declare="true"></rabbit:queue>
  23. <!--定义 rabbitTemplate 对象操作可以在代码中方便发送消息-->
  24. <rabbit:template connection-factory="connectionFactory" id="rabbitTemplate"/>
  25. <!--==================简单模式==================-->
  26. <rabbit:queue id="spring-simple-queue" name="spring-simple-queue" durable="false" auto-delete="false" auto-declare="true"/>
  27. <!--==================工作队列模式==================-->
  28. <rabbit:queue id="spring-work-queue" name="spring-work-queue" durable="false" auto-delete="false" auto-declare="true"/>
  29. </beans>

2.修改producer测试类

  1. package com.qbb;
  2. import org.junit.Test;
  3. import org.junit.runner.RunWith;
  4. import org.springframework.amqp.rabbit.core.RabbitTemplate;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.test.context.ContextConfiguration;
  7. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
  8. /**
  9. * @author QiuQiu&LL (个人博客:https://www.cnblogs.com/qbbit)
  10. * @version 1.0
  11. * @date 2022-03-28 23:56
  12. * @Description:
  13. */
  14. @RunWith(SpringJUnit4ClassRunner.class)
  15. @ContextConfiguration(locations = "classpath:spring-rabbitmq-producer.xml")
  16. public class MQTest {
  17. @Autowired
  18. private RabbitTemplate rabbitTemplate;
  19. /**
  20. * 简单模式
  21. */
  22. @Test
  23. public void testSimple() {
  24. rabbitTemplate.convertAndSend("spring-simple-queue", "hello QiuQiu Spring-MQ-Simple");
  25. }
  26. /**
  27. * 工作队列模式
  28. */
  29. @Test
  30. public void testWorkQueue() {
  31. for (int i = 0; i < 10; i++) {
  32. rabbitTemplate.convertAndSend("spring-work-queue", "hello QiuQiu Spring-MQ-WorkQueue"+i);
  33. }
  34. }
  35. }

3.修改spring-rabbitmq-consumer.xml配置文件

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:rabbit="http://www.springframework.org/schema/rabbit"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/rabbit http://www.springframework.org/schema/rabbit/spring-rabbit.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
  6. <!--加载rabbitmq.properties-->
  7. <context:property-placeholder location="classpath:rabbitmq.properties"/>
  8. <!--配置连接工厂-->
  9. <rabbit:connection-factory
  10. id="connectionFactory"
  11. host="${rabbitmq.host}"
  12. port="${rabbitmq.port}"
  13. username="${rabbitmq.username}"
  14. password="${rabbitmq.password}"
  15. virtual-host="${rabbitmq.virtual-host}"/>
  16. <!--配置监听器-->
  17. <!--简单模式-->
  18. <bean id="simpleListener" class="com.qbb.listener.SimpleListener"/>
  19. <!--工作队列模式-->
  20. <bean id="workQueueListener1" class="com.qbb.listener.WorkQueueListener1"/>
  21. <bean id="workQueueListener2" class="com.qbb.listener.WorkQueueListener2"/>
  22. <!--将监听器放入rabbit容器-->
  23. <rabbit:listener-container connection-factory="connectionFactory">
  24. <!--简单模式-->
  25. <rabbit:listener ref="simpleListener" queue-names="spring-simple-queue"/>
  26. <!--工作队列模式-->
  27. <rabbit:listener ref="workQueueListener1" queue-names="spring-work-queue"/>
  28. <rabbit:listener ref="workQueueListener2" queue-names="spring-work-queue"/>
  29. </rabbit:listener-container>
  30. </beans>

4.创建两个监听类

  1. package com.qbb.listener;
  2. import org.springframework.amqp.core.Message;
  3. import org.springframework.amqp.core.MessageListener;
  4. /**
  5. * @author QiuQiu&LL (个人博客:https://www.cnblogs.com/qbbit)
  6. * @version 1.0
  7. * @date 2022-03-29 0:09
  8. * @Description:消息队列模式
  9. */
  10. public class WorkQueueListener2 implements MessageListener {
  11. @Override
  12. public void onMessage(Message message) {
  13. System.out.println("消费者2唯一标识 =" + message.getMessageProperties().getConsumerTag());
  14. System.out.println("消费者2消息唯一标识 =" + message.getMessageProperties().getDeliveryTag());
  15. System.out.println("消费者2交换机名称 =" + message.getMessageProperties().getReceivedExchange());
  16. System.out.println("消费者2路由key =" + message.getMessageProperties().getReceivedRoutingKey());
  17. System.out.println("消费者2消费的消息 =" + new String(message.getBody()));
  18. }
  19. }
  20. ------------
  21. package com.qbb.listener;
  22. import org.springframework.amqp.core.Message;
  23. import org.springframework.amqp.core.MessageListener;
  24. /**
  25. * @author QiuQiu&LL (个人博客:https://www.cnblogs.com/qbbit)
  26. * @version 1.0
  27. * @date 2022-03-29 0:09
  28. * @Description:消息队列模式
  29. */
  30. public class WorkQueueListener1 implements MessageListener {
  31. @Override
  32. public void onMessage(Message message) {
  33. System.out.println("消费者1唯一标识 =" + message.getMessageProperties().getConsumerTag());
  34. System.out.println("消费者1消息唯一标识 =" + message.getMessageProperties().getDeliveryTag());
  35. System.out.println("消费者1交换机名称 =" + message.getMessageProperties().getReceivedExchange());
  36. System.out.println("消费者1路由key =" + message.getMessageProperties().getReceivedRoutingKey());
  37. System.out.println("消费者1消费的消息 =" + new String(message.getBody()));
  38. }
  39. }

执行测试类测试结果:

  1. 消费者1唯一标识 =amq.ctag-Jh86rHgn7_CftQS9Klseew
  2. 消费者1消息唯一标识 =1
  3. 消费者1交换机名称 =
  4. 消费者1路由key =spring-work-queue
  5. 消费者2唯一标识 =amq.ctag-CP-q5LpFxWo9RY4yOpgMGQ
  6. 消费者2消息唯一标识 =1
  7. 消费者2交换机名称 =
  8. 消费者1消费的消息 =hello QiuQiu Spring-MQ-WorkQueue0
  9. 消费者2路由key =spring-work-queue
  10. 消费者2消费的消息 =hello QiuQiu Spring-MQ-WorkQueue1
  11. 消费者2唯一标识 =amq.ctag-CP-q5LpFxWo9RY4yOpgMGQ
  12. 消费者2消息唯一标识 =2
  13. 消费者2交换机名称 =
  14. 消费者2路由key =spring-work-queue
  15. 消费者2消费的消息 =hello QiuQiu Spring-MQ-WorkQueue3
  16. 消费者2唯一标识 =amq.ctag-CP-q5LpFxWo9RY4yOpgMGQ
  17. 消费者2消息唯一标识 =3
  18. 消费者2交换机名称 =
  19. 消费者2路由key =spring-work-queue
  20. 消费者2消费的消息 =hello QiuQiu Spring-MQ-WorkQueue5
  21. 消费者2唯一标识 =amq.ctag-CP-q5LpFxWo9RY4yOpgMGQ
  22. 消费者2消息唯一标识 =4
  23. 消费者2交换机名称 =
  24. 消费者2路由key =spring-work-queue
  25. 消费者2消费的消息 =hello QiuQiu Spring-MQ-WorkQueue7
  26. 消费者2唯一标识 =amq.ctag-CP-q5LpFxWo9RY4yOpgMGQ
  27. 消费者2消息唯一标识 =5
  28. 消费者2交换机名称 =
  29. 消费者2路由key =spring-work-queue
  30. 消费者2消费的消息 =hello QiuQiu Spring-MQ-WorkQueue9
  31. 消费者1唯一标识 =amq.ctag-Jh86rHgn7_CftQS9Klseew
  32. 消费者1消息唯一标识 =2
  33. 消费者1交换机名称 =
  34. 消费者1路由key =spring-work-queue
  35. 消费者1消费的消息 =hello QiuQiu Spring-MQ-WorkQueue2
  36. 消费者1唯一标识 =amq.ctag-Jh86rHgn7_CftQS9Klseew
  37. 消费者1消息唯一标识 =3
  38. 消费者1交换机名称 =
  39. 消费者1路由key =spring-work-queue
  40. 消费者1消费的消息 =hello QiuQiu Spring-MQ-WorkQueue4
  41. 消费者1唯一标识 =amq.ctag-Jh86rHgn7_CftQS9Klseew
  42. 消费者1消息唯一标识 =4
  43. 消费者1交换机名称 =
  44. 消费者1路由key =spring-work-queue
  45. 消费者1消费的消息 =hello QiuQiu Spring-MQ-WorkQueue6
  46. 消费者1唯一标识 =amq.ctag-Jh86rHgn7_CftQS9Klseew
  47. 消费者1消息唯一标识 =5
  48. 消费者1交换机名称 =
  49. 消费者1路由key =spring-work-queue
  50. 消费者1消费的消息 =hello QiuQiu Spring-MQ-WorkQueue8

可以看出10条消息平均分配个两个消费者

14.Spring 整合 RabbitMQ(发布订阅模式,routing(路由模式),topic模式),这里我就把三种情况写一起啦,代码和配置文件中都有详细的注释.不然太长了阅读也不方便

spring-rabbitmq-producer.xml配置文件

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:rabbit="http://www.springframework.org/schema/rabbit"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/rabbit http://www.springframework.org/schema/rabbit/spring-rabbit.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
  6. <!--加载rabbitmq.properties-->
  7. <context:property-placeholder location="classpath:rabbitmq.properties"/>
  8. <!--配置连接工厂-->
  9. <rabbit:connection-factory
  10. id="connectionFactory"
  11. host="${rabbitmq.host}"
  12. port="${rabbitmq.port}"
  13. username="${rabbitmq.username}"
  14. password="${rabbitmq.password}"
  15. virtual-host="${rabbitmq.virtual-host}"/>
  16. <!--RabbitAdmin 用于远程创建、管理交换机、队列-->
  17. <rabbit:admin connection-factory="connectionFactory"/>
  18. <!--声明队列:
  19. id 属性方便下面引用(当然 id 属性可以省略,通过 name 属性引用也行)
  20. name 属性执行创建队列的名称(name 属性不可省略,否则无法定义队列名称),
  21. auto-declare 属性为 true 表示不存在则自动创建-->
  22. <rabbit:queue id="spring-queue" name="spring-queue" auto-declare="true"></rabbit:queue>
  23. <!--定义 rabbitTemplate 对象操作可以在代码中方便发送消息-->
  24. <rabbit:template connection-factory="connectionFactory" id="rabbitTemplate"/>
  25. <!--==================简单模式==================-->
  26. <rabbit:queue id="spring-simple-queue" name="spring-simple-queue" durable="false" auto-delete="false" auto-declare="true"/>
  27. <!--==================工作队列模式==================-->
  28. <rabbit:queue id="spring-work-queue" name="spring-work-queue" durable="false" auto-delete="false" auto-declare="true"/>
  29. <!--==================发布订阅模式==================-->
  30. <rabbit:queue id="spring-fanout-queue1" name="spring-fanout-queue1" durable="false" auto-delete="false" auto-declare="true"/>
  31. <rabbit:queue id="spring-fanout-queue2" name="spring-fanout-queue2" durable="false" auto-delete="false" auto-declare="true"/>
  32. <!--创建交换机-->
  33. <rabbit:fanout-exchange name="spring-fanout-exchange">
  34. <!--绑定队列-->
  35. <rabbit:bindings>
  36. <rabbit:binding queue="spring-fanout-queue1"/>
  37. <rabbit:binding queue="spring-fanout-queue2"/>
  38. </rabbit:bindings>
  39. </rabbit:fanout-exchange>
  40. <!--==================routing模式==================-->
  41. <rabbit:queue id="spring-routing-queue1" name="spring-routing-queue1" durable="false" auto-delete="false" auto-declare="true"/>
  42. <rabbit:queue id="spring-routing-queue2" name="spring-routing-queue2" durable="false" auto-delete="false" auto-declare="true"/>
  43. <!--创建交换机-->
  44. <rabbit:direct-exchange name="spring-routing-exchange">
  45. <!--绑定队列-->
  46. <rabbit:bindings>
  47. <rabbit:binding queue="spring-routing-queue1" key="error"/>
  48. <rabbit:binding queue="spring-routing-queue2" key="error"/>
  49. <rabbit:binding queue="spring-routing-queue2" key="info"/>
  50. <rabbit:binding queue="spring-routing-queue2" key="warning"/>
  51. </rabbit:bindings>
  52. </rabbit:direct-exchange>
  53. <!--==================topic模式==================-->
  54. <rabbit:queue id="spring-topic-queue1" name="spring-topic-queue1" durable="false" auto-delete="false" auto-declare="true"/>
  55. <rabbit:queue id="spring-topic-queue2" name="spring-topic-queue2" durable="false" auto-delete="false" auto-declare="true"/>
  56. <!--创建交换机-->
  57. <rabbit:topic-exchange name="spring-topic-exchange">
  58. <!--绑定队列-->
  59. <rabbit:bindings>
  60. <rabbit:binding pattern="*.orange.*" queue="spring-topic-queue1"></rabbit:binding>
  61. <rabbit:binding pattern="*.*.rabbit" queue="spring-topic-queue2"></rabbit:binding>
  62. <rabbit:binding pattern="lazy.#" queue="spring-topic-queue2"></rabbit:binding>
  63. </rabbit:bindings>
  64. </rabbit:topic-exchange>
  65. </beans>

producer生产者的MQTest.java

  1. package com.qbb;
  2. import org.junit.Test;
  3. import org.junit.runner.RunWith;
  4. import org.springframework.amqp.rabbit.core.RabbitTemplate;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.test.context.ContextConfiguration;
  7. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
  8. /**
  9. * @author QiuQiu&LL (个人博客:https://www.cnblogs.com/qbbit)
  10. * @version 1.0
  11. * @date 2022-03-28 23:56
  12. * @Description:
  13. */
  14. @RunWith(SpringJUnit4ClassRunner.class)
  15. @ContextConfiguration(locations = "classpath:spring-rabbitmq-producer.xml")
  16. public class MQTest {
  17. @Autowired
  18. private RabbitTemplate rabbitTemplate;
  19. /**
  20. * 简单模式
  21. */
  22. @Test
  23. public void testSimple() {
  24. rabbitTemplate.convertAndSend("spring-simple-queue", "hello QiuQiu Spring-MQ-Simple");
  25. }
  26. /**
  27. * 工作队列模式
  28. */
  29. @Test
  30. public void testWorkQueue() {
  31. for (int i = 0; i < 10; i++) {
  32. rabbitTemplate.convertAndSend("spring-work-queue", "hello QiuQiu Spring-MQ-WorkQueue" + i);
  33. }
  34. }
  35. /**
  36. * 发布订阅模式
  37. */
  38. @Test
  39. public void testFanout() {
  40. rabbitTemplate.convertSendAndReceive("spring-fanout-exchange", "", "hello QiuQiu Spring-MQ-PubSub");
  41. }
  42. /**
  43. * routing模式
  44. */
  45. @Test
  46. public void testRouting() {
  47. rabbitTemplate.convertSendAndReceive("spring-routing-exchange", "error", "hello QiuQiu Spring-MQ-Routing-AAA");
  48. rabbitTemplate.convertSendAndReceive("spring-routing-exchange", "info", "hello QiuQiu Spring-MQ-Routing-BBB");
  49. }
  50. /**
  51. * topic模式
  52. */
  53. @Test
  54. public void testTopic() {
  55. rabbitTemplate.convertSendAndReceive("spring-topic-exchange", "lazy.orange.qiu", "hello QiuQiu Spring-MQ-Topic-AAA");
  56. rabbitTemplate.convertSendAndReceive("spring-topic-exchange", "qiu.ll.rabbit", "hello QiuQiu Spring-MQ-Topic-BBB");
  57. }
  58. }

spring-rabbitmq-consumer.xml配置文件

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:rabbit="http://www.springframework.org/schema/rabbit"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/rabbit http://www.springframework.org/schema/rabbit/spring-rabbit.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
  6. <!--加载rabbitmq.properties-->
  7. <context:property-placeholder location="classpath:rabbitmq.properties"/>
  8. <!--配置连接工厂-->
  9. <rabbit:connection-factory
  10. id="connectionFactory"
  11. host="${rabbitmq.host}"
  12. port="${rabbitmq.port}"
  13. username="${rabbitmq.username}"
  14. password="${rabbitmq.password}"
  15. virtual-host="${rabbitmq.virtual-host}"/>
  16. <!--配置监听器-->
  17. <!--简单模式-->
  18. <bean id="simpleListener" class="com.qbb.listener.SimpleListener"/>
  19. <!--工作队列模式-->
  20. <bean id="workQueueListener1" class="com.qbb.listener.WorkQueueListener1"/>
  21. <bean id="workQueueListener2" class="com.qbb.listener.WorkQueueListener2"/>
  22. <!--发布订阅模式-->
  23. <bean id="fanoutListener1" class="com.qbb.listener.FanoutListener1"/>
  24. <bean id="fanoutListener2" class="com.qbb.listener.FanoutListener2"/>
  25. <!--routing模式-->
  26. <bean id="routingListener1" class="com.qbb.listener.RoutingListener1"/>
  27. <bean id="routingListener2" class="com.qbb.listener.RoutingListener2"/>
  28. <!--topic模式-->
  29. <bean id="topicListener1" class="com.qbb.listener.TopicListener1"/>
  30. <bean id="topicListener2" class="com.qbb.listener.TopicListener2"/>
  31. <!--将监听器放入rabbit容器-->
  32. <rabbit:listener-container connection-factory="connectionFactory">
  33. <!--简单模式-->
  34. <rabbit:listener ref="simpleListener" queue-names="spring-simple-queue"/>
  35. <!--工作队列模式-->
  36. <rabbit:listener ref="workQueueListener1" queue-names="spring-work-queue"/>
  37. <rabbit:listener ref="workQueueListener2" queue-names="spring-work-queue"/>
  38. <!--发布订阅模式-->
  39. <rabbit:listener ref="fanoutListener1" queue-names="spring-fanout-queue1"/>
  40. <rabbit:listener ref="fanoutListener2" queue-names="spring-fanout-queue2"/>
  41. <!--routing模式-->
  42. <rabbit:listener ref="routingListener1" queue-names="spring-routing-queue1"/>
  43. <rabbit:listener ref="routingListener2" queue-names="spring-routing-queue2"/>
  44. <!--topic模式-->
  45. <rabbit:listener ref="topicListener1" queue-names="spring-topic-queue1"/>
  46. <rabbit:listener ref="topicListener2" queue-names="spring-topic-queue2"/>
  47. </rabbit:listener-container>
  48. </beans>

FanoutListener1监听器

  1. package com.qbb.listener;
  2. import org.springframework.amqp.core.Message;
  3. import org.springframework.amqp.core.MessageListener;
  4. /**
  5. * @author QiuQiu&LL (个人博客:https://www.cnblogs.com/qbbit)
  6. * @version 1.0
  7. * @date 2022-03-29 0:09
  8. * @Description:发布订阅模式
  9. */
  10. public class FanoutListener1 implements MessageListener {
  11. @Override
  12. public void onMessage(Message message) {
  13. System.out.println("消费者1唯一标识 =" + message.getMessageProperties().getConsumerTag());
  14. System.out.println("消费者1消息唯一标识 =" + message.getMessageProperties().getDeliveryTag());
  15. System.out.println("消费者1交换机名称 =" + message.getMessageProperties().getReceivedExchange());
  16. System.out.println("消费者1路由key =" + message.getMessageProperties().getReceivedRoutingKey());
  17. System.out.println("消费者1消费的消息 =" + new String(message.getBody()));
  18. }
  19. }

FanoutListener2监听器

  1. package com.qbb.listener;
  2. import org.springframework.amqp.core.Message;
  3. import org.springframework.amqp.core.MessageListener;
  4. /**
  5. * @author QiuQiu&LL (个人博客:https://www.cnblogs.com/qbbit)
  6. * @version 1.0
  7. * @date 2022-03-29 0:09
  8. * @Description:发布订阅模式
  9. */
  10. public class FanoutListener2 implements MessageListener {
  11. @Override
  12. public void onMessage(Message message) {
  13. System.out.println("消费者2唯一标识 =" + message.getMessageProperties().getConsumerTag());
  14. System.out.println("消费者2消息唯一标识 =" + message.getMessageProperties().getDeliveryTag());
  15. System.out.println("消费者2交换机名称 =" + message.getMessageProperties().getReceivedExchange());
  16. System.out.println("消费者2路由key =" + message.getMessageProperties().getReceivedRoutingKey());
  17. System.out.println("消费者2消费的消息 =" + new String(message.getBody()));
  18. }
  19. }

RoutingListener1监听器

  1. package com.qbb.listener;
  2. import org.springframework.amqp.core.Message;
  3. import org.springframework.amqp.core.MessageListener;
  4. /**
  5. * @author QiuQiu&LL (个人博客:https://www.cnblogs.com/qbbit)
  6. * @version 1.0
  7. * @date 2022-03-29 0:09
  8. * @Description:routing模式
  9. */
  10. public class RoutingListener1 implements MessageListener {
  11. @Override
  12. public void onMessage(Message message) {
  13. System.out.println("消费者1唯一标识 =" + message.getMessageProperties().getConsumerTag());
  14. System.out.println("消费者1消息唯一标识 =" + message.getMessageProperties().getDeliveryTag());
  15. System.out.println("消费者1交换机名称 =" + message.getMessageProperties().getReceivedExchange());
  16. System.out.println("消费者1路由key =" + message.getMessageProperties().getReceivedRoutingKey());
  17. System.out.println("消费者1消费的消息 =" + new String(message.getBody()));
  18. }
  19. }

RoutingListener2监听器

  1. package com.qbb.listener;
  2. import org.springframework.amqp.core.Message;
  3. import org.springframework.amqp.core.MessageListener;
  4. /**
  5. * @author QiuQiu&LL (个人博客:https://www.cnblogs.com/qbbit)
  6. * @version 1.0
  7. * @date 2022-03-29 0:09
  8. * @Description:routing模式
  9. */
  10. public class RoutingListener2 implements MessageListener {
  11. @Override
  12. public void onMessage(Message message) {
  13. System.out.println("消费者2唯一标识 =" + message.getMessageProperties().getConsumerTag());
  14. System.out.println("消费者2消息唯一标识 =" + message.getMessageProperties().getDeliveryTag());
  15. System.out.println("消费者2交换机名称 =" + message.getMessageProperties().getReceivedExchange());
  16. System.out.println("消费者2路由key =" + message.getMessageProperties().getReceivedRoutingKey());
  17. System.out.println("消费者2消费的消息 =" + new String(message.getBody()));
  18. }
  19. }

TopicListener1监听器

  1. package com.qbb.listener;
  2. import org.springframework.amqp.core.Message;
  3. import org.springframework.amqp.core.MessageListener;
  4. /**
  5. * @author QiuQiu&LL (个人博客:https://www.cnblogs.com/qbbit)
  6. * @version 1.0
  7. * @date 2022-03-29 0:09
  8. * @Description:topic模式
  9. */
  10. public class TopicListener1 implements MessageListener {
  11. @Override
  12. public void onMessage(Message message) {
  13. System.out.println("消费者1唯一标识 =" + message.getMessageProperties().getConsumerTag());
  14. System.out.println("消费者1消息唯一标识 =" + message.getMessageProperties().getDeliveryTag());
  15. System.out.println("消费者1交换机名称 =" + message.getMessageProperties().getReceivedExchange());
  16. System.out.println("消费者1路由key =" + message.getMessageProperties().getReceivedRoutingKey());
  17. System.out.println("消费者1消费的消息 =" + new String(message.getBody()));
  18. }
  19. }

TopicListener2监听器

  1. package com.qbb.listener;
  2. import org.springframework.amqp.core.Message;
  3. import org.springframework.amqp.core.MessageListener;
  4. /**
  5. * @author QiuQiu&LL (个人博客:https://www.cnblogs.com/qbbit)
  6. * @version 1.0
  7. * @date 2022-03-29 0:09
  8. * @Description:topic模式
  9. */
  10. public class TopicListener2 implements MessageListener {
  11. @Override
  12. public void onMessage(Message message) {
  13. System.out.println("消费者2唯一标识 =" + message.getMessageProperties().getConsumerTag());
  14. System.out.println("消费者2消息唯一标识 =" + message.getMessageProperties().getDeliveryTag());
  15. System.out.println("消费者2交换机名称 =" + message.getMessageProperties().getReceivedExchange());
  16. System.out.println("消费者2路由key =" + message.getMessageProperties().getReceivedRoutingKey());
  17. System.out.println("消费者2消费的消息 =" + new String(message.getBody()));
  18. }
  19. }

consumer消息消费者的MQTest.java

  1. package com.qbb;
  2. import org.junit.Test;
  3. import org.junit.runner.RunWith;
  4. import org.springframework.test.context.ContextConfiguration;
  5. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
  6. /**
  7. * @author QiuQiu&LL (个人博客:https://www.cnblogs.com/qbbit)
  8. * @version 1.0
  9. * @date 2022-03-29 0:14
  10. * @Description:
  11. */
  12. @RunWith(SpringJUnit4ClassRunner.class)
  13. @ContextConfiguration(locations = "classpath:spring-rabbitmq-consumer.xml")
  14. public class MQTest {
  15. @Test
  16. public void test01() {
  17. while (true) {
  18. }
  19. }
  20. }

发布订阅模式测试据结果:

routing路由模式测试结果:

topic模式测试结果:

RabbitMQ 高级特性

15.消息的可靠性投递

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

  • confirm 确认模式
  • return 退回模式

rabbitmq 整个消息投递的路径为:

producer—>rabbitmq broker—>exchange—>queue—>consumer

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

2.消息从 exchange–>queue 投递失败则会返回一个 returnCallback 。

confirm 确认模式

修改spring-rabbitmq-producer.xml

  1. <!--配置连接工厂-->
  2. <rabbit:connection-factory
  3. id="connectionFactory"
  4. host="${rabbitmq.host}"
  5. port="${rabbitmq.port}"
  6. username="${rabbitmq.username}"
  7. password="${rabbitmq.password}"
  8. virtual-host="${rabbitmq.virtual-host}"
  9. 添加如下两行设置,开启confirmreturn模式
  10. publisher-returns="true"
  11. confirm-type="CORRELATED"/>

修改测试类MQTest.java

  1. /**
  2. * topic模式
  3. */
  4. @Test
  5. public void testTopic() {
  6. // 发送消息之前设置ConfirmCallBack回调方法
  7. rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
  8. /**
  9. * CorrelationData correlationData
  10. * boolean ack : 当消费者成功把消息发送给交换机 ack=true 发送失败 ack=false
  11. * String cause : 消息发送失败的原因
  12. */
  13. @Override
  14. public void confirm(CorrelationData correlationData, boolean ack, String cause) {
  15. if (ack) {
  16. System.out.println("消息发送成功:cause="+cause);
  17. }else {
  18. // 发送失败我们可以做其他的补救措施,例如发送给其他的交换机
  19. System.out.println("消息发送失败:cause=" + cause);
  20. }
  21. }
  22. });
  23. rabbitTemplate.convertSendAndReceive("spring-topic-exchange", "lazy.orange.qiu", "hello QiuQiu Spring-MQ-Topic-AAA");
  24. // rabbitTemplate.convertSendAndReceive("spring-topic-exchange", "qiu.ll.rabbit", "hello QiuQiu Spring-MQ-Topic-BBB");
  25. }

上面看到的是发送成功的情况,我们把交换机名字故意写错,看看会有什么效果

  1. rabbitTemplate.convertSendAndReceive("spring-topic-exchange-111", "lazy.orange.qiu", "hello QiuQiu Spring-MQ-Topic-AAA");

return 退回模式

开启return 退回模式支持,上面我们已经开启了

发送消息之前设置ReturnCallBack回调方法

  1. rabbitTemplate.setReturnsCallback(new RabbitTemplate.ReturnsCallback() {
  2. @Override
  3. public void returnedMessage(ReturnedMessage returnedMessage) {
  4. // 出错了可以指定发送给其他的queue
  5. System.out.println("returnedMessage.getExchange() = " + returnedMessage.getExchange());
  6. System.out.println("returnedMessage.getMessage() = " + returnedMessage.getMessage());
  7. System.out.println("returnedMessage.getReplyCode() = " + returnedMessage.getReplyCode());
  8. System.out.println("returnedMessage.getReplyText() = " + returnedMessage.getReplyText());
  9. System.out.println("returnedMessage.getRoutingKey() = " + returnedMessage.getRoutingKey());
  10. }
  11. });

设置交换机把消息发送给队列失败时,强制把消息回退给消息发送者(默认为false即丢失消息)

  1. rabbitTemplate.setMandatory(true);

前面两种模式我们是确保了producer->exchange和exchange->queue的消息可靠性,但是我们消息从queue->consumer我们怎么办证消息一定投递成功呢?下面我们就解决一下这个问题

其实也简单,我们只需要关闭自动ACK,然后再处理完业务逻辑后手动ACK即可

  • 修改spring-rabbitmq-consumer.xml
  1. ...
  2. <bean id="manualAckListener" class="com.qbb.listener.ManualAckListener"/>
  3. ...
  4. <rabbit:listener ref="manualAckListener" queue-names="spring-topic-queue1"/>

  • 实现ChannelAwareMessageListener监听器
  1. package com.qbb.listener;
  2. import com.rabbitmq.client.Channel;
  3. import org.springframework.amqp.core.Message;
  4. import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
  5. import java.io.IOException;
  6. /**
  7. * @author QiuQiu&LL (个人博客:https://www.cnblogs.com/qbbit)
  8. * @version 1.0
  9. * @date 2022-03-29 23:27
  10. * @Description:
  11. */
  12. public class ManualAckListener implements ChannelAwareMessageListener {
  13. @Override
  14. public void onMessage(Message message, Channel channel) throws Exception {
  15. try {
  16. System.out.println("消费者消费的消息为:"+new String(message.getBody()));
  17. // ....业务逻辑... 此处有可能出现异常从而导致消息无法正常手动确认
  18. // 手动确认
  19. channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
  20. } catch (IOException e) {
  21. e.printStackTrace();
  22. /**
  23. * 参数1: 消息唯一标识
  24. * 参数2: 是否重新入队列
  25. */
  26. // channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
  27. /**
  28. * 参数1: 消息唯一标识
  29. * 参数2: 不需要多个消费与队列确认,只要有一个消费者消费了就证明消息被消费了
  30. * 参数3: 是否重新入队列,注意如果设置为true则会出现反复死循环般的消费消息
  31. */
  32. channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
  33. }
  34. }
  35. }

测试结果:消息即可有正常消费,出现错误了也可以进行响应的补救措施,保证了消息从queue->consumer的可靠性

消息可靠性总结

1.持久化 exchange和queue持久化设置: durable="true",Spring整合RabbitMQ消息本身就是持久化的

2.生产方确认 ConfirmCallBack 和 returnCallBack

3.消费方确认 手动Ack

4.Broker 高可用,搭建集群

RabbitMQ 应用性问题

  • 消息百分百投递

假如在发送的过程中出现了网络抖动或者其他的不可逆因素,如何保证消息不丢失呢?

从上图我们可以将要消费的消息存入一个MSGDB的数据库,给它设置一个状态status=0代表未消费,当出现消费成功则修改状态为status=1,如果出现了网络故障status=0我们编写一个定时任务,指定时间把status=0的消息查询出来再次执行即可

上面的定时任务和存入将消息数据库确实可以解决一些问题,但是同时也带来了消息重复消费的问题,也就是消息幂等性问题,如何解决消息幂等性问题呢?

  • 业务ID
  • 乐观锁

16.消费端限流

修改配置文件

  1. prefetch="1"
  1. package com.qbb.listener;
  2. import com.rabbitmq.client.Channel;
  3. import org.springframework.amqp.core.Message;
  4. import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
  5. /**
  6. * @author QiuQiu&LL (个人博客:https://www.cnblogs.com/qbbit)
  7. * @version 1.0
  8. * @date 2022-03-30 0:40
  9. * @Description:
  10. */
  11. public class LimitListener1 implements ChannelAwareMessageListener {
  12. @Override
  13. public void onMessage(Message message, Channel channel) throws Exception {
  14. System.out.println("消费者1消息为:" + new String(message.getBody()));
  15. channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
  16. }
  17. }
  18. package com.qbb.listener;
  19. import com.rabbitmq.client.Channel;
  20. import org.springframework.amqp.core.Message;
  21. import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
  22. /**
  23. * @author QiuQiu&LL (个人博客:https://www.cnblogs.com/qbbit)
  24. * @version 1.0
  25. * @date 2022-03-30 0:40
  26. * @Description:
  27. */
  28. public class LimitListener2 implements ChannelAwareMessageListener {
  29. @Override
  30. public void onMessage(Message message, Channel channel) throws Exception {
  31. System.out.println("消费者2消息为:" + new String(message.getBody()));
  32. channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
  33. }
  34. }

测试结果

17.TTL消息过期时间

控制台方式操作:添加相应的队列设置过期时间,发送消息测试

代码方式操作之指定所有消息过期时间

  1. <!--==================TTL-QUEUE==================-->
  2. <rabbit:queue id="ttl-queue1" name="ttl-queue2" auto-declare="true">
  3. <rabbit:queue-arguments>
  4. <entry key="x-message-ttl" value="10000" value-type="java.lang.Integer"></entry>
  5. </rabbit:queue-arguments>
  6. </rabbit:queue>

代码方式操作之指定某个消息过期时间

  1. @Test
  2. public void testTTL2() {
  3. MessagePostProcessor messagePostProcessor = new MessagePostProcessor() {
  4. @Override
  5. public Message postProcessMessage(Message message) throws AmqpException {
  6. message.getMessageProperties().setExpiration("10000");
  7. return message;
  8. }
  9. };
  10. rabbitTemplate.convertAndSend("ttl-queue2", (Object) "qiuqiu", messagePostProcessor);
  11. }

注意:RabbitMQ只会检查队列头部的那个信息是否过期,过期及剔除,队列后面的消息即使过期了也不会剔除

18.死信队列

死信,顾名思义就是无法被消费的消息,字面意思可以这 样理解,一般来说,producer 将消息投递到 broker 或者直接到 queue 里了,consumer 从 queue 取出消息进行消费,但某些时候由于特定的原因导致 queue 中的某些消息无法被 消费,这样的消息如果没有后续的处理,就变成了死信,有死信,自然就有了死信队列;

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

1.队列消息数量到达限制;比如给队列最大只能存储10条消息,当第11条消息进来的时候存 不下了,第1条消息就被称为死信

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

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

  1. <!--==================正常QUEUE EXCHANGE==================-->
  2. <rabbit:queue id="normal-queue" name="normal-queue">
  3. <rabbit:queue-arguments>
  4. <!--绑定死信交换机-->
  5. <entry key="x-dead-letter-exchange" value="dead-exchange"/>
  6. <!--绑定routing-key-->
  7. <entry key="x-dead-letter-routing-key" value="b.c"/>
  8. <!--设置消息容量-->
  9. <entry key="x-max-length" value="10" value-type="java.lang.Integer"/>
  10. <!--统一的过期时间-->
  11. <entry key="x-message-ttl" value="10000" value-type="java.lang.Integer"/>
  12. </rabbit:queue-arguments>
  13. </rabbit:queue>
  14. <rabbit:topic-exchange name="normal-exchange">
  15. <rabbit:bindings>
  16. <rabbit:binding pattern="a.#" queue="normal-queue"></rabbit:binding>
  17. </rabbit:bindings>
  18. </rabbit:topic-exchange>
  19. <!--==================死信QUEUE EXCHANGE==================-->
  20. <rabbit:queue id="dead-queue" name="dead-queue"/>
  21. <rabbit:topic-exchange name="dead-exchange">
  22. <rabbit:bindings>
  23. <rabbit:binding pattern="b.#" queue="dead-queue"></rabbit:binding>
  24. </rabbit:bindings>
  25. </rabbit:topic-exchange>
  1. @Test
  2. public void testDeadQueue() {
  3. for (int i = 0; i < 12; i++) {
  4. rabbitTemplate.convertAndSend("normal-exchange", "a.qiu","qiuqiu" + i);
  5. }
  6. }

19.延迟队列

代码配置方式和上面的一样,就是把正常队列设置了一个消息过期时间

20.SpringBoot整合RabbitMQ

生产者:

到入依赖

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6. <parent>
  7. <groupId>org.springframework.boot</groupId>
  8. <artifactId>spring-boot-starter-parent</artifactId>
  9. <version>2.6.4</version>
  10. </parent>
  11. <groupId>com.qbb</groupId>
  12. <artifactId>springboot-mq-producer</artifactId>
  13. <version>1.0-SNAPSHOT</version>
  14. <dependencies>
  15. <dependency>
  16. <groupId>org.springframework.boot</groupId>
  17. <artifactId>spring-boot-starter-web</artifactId>
  18. </dependency>
  19. <dependency>
  20. <groupId>org.springframework.boot</groupId>
  21. <artifactId>spring-boot-starter-amqp</artifactId>
  22. </dependency>
  23. <dependency>
  24. <groupId>org.springframework.boot</groupId>
  25. <artifactId>spring-boot-starter-test</artifactId>
  26. </dependency>
  27. </dependencies>
  28. </project>

编写配置类

  1. package com.qbb.mq.config;
  2. import org.springframework.amqp.core.*;
  3. import org.springframework.beans.factory.annotation.Qualifier;
  4. import org.springframework.boot.SpringBootConfiguration;
  5. import org.springframework.context.annotation.Bean;
  6. /**
  7. * @author QiuQiu&LL (个人博客:https://www.cnblogs.com/qbbit)
  8. * @version 1.0
  9. * @date 2022-03-30 1:56
  10. * @Description:
  11. */
  12. @SpringBootConfiguration
  13. public class MQProducerConfig {
  14. public static final String EXCHANGE_NAME = "boot_topic_exchange";
  15. public static final String QUEUE_NAME = "boot_queue";
  16. //1.交换机
  17. @Bean("bootExchange")
  18. public Exchange bootExchange() {
  19. return ExchangeBuilder.topicExchange(EXCHANGE_NAME).durable(true).build();
  20. }
  21. //2.Queue 队列
  22. @Bean("bootQueue")
  23. public Queue bootQueue() {
  24. return QueueBuilder.durable(QUEUE_NAME).build();
  25. }
  26. //3. 队列和交互机绑定关系 Binding
  27. /* 1. 知道哪个队列 2. 知道哪个交换机 3. routing key */
  28. @Bean
  29. public Binding bindQueueExchange(@Qualifier("bootQueue") Queue queue, @Qualifier("bootExchange") Exchange exchange) {
  30. return BindingBuilder.bind(queue).to(exchange).with("boot.#").noargs();
  31. }
  32. }

测试一下

  1. package com.qbb.mq;
  2. import org.junit.jupiter.api.Test;
  3. import org.springframework.amqp.rabbit.core.RabbitTemplate;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.boot.test.context.SpringBootTest;
  6. /**
  7. * @author QiuQiu&LL (个人博客:https://www.cnblogs.com/qbbit)
  8. * @version 1.0
  9. * @date 2022-03-30 1:58
  10. * @Description:
  11. */
  12. @SpringBootTest
  13. public class ProducerTest {
  14. @Autowired
  15. private RabbitTemplate rabbitTemplate;
  16. @Test
  17. public void test01() {
  18. rabbitTemplate.convertSendAndReceive("boot_topic_exchange", "boot.qiu", "等我完成目标就来找你...");
  19. }
  20. }

消费者:

配置监听器类BootMessageListener

  1. @Component
  2. public class BootMessageListener {
  3. @RabbitListener(queues = "boot_queue")
  4. public void consumeMessage(Message message) {
  5. System.out.println("消息为:" + new String(message.getBody()));
  6. }
  7. }

测试结果

<<<<<<<<<<<<<<<<至此RabbitMQ知识点和常用的一些方式就都概述完毕了>>>>>>>>>>>>>>>>

RabbitMQ入门到进阶(Spring整合RabbitMQ&SpringBoot整合RabbitMQ)的更多相关文章

  1. RabbitMQ入门:在Spring Boot 应用中整合RabbitMQ

    在上一篇随笔中我们认识并安装了RabbitMQ,接下来我们来看下怎么在Spring Boot 应用中整合RabbitMQ. 先给出最终目录结构: 搭建步骤如下: 新建maven工程amqp 修改pom ...

  2. 3、SpringBoot整合之SpringBoot整合JDBC

    SpringBoot整合JDBC 一.创建SpringBoot项目 选择Spring Web.JDBC API.MySQL Driver 二.在pom配置文件中修改JDBC版本,导入lombok &l ...

  3. 1、SpringBoot整合之SpringBoot整合JSP

    SpringBoot整合JSP 一.创建SpringBoot项目,仅选择Web模块即可 二.在POM文件中添加依赖 <!-- 添加servlet依赖模块 --> <dependenc ...

  4. 5、SpringBoot整合之SpringBoot整合MybatisPlus

    SpringBoot整合MybatisPlus 目录(可点击直接跳转,但还是建议按照顺序观看,四部分具有一定的关联性): 实现基础的增删改查 实现自动填充功能 实现逻辑删除 实现分页 首先给出四部分完 ...

  5. 8、SpringBoot整合之SpringBoot整合MongoDB

    SpringBoot整合MongoDB 一.创建项目,选择依赖 仅选择Spring Web.Spring Data MongoDB即可 二.引入相关依赖(非必要) 这里只是为了实体类的创建方便而引入l ...

  6. 9、SpringBoot整合之SpringBoot整合SpringSecurity

    SpringBoot整合SpringSecurity 一.创建项目,选择依赖 选择Spring Web.Thymeleaf即可 二.在pom文件中导入相关依赖 <!-- 导入SpringSecu ...

  7. 2、SpringBoot整合之SpringBoot整合servlet

    SpringBoot整合servlet 一.创建SpringBoot项目,仅选择Web模块即可 二.在POM文件中添加依赖 <!-- 添加servlet依赖模块 --> <depen ...

  8. springboot入门系列(二):SpringBoot整合Swagger

    上一篇<简单搭建SpringBoot项目>讲了简单的搭建SpringBoot 项目,而 SpringBoot 和 Swagger-ui 搭配在持续交付的前后端开发中意义重大,Swagger ...

  9. RabbitMQ入门:总结

    随着上一篇博文的发布,RabbitMQ的基础内容我也学习完了,RabbitMQ入门系列的博客跟着收官了,以后有机会的话再写一些在实战中的应用分享,多谢大家一直以来的支持和认可. RabbitMQ入门系 ...

随机推荐

  1. 聊聊几个阿里 P8、P9 程序员的故事

    大家好,我是对白. 阿里 P8 程序员年薪百万已经是公开的秘密了,有人关心他们年薪百万,而我更加关注阿里这些 P8.P9 程序员的成长故事,在聊这些大牛的故事之前,跟大家稍微简单聊下阿里技术人等级制度 ...

  2. ESP32-S3 arduino 开发环境搭建

    ESP32-S3 arduino 简要描述 在github上搜索arduino-esp32,找到并打开espressif/arduino-esp32仓库,从master主分支切换到esp32-s3-s ...

  3. monowall

    https://www.cat-home.org/?action=show&id=158

  4. 简单excel饼状图怎么做,bi工具怎么做饼状图

    饼状图是为了在一个整体体现个体所占的比例,比如一块蛋糕每人各分多大份.了解了饼状图的含义,就来学习饼状图怎么做吧. 首先,我们准备excel表格饼状图的初始数据 然后选择excel表格上方的插入,选择 ...

  5. 【C# Parallel】开端

    使用条件 1.必须熟练掌握锁.死锁.task的知识,他是建立这两个的基础上的.task建立在线程和线程池上的. 2.并不是所有代码都适合并行化. 例如,如果某个循环在每次迭代时只执行少量工作,或它在很 ...

  6. 小白学python第2问: 为什么只有int,没有long?

    为什么只有int,没有long? 在python官网开发者指引里面能找到 PEP 237 -- Unifying Long Integers and Integers,这里说明了为什么要统一 int ...

  7. @vue/cli的配置知道多少-publicPath,outputDir,assetsDir,indexPath,filenameHashing,configureWebpack,productionSourceMap

    vue.config.js的简单介绍 vue.config.js 是一个可选的配置文件, 在项目的 (和 package.json 同级的) 根目录中存在这个文件. 默认情况没有这个文件需要我们手动去 ...

  8. 什么是NFT?

    我有一个年轻朋友,最近买了一个数字艺术品,9百多入手,几周后卖掉,赚了7万多,他告诉我这个东西叫NFT. 2021年twitter创始人杰克.多西将自己发布的第一条twitter通过NFT以250万美 ...

  9. 哈工大 计算机系统 实验七 TinyShell

    所有实验文件可见github 计算机系统实验整理 实验报告 实 验(七) 题 目 TinyShell 微壳 计算机科学与技术学院 目 录 第1章 实验基本信息 - 4 - 1.1 实验目的 - 4 - ...

  10. 控制台console不打印信息的解决办法

    一直用控制台调试,突然不知道怎么回事看不到控制台输出的信息了: 需要检查下面几方面的问题: 1:我的就属于第一个问题,不知道怎么搜索的时候就改变了Filter; 2:确保以上选项是勾选的 3:点击设置 ...