赞
踩
提示:以下是本篇文章正文内容,下面案例可供参考
MQ全称 Message Queue(消息队列),是在消息的传输过程中保存消息的容器。多用于分布式系统之间进行通信。
应用之间的远程调用
加入MQ后应用之间的调用
MQ相当于一个中介,生产方通过MQ与消费方交互,它将应用程序进行解耦合。
系统的耦合性越高,容错性就越低,可维护性就越低。
使用 MQ 使得应用间解耦,提升容错性和可维护性。
将不需要同步处理的并且耗时长的操作由消息队列通知消息接收方进行异步处理。提高了应用程序的响应时间。
一个下单操作耗时:20 + 300 + 300 + 300 = 920ms
用户点击完下单按钮后,需要等待920ms才能得到下单响应,太慢!
用户点击完下单按钮后,只需等待25ms就能得到下单响应 (20 + 5 = 25ms)。
提升用户体验和系统吞吐量(单位时间内处理请求的数目)。
如订单系统,在下单的时候就会往数据库写数据。但是数据库只能支撑每秒1000左右的并发写入,并发量再高就容易宕机。低峰期的时候并发也就100多个,但是在高峰期时候,并发量会突然激增到5000以上,这个时候数据库肯定卡死了。
于是可以将信息放入MQ,消息被MQ保存起来了,然后系统就可以按照自己的消费能力来消费,比如每秒1000个消息,这样慢慢写入数据库,这样就不会卡死数据库了。
但是使用了MQ之后,限制消费消息的速度为1000,但是这样一来,高峰期产生的数据势必会被积压在MQ中,高峰就被“削”掉了。但是因为消息积压,在高峰期过后的一段时间内,消费消息的速度还是会维持在1000QPS,直到消费完积压的消息,这就叫做“填谷”
系统可用性降低
系统引入的外部依赖越多,系统稳定性越差。一旦 MQ 宕机,就会对业务造成影响。如何保证MQ的高可用?
系统复杂度提高
MQ 的加入大大增加了系统的复杂度,以前系统间是同步的远程调用,现在是通过 MQ 进行异步调用。如何保证消息没有被重复消费?怎么处理消息丢失情况?那么保证消息传递的顺序性?
一致性问题
A 系统处理完业务,通过 MQ 给B、C、D三个系统发消息,如果 B 系统、C 系统处理成功,D 系统处理失败。如何保证消息数据处理的一致性?
参考链接: https://www.jianshu.com/p/4491cba335d1
实现MQ的大致有两种主流方式:AMQP、JMS。
AMQP
AMQP,即 Advanced Message Queuing Protocol(高级消息队列协议),是一个网络协议,是应用层协议的一个开放标准,为面向消息的中间件设计。基于此协议的客户端与消息中间件可传递消息,遵循此协议,不受客户端和中间件产品和开发语言限制。2006年,AMQP 规范发布。类比HTTP。
JMS
JMS 即 Java 消息服务(JavaMessage Service)应用程序接口,是一个 Java 平台中关于面向消息中间件的API
JMS 是 JavaEE 规范中的一种,类比JDBC
很多消息中间件都实现了JMS规范,例如:ActiveMQ。RabbitMQ 官方没有提供 JMS 的实现包,但是开源社区有。
AMQP 与 JMS 区别
2007年,Rabbit 技术公司基于 AMQP 标准开发的 RabbitMQ 1.0 发布。RabbitMQ 采用 Erlang 语言开发。Erlang 语言专门为开发高并发和分布式系统的一种语言,在电信领域使用广泛。
RabbitMQ 中的相关概念:
RabbitMQ提供了6种模式:简单模式,work模式,Publish/Subscribe发布与订阅模式,Routing路由模式,Topics主题模式,RPC远程调用模式(远程调用,不太算MQ);
在上图的模型中,有以下概念:
生产者
import com.lxs.rabbitmq.utils.ConnectionUtils; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; import java.io.IOException; import java.util.concurrent.TimeoutException; public class Producer { public static String QUEUE_NAME = "simple_queue"; public static void main(String[] args) throws IOException, TimeoutException { Connection connection = ConnectionUtils.getConnection(); //创建频道 Channel channel = connection.createChannel(); //声明(创建)队列 /** * 参数1:队列名称 * 参数2:是否定义持久化队列 * 参数3:是否独占本次连接,只能有一个Consumer监听这个队列 * 参数4:是否在不使用的时候自动删除队列,当没有Consumer时,自动删除 * 参数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(); } }
在执行上述的消息发送之后;可以登录rabbitMQ的管理控制台,可以发现队列和其消息:
消费者
import com.lxs.rabbitmq.utils.ConnectionUtils; import com.rabbitmq.client.*; import java.io.IOException; import java.util.concurrent.TimeoutException; public class Consumer { public static void main(String[] args) throws IOException, TimeoutException { Connection connection = ConnectionUtils.getConnection(); //创建频道 Channel channel = connection.createChannel(); //声明(创建)队列 /** * 参数1:队列名称 * 参数2:是否定义持久化队列 * 参数3:是否独占本次连接,只能有一个Consumer监听这个队列 * 参数4:是否在不使用的时候自动删除队列,当没有Consumer时,自动删除 * 参数5:队列其它参数 */ channel.queueDeclare(Producer.QUEUE_NAME, true, false, false, null); //接收消息 DefaultConsumer consumer = new DefaultConsumer(channel) { /** * 接收到消息执行的的回调 * consumerTag 消息者标签,在channel.basicConsume时候可以指定 * envelope 消息包的内容,可从中获取消息id,消息routingkey,交换机,消息和重传标志(收到消息失败后是否需要重新发送) * properties 属性信息 * body 消息 */ @Override 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(); } }
Work Queues 与入门程序的 简单模式 相比,多了一个或一些消费端,多个消费端共同消费同一个队列中的消息。
应用场景:对于任务过重或任务较多情况使用工作队列可以提高任务处理的速度。
生产者
import com.lxs.rabbitmq.utils.ConnectionUtils; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import java.io.IOException; import java.util.concurrent.TimeoutException; public class Producer { public static String QUEUE_NAME = "work_queue"; public static void main(String[] args) throws IOException, TimeoutException { Connection connection = ConnectionUtils.getConnection(); //创建频道 Channel channel = connection.createChannel(); //声明(创建)队列 /** * 参数1:队列名称 * 参数2:是否定义持久化队列 * 参数3:是否独占本次连接,只能有一个Consumer监听这个队列 * 参数4:是否在不使用的时候自动删除队列,当没有Consumer时,自动删除 * 参数5:队列其它参数 */ channel.queueDeclare(QUEUE_NAME, true, false, false, null); for (int i = 1; i <= 30; i++) { //发送消息 String message = "你好:小兔子~ work queue模式---" + i; /** * 参数1:交换机名称,如果没有指定则使用默认Default Exchage * 参数2:路由key,简单模式可以传递队列名称 * 参数3:消息其它属性 * 参数4:消息内容 */ channel.basicPublish("", QUEUE_NAME, null, message.getBytes()); System.out.println("已发送消息:" + message); } //释放资源 channel.close(); connection.close(); } }
消费者A
import com.lxs.rabbitmq.utils.ConnectionUtils; import com.rabbitmq.client.*; import java.io.IOException; import java.util.concurrent.TimeoutException; public class Consumer1 { public static void main(String[] args) throws IOException, TimeoutException { Connection connection = ConnectionUtils.getConnection(); //创建频道 Channel channel = connection.createChannel(); //声明(创建)队列 /** * 参数1:队列名称 * 参数2:是否定义持久化队列 * 参数3:是否独占本次连接,只能有一个Consumer监听这个队列 * 参数4:是否在不使用的时候自动删除队列,当没有Consumer时,自动删除 * 参数5:队列其它参数 */ channel.queueDeclare(Producer.QUEUE_NAME, true, false, false, null); //接收消息 DefaultConsumer consumer = new DefaultConsumer(channel) { /** * 接收到消息执行的的回调 * consumerTag 消息者标签,在channel.basicConsume时候可以指定 * envelope 消息包的内容,可从中获取消息id,消息routingkey,交换机,消息和重传标志(收到消息失败后是否需要重新发送) * properties 属性信息 * body 消息 */ @Override 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.QUEUE_NAME, true, consumer); //释放资源 // channel.close(); // connection.close(); } }
消费者B
import com.lxs.rabbitmq.utils.ConnectionUtils; import com.rabbitmq.client.*; import java.io.IOException; import java.util.concurrent.TimeoutException; public class Consumer2 { public static void main(String[] args) throws IOException, TimeoutException { Connection connection = ConnectionUtils.getConnection(); //创建频道 Channel channel = connection.createChannel(); //声明(创建)队列 /** * 参数1:队列名称 * 参数2:是否定义持久化队列 * 参数3:是否独占本次连接,只能有一个Consumer监听这个队列 * 参数4:是否在不使用的时候自动删除队列,当没有Consumer时,自动删除 * 参数5:队列其它参数 */ channel.queueDeclare(Producer.QUEUE_NAME, true, false, false, null); //接收消息 DefaultConsumer consumer = new DefaultConsumer(channel) { /** * 接收到消息执行的的回调 * consumerTag 消息者标签,在channel.basicConsume时候可以指定 * envelope 消息包的内容,可从中获取消息id,消息routingkey,交换机,消息和重传标志(收到消息失败后是否需要重新发送) * properties 属性信息 * body 消息 */ @Override 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.QUEUE_NAME, true, consumer); //释放资源 // channel.close(); // connection.close(); } }
启动两个消费者,然后再启动生产者发送消息;到IDEA的两个消费者对应的控制台查看是否竞争性的接收到消息
在一个队列中如果有多个消费者,那么消费者之间对于同一个消息的关系是竞争的关系。
订阅模式示例图:
前面2个案例中,只有3个角色:
而在订阅模型中,多了一个exchange角色,而且过程略有变化:
Exchange(交换机)只负责转发消息,不具备存储消息的能力,因此如果没有任何队列与Exchange绑定,或者没有符合路由规则的队列,那么消息会丢失!
模式说明
发布订阅模式: 1、每个消费者监听自己的队列。 2、生产者将消息发给broker,由交换机将消息转发到绑定此交换机的每个队列,每个绑定交换机的队列都将接收到消息
生产者
import com.lxs.rabbitmq.utils.ConnectionUtils; import com.rabbitmq.client.BuiltinExchangeType; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import java.io.IOException; import java.util.concurrent.TimeoutException; public class Producer { public static String FANOUT_EXCHAGE = "fanout_exchage"; public static String FANOUT_QUEUE_1 = "fanout_queue_1"; public static String FANOUT_QUEUE_2 = "fanout_queue_2"; public static void main(String[] args) throws IOException, TimeoutException { Connection connection = ConnectionUtils.getConnection(); //创建频道 Channel channel = connection.createChannel(); /**声明交换机 * 参数1:交换机名称 * 参数2:交换机类型,fanout, topic, direct, headers */ channel.exchangeDeclare(FANOUT_EXCHAGE, BuiltinExchangeType.FANOUT); //声明(创建)队列 /** * 参数1:队列名称 * 参数2:是否定义持久化队列 * 参数3:是否独占本次连接,只能有一个Consumer监听这个队列 * 参数4:是否在不使用的时候自动删除队列,当没有Consumer时,自动删除 * 参数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 = "你好:小兔子~ fanout 模式---" + i; /** * 参数1:交换机名称,如果没有指定则使用默认Default Exchage * 参数2:路由key,简单模式可以传递队列名称 * 参数3:消息其它属性 * 参数4:消息内容 */ channel.basicPublish(FANOUT_EXCHAGE, "", null, message.getBytes()); System.out.println("已发送消息:" + message); } //释放资源 channel.close(); connection.close(); } }
消费者1
import com.lxs.rabbitmq.utils.ConnectionUtils; import com.rabbitmq.client.*; import java.io.IOException; import java.util.concurrent.TimeoutException; public class Consumer1 { public static void main(String[] args) throws IOException, TimeoutException { Connection connection = ConnectionUtils.getConnection(); //创建频道 Channel channel = connection.createChannel(); //声明(创建)队列 /** * 参数1:队列名称 * 参数2:是否定义持久化队列 * 参数3:是否独占本次连接,只能有一个Consumer监听这个队列 * 参数4:是否在不使用的时候自动删除队列,当没有Consumer时,自动删除 * 参数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) { /** * 接收到消息执行的的回调 * consumerTag 消息者标签,在channel.basicConsume时候可以指定 * envelope 消息包的内容,可从中获取消息id,消息routingkey,交换机,消息和重传标志(收到消息失败后是否需要重新发送) * properties 属性信息 * body 消息 */ @Override 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); //释放资源 // channel.close(); // connection.close(); } }
消费者2
import com.lxs.rabbitmq.utils.ConnectionUtils; import com.rabbitmq.client.*; import java.io.IOException; import java.util.concurrent.TimeoutException; public class Consumer2 { public static void main(String[] args) throws IOException, TimeoutException { Connection connection = ConnectionUtils.getConnection(); //创建频道 Channel channel = connection.createChannel(); //声明(创建)队列 /** * 参数1:队列名称 * 参数2:是否定义持久化队列 * 参数3:是否独占本次连接,只能有一个Consumer监听这个队列 * 参数4:是否在不使用的时候自动删除队列,当没有Consumer时,自动删除 * 参数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) { /** * 接收到消息执行的的回调 * consumerTag 消息者标签,在channel.basicConsume时候可以指定 * envelope 消息包的内容,可从中获取消息id,消息routingkey,交换机,消息和重传标志(收到消息失败后是否需要重新发送) * properties 属性信息 * body 消息 */ @Override 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); //释放资源 // channel.close(); // connection.close(); } }
模式说明
路由模式特点:
图解:
在编码上与 Publish/Subscribe发布与订阅模式 的区别是交换机的类型为:Direct,还有队列绑定交换机的时候需要指定routing key。
生产者
package com.lxs.rabbitmq.routing; import com.lxs.rabbitmq.utils.ConnectionUtils; import com.rabbitmq.client.BuiltinExchangeType; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import java.io.IOException; import java.util.concurrent.TimeoutException; public class Producer { public static String DIRECT_EXCHAGE = "direct_exchage"; public static String DIRECT_QUEUE_INSERT = "direct_queue_insert"; public static String DIRECT_QUEUE_UPDATE = "direct_queue_update"; public static void main(String[] args) throws IOException, TimeoutException { Connection connection = ConnectionUtils.getConnection(); //创建频道 Channel channel = connection.createChannel(); /**声明交换机 * 参数1:交换机名称 * 参数2:交换机类型,fanout, topic, direct, headers */ channel.exchangeDeclare(DIRECT_EXCHAGE, BuiltinExchangeType.DIRECT); //声明(创建)队列 /** * 参数1:队列名称 * 参数2:是否定义持久化队列 * 参数3:是否独占本次连接,只能有一个Consumer监听这个队列 * 参数4:是否在不使用的时候自动删除队列,当没有Consumer时,自动删除 * 参数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(); } }
消费者1
package com.lxs.rabbitmq.routing; import com.lxs.rabbitmq.utils.ConnectionUtils; import com.rabbitmq.client.*; import java.io.IOException; import java.util.concurrent.TimeoutException; public class Consumer1 { public static void main(String[] args) throws IOException, TimeoutException { Connection connection = ConnectionUtils.getConnection(); //创建频道 Channel channel = connection.createChannel(); //声明(创建)队列 /** * 参数1:队列名称 * 参数2:是否定义持久化队列 * 参数3:是否独占本次连接,只能有一个Consumer监听这个队列 * 参数4:是否在不使用的时候自动删除队列,当没有Consumer时,自动删除 * 参数5:队列其它参数 */ channel.queueDeclare(Producer.DIRECT_EXCHAGE, true, false, false, null); //队列绑定交换机 channel.queueBind(Producer.DIRECT_QUEUE_INSERT, Producer.DIRECT_EXCHAGE, "insert"); //接收消息 DefaultConsumer consumer = new DefaultConsumer(channel) { /** * 接收到消息执行的的回调 * consumerTag 消息者标签,在channel.basicConsume时候可以指定 * envelope 消息包的内容,可从中获取消息id,消息routingkey,交换机,消息和重传标志(收到消息失败后是否需要重新发送) * properties 属性信息 * body 消息 */ @Override 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); //释放资源 // channel.close(); // connection.close(); } }
消费者2
package com.lxs.rabbitmq.routing; import com.lxs.rabbitmq.utils.ConnectionUtils; import com.rabbitmq.client.*; import java.io.IOException; import java.util.concurrent.TimeoutException; public class Consumer2 { public static void main(String[] args) throws IOException, TimeoutException { Connection connection = ConnectionUtils.getConnection(); //创建频道 Channel channel = connection.createChannel(); //声明(创建)队列 /** * 参数1:队列名称 * 参数2:是否定义持久化队列 * 参数3:是否独占本次连接,只能有一个Consumer监听这个队列 * 参数4:是否在不使用的时候自动删除队列,当没有Consumer时,自动删除 * 参数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) { /** * 接收到消息执行的的回调 * consumerTag 消息者标签,在channel.basicConsume时候可以指定 * envelope 消息包的内容,可从中获取消息id,消息routingkey,交换机,消息和重传标志(收到消息失败后是否需要重新发送) * properties 属性信息 * body 消息 */ @Override 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); //释放资源 // channel.close(); // connection.close(); } }
启动所有消费者,然后使用生产者发送消息;在消费者对应的控制台可以查看到生产者发送对应routing key对应队列的消息;到达按照需要接收的效果。
在执行完测试代码后,其实到RabbitMQ的管理后台找到 Exchanges 选项卡,点击 direct_exchange的交换机,可以查看到如下的绑定:
Routing模式要求队列在绑定交换机时要指定routing key,消息会转发到符合routing key的队列。
模式说明
Topic 类型与 Direct 相比,都是可以根据 RoutingKey 把消息路由到不同的队列。只不过 Topic 类型Exchange 可以让队列在绑定 Routing key 的时候使用通配符!
Routingkey 一般都是有一个或多个单词组成,多个单词之间以”.”分割,例如: item.insert
通配符规则:
/ # :匹配一个或多个词
/ * :匹配不多不少恰好1个词
举例:
item.# :能够匹配 item.insert.abc 或者 item.insert
item.* :只能匹配 item.insert
生产者
package com.lxs.rabbitmq.topic; import com.lxs.rabbitmq.utils.ConnectionUtils; import com.rabbitmq.client.BuiltinExchangeType; import com.rabbitmq.client.Channel; import com.rabbitmq.client.Connection; import java.io.IOException; import java.util.concurrent.TimeoutException; public class Producer { public static String TOPIC_EXCHAGE = "topic_exchage"; public static String TOPIC_QUEUE_ALL = "topic_queue_all"; public static String TOPIC_QUEUE_INSERT_UPDATE = "topic_queue_insert_update"; public static void main(String[] args) throws IOException, TimeoutException { Connection connection = ConnectionUtils.getConnection(); //创建频道 Channel channel = connection.createChannel(); /**声明交换机 * 参数1:交换机名称 * 参数2:交换机类型,fanout, topic, direct, headers */ channel.exchangeDeclare(TOPIC_EXCHAGE, BuiltinExchangeType.TOPIC); //发送消息 String message = "新增商品。 topic模式:routing key item.insert"; /** * 参数1:交换机名称,如果没有指定则使用默认Default Exchage * 参数2:路由key,简单模式可以传递队列名称 * 参数3:消息其它属性 * 参数4:消息内容 */ channel.basicPublish(TOPIC_EXCHAGE, "item.insert", null, message.getBytes()); System.out.println("已发送消息:" + message); //发送消息 message = "修改商品。 topic模式:routing key item.update"; /** * 参数1:交换机名称,如果没有指定则使用默认Default Exchage * 参数2:路由key,简单模式可以传递队列名称 * 参数3:消息其它属性 * 参数4:消息内容 */ channel.basicPublish(TOPIC_EXCHAGE, "item.update", null, message.getBytes()); System.out.println("已发送消息:" + message); //发送消息 message = "删除商品。 topic模式:routing key item.delete"; /** * 参数1:交换机名称,如果没有指定则使用默认Default Exchage * 参数2:路由key,简单模式可以传递队列名称 * 参数3:消息其它属性 * 参数4:消息内容 */ channel.basicPublish(TOPIC_EXCHAGE, "item.delete", null, message.getBytes()); System.out.println("已发送消息:" + message); //释放资源 channel.close(); connection.close(); } }
消费者1
package com.lxs.rabbitmq.topic; import com.lxs.rabbitmq.utils.ConnectionUtils; import com.rabbitmq.client.*; import java.io.IOException; import java.util.concurrent.TimeoutException; public class Consumer1 { public static void main(String[] args) throws IOException, TimeoutException { Connection connection = ConnectionUtils.getConnection(); //创建频道 Channel channel = connection.createChannel(); //声明交换机 channel.exchangeDeclare(Producer.TOPIC_EXCHAGE, BuiltinExchangeType.TOPIC); //声明(创建)队列 /** * 参数1:队列名称 * 参数2:是否定义持久化队列 * 参数3:是否独占本次连接,只能有一个Consumer监听这个队列 * 参数4:是否在不使用的时候自动删除队列,当没有Consumer时,自动删除 * 参数5:队列其它参数 */ channel.queueDeclare(Producer.TOPIC_QUEUE_ALL, true, false, false, null); //队列绑定交换机 channel.queueBind(Producer.TOPIC_QUEUE_ALL, Producer.TOPIC_EXCHAGE, "item.*"); //接收消息 DefaultConsumer consumer = new DefaultConsumer(channel) { /** * 接收到消息执行的的回调 * consumerTag 消息者标签,在channel.basicConsume时候可以指定 * envelope 消息包的内容,可从中获取消息id,消息routingkey,交换机,消息和重传标志(收到消息失败后是否需要重新发送) * properties 属性信息 * body 消息 */ @Override 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_ALL, true, consumer); //释放资源 // channel.close(); // connection.close(); } }
消费者2
package com.lxs.rabbitmq.topic; import com.lxs.rabbitmq.utils.ConnectionUtils; import com.rabbitmq.client.*; import java.io.IOException; import java.util.concurrent.TimeoutException; public class Consumer2 { public static void main(String[] args) throws IOException, TimeoutException { Connection connection = ConnectionUtils.getConnection(); //创建频道 Channel channel = connection.createChannel(); //声明交换机 channel.exchangeDeclare(Producer.TOPIC_EXCHAGE, BuiltinExchangeType.TOPIC); //声明(创建)队列 /** * 参数1:队列名称 * 参数2:是否定义持久化队列 * 参数3:是否独占本次连接,只能有一个Consumer监听这个队列 * 参数4:是否在不使用的时候自动删除队列,当没有Consumer时,自动删除 * 参数5:队列其它参数 */ channel.queueDeclare(Producer.TOPIC_QUEUE_INSERT_UPDATE, true, false, false, null); //队列绑定交换机 channel.queueBind(Producer.TOPIC_QUEUE_INSERT_UPDATE, Producer.TOPIC_EXCHAGE, "item.update"); channel.queueBind(Producer.TOPIC_QUEUE_INSERT_UPDATE, Producer.TOPIC_EXCHAGE, "item.insert"); //接收消息 DefaultConsumer consumer = new DefaultConsumer(channel) { /** * 接收到消息执行的的回调 * consumerTag 消息者标签,在channel.basicConsume时候可以指定 * envelope 消息包的内容,可从中获取消息id,消息routingkey,交换机,消息和重传标志(收到消息失败后是否需要重新发送) * properties 属性信息 * body 消息 */ @Override 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_INSERT_UPDATE, true, consumer); //释放资源 // channel.close(); // connection.close(); } }
依赖
## 主要引入rabbit依赖
<dependency>
<groupId>org.springframework.amqp</groupId>
<artifactId>spring-rabbit</artifactId>
<version>2.1.8.RELEASE</version>
</dependency>
消息发送服务
配置文件
rabbitmq.host=ip
rabbitmq.port=5672
rabbitmq.username=xxx
rabbitmq.password=xxx
rabbitmq.virtual-host=/xxx
<?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>
@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的消息"); } }
信息接受服务
<dependency>
<groupId>org.springframework.amqp</groupId>
<artifactId>spring-rabbit</artifactId>
<version>2.1.8.RELEASE</version>
</dependency>
<?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>
package com.lxs.rabbitmq.listener; import org.springframework.amqp.core.Message; import org.springframework.amqp.core.MessageListener; public class SpringQueueListener implements MessageListener { @Override 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(); } } }
在Spring项目中,可以使用Spring-Rabbit去操作RabbitMQ
尤其是在spring boot项目中只需要引入对应的amqp启动器依赖即可,方便的使用RabbitTemplate发送消息,使用注解接收消息。
一般在开发过程中:
生产者工程:
消费者功能:
生产者工程
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
spring:
rabbitmq:
host: ip
port: 5672
virtual-host: /xxx
username: xxx
password: xxx
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"; /** * 声明交换机 * @return */ @Bean public Exchange itemTopicExchange() { return ExchangeBuilder.topicExchange(ITEM_TOPIC_EXCHANGE).durable(true).build(); } @Bean 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(); } }
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"); } }
先运行上述测试程序(交换机和队列才能先被声明和绑定),然后启动消费者;
消费者工程
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
spring:
rabbitmq:
host: ip
port: 5672
virtual-host: /xxx
username: xxx
password: xxx
package com.lxs.rabbitmq.listener;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
@Component
public class MyListener {
@RabbitListener(queues = "springboot_item_queue")
public void myListener1(String message) {
System.out.println("消费者接收到的消息为:" + message);
}
}
在使用 RabbitMQ 的时候,作为消息发送方希望杜绝任何消息丢失或者投递失败场景。RabbitMQ 为我们提供了两种方式用来控制消息的投递可靠性模式。
rabbitmq 整个消息投递的路径为:
producer—>rabbitmq broker—>exchange—>queue—>consumer
我们将利用这两个 callback 控制消息的可靠性投递
1.确认模式
SpringBoot环境
spring:
rabbitmq:
listener:
simple: #对应模式
acknowledge-mode: manual #ack 手动确认
direct: #对应模式
acknowledge-mode: manual
#消息从 producer 到 exchange 则会返回一个 confirmCallback,确认模式
publisher-confirm-type: simple
#消息从 exchange-->queue 投递失败则会返回一个 returnCallback,退回模式
publisher-returns: true
代码实现
//确认模式 rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() { /** * * @param correlationData 相关配置信息 * @param ack exchange交换机 是否成功收到了消息。true 成功,false代表失败 * @param cause 失败原因 */ @Override public void confirm(CorrelationData correlationData, boolean ack, String cause) { if (!ack){ System.out.println("------------用户到路由信息丢失----------"); System.out.println("失败原因:"+cause); } } });
2.确认模式
SpringBoot环境
spring:
rabbitmq:
listener:
simple: #对应模式
acknowledge-mode: manual #ack 手动确认
direct: #对应模式
acknowledge-mode: manual
#消息从 producer 到 exchange 则会返回一个 confirmCallback,确认模式
publisher-confirm-type: simple
#消息从 exchange-->queue 投递失败则会返回一个 returnCallback,退回模式
publisher-returns: true
代码实现
//退回模式 rabbitTemplate.setMandatory(true); 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("TO"+exchange+"---"+replyText); } });
Consumer Ack
ack指Acknowledge,确认。 表示消费端收到消息后的确认方式。
有三种确认方式:
其中自动确认是指,当消息一旦被Consumer接收到,则自动确认收到,并将相应 message 从RabbitMQ 的消息缓存中移除。但是在实际业务处理中,很可能消息接收到,业务处理出现异常,那么该消息就会丢失。如果设置了手动确认方式,则需要在业务处理成功后,调用channel.basicAck(),手动签收,如果出现异常,则调用channel.basicNack()方法,让其自动重新发送消息。
配置文件
spring:
rabbitmq:
listener:
simple: #对应模式
acknowledge-mode: manual #ack 手动确认
direct: #对应模式
acknowledge-mode: manual
代码实现
//1.成功确认 /** * 手动确认: * deliveryTag:该消息的index(message.getMessageProperties().getDeliveryTag()) * multiple:是否批量处理.true:将一次性ack所有小于deliveryTag的消息 (1,2两条信息 true:当前为2 则1自动确认) * * 告诉服务器收到这条消息 已经被我消费了 可以在队列删掉 这样以后就不会再发了 否则消息服务器以为这条消息没处理掉 后续还会在发 */ channel.basicAck(message.getMessageProperties().getDeliveryTag(),false); //2.失败确认 /** * multiple: 仅是代表当前下标信息 * requeue: 是否重新放回队列 */ channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
Time To Live,消息过期时间设置
控制台中设置队列TTL
@Bean
public Queue ttlQueue(){
return QueueBuilder.durable(env.getProperty("mq.order.queue.ttl"))
// 队列的过期时间,测试数据x秒过期
.withArgument("x-message-ttl",30000)
.build();
}
死信队列,英文缩写:DLX 。Dead Letter Exchange(死信交换机),当消息成为Dead message后,可以被重新发送到另一个交换机,这个交换机就是DLX。
消息成为死信的三种情况:
队列绑定死信交换机:
给队列设置参数: x-dead-letter-exchange 和 x-dead-letter-routing-key
package com.lxs.legou.order.config; import org.springframework.amqp.core.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; /** * @Auther: Mcb * @Description: 延迟队列配置,30分钟未支付订单,取消订单,回滚库存 */ @Configuration public class MqConfig { @Autowired private Environment env; @Bean public Exchange ttlExchange(){ return ExchangeBuilder.directExchange(env.getProperty("mq.order.exchange.ttl")).durable(true).build(); } @Bean public Queue ttlQueue(){ return QueueBuilder.durable(env.getProperty("mq.order.queue.ttl")) // 队列的过期时间,测试数据x秒过期 .withArgument("x-message-ttl",30000) // 指定死信交换机 .withArgument("x-dead-letter-exchange",env.getProperty("mq.order.exchange.dlx")) // 设置死信队列路由key .withArgument("x-dead-letter-routing-key",env.getProperty("mq.order.routing.dlx")) .build(); } /** * 正常交换机,队列绑定 * @param queue * @param exchange * @return */ @Bean public Binding ttlBinding(@Qualifier("ttlQueue") Queue queue, @Qualifier("ttlExchange") Exchange exchange) { return BindingBuilder.bind(queue).to(exchange).with(env.getProperty("mq.order.routing.ttl")).noargs(); } /** * 死信交换机 * @return */ @Bean public Exchange dlxExchange(){ return ExchangeBuilder.directExchange(env.getProperty("mq.order.exchange.dlx")).durable(true).build(); } /** * 死信队列 * @return */ @Bean public Queue dlxQueue() { return QueueBuilder.durable(env.getProperty("mq.order.queue.dlx")).build(); } /** * 死信交换机,队列绑定 * @param queue * @param exchange * @return */ @Bean public Binding dlxBinding(@Qualifier("dlxQueue") Queue queue, @Qualifier("dlxExchange") Exchange exchange) { return BindingBuilder.bind(queue).to(exchange).with(env.getProperty("mq.order.routing.dlx")).noargs(); } }
延迟队列,即消息进入队列后不会立即被消费,只有到达指定时间后,才会被消费。在RabbitMQ中延迟队列的实现主要依靠于TTL+死信队列
package com.lxs.legou.order.config; import org.springframework.amqp.core.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; /** * @Auther: Mcb * @Description: 延迟队列配置,30分钟未支付订单,取消订单,回滚库存 */ @Configuration public class MqConfig { @Autowired private Environment env; @Bean public Exchange ttlExchange(){ return ExchangeBuilder.directExchange(env.getProperty("mq.order.exchange.ttl")).durable(true).build(); } @Bean public Queue ttlQueue(){ return QueueBuilder.durable(env.getProperty("mq.order.queue.ttl")) // 队列的过期时间,测试数据x秒过期 .withArgument("x-message-ttl",30000) // 指定死信交换机 .withArgument("x-dead-letter-exchange",env.getProperty("mq.order.exchange.dlx")) // 设置死信队列路由key .withArgument("x-dead-letter-routing-key",env.getProperty("mq.order.routing.dlx")) .build(); } /** * 正常交换机,队列绑定 * @param queue * @param exchange * @return */ @Bean public Binding ttlBinding(@Qualifier("ttlQueue") Queue queue, @Qualifier("ttlExchange") Exchange exchange) { return BindingBuilder.bind(queue).to(exchange).with(env.getProperty("mq.order.routing.ttl")).noargs(); } /** * 死信交换机 * @return */ @Bean public Exchange dlxExchange(){ return ExchangeBuilder.directExchange(env.getProperty("mq.order.exchange.dlx")).durable(true).build(); } /** * 死信队列 * @return */ @Bean public Queue dlxQueue() { return QueueBuilder.durable(env.getProperty("mq.order.queue.dlx")).build(); } /** * 死信交换机,队列绑定 * @param queue * @param exchange * @return */ @Bean public Binding dlxBinding(@Qualifier("dlxQueue") Queue queue, @Qualifier("dlxExchange") Exchange exchange) { return BindingBuilder.bind(queue).to(exchange).with(env.getProperty("mq.order.routing.dlx")).noargs(); } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。