消费端限流
在实际场景中,如果 MQ 服务器上有数以万计未处理的消息,当我们打开一个消费者客户端时,海量消息瞬间全部推送过来,而单个客户端无法同时处理这么多数据,很可能导致服务性能下降、卡顿,甚至资源耗尽。
我们无法限制生产端生产消息,只能在消费端进行限流,以应对巨量消息待处理的情况。
RabbitMQ 提供了一种 qos(服务质量保证)功能,即在非自动确认消息的前提下,如果一定数目的消息在未被确认前,就不会消费(处理)新的消息。
MyProducer.java
public class MyProducer {
public static void main(String[] args) throws Exception {
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setHost("192.168.0.125");
connectionFactory.setPort(5672);
connectionFactory.setVirtualHost("/");
Connection connection = connectionFactory.newConnection();
Channel channel = connection.createChannel();
channel.confirmSelect();
String exchangeName = "exchange_qos";
String routingKey = "test.qos";
String msg = "hello, rabbitmq, test qos ";
// 发送10条消息
for(int i = 0; i < 10; i++) {
channel.basicPublish(exchangeName, routingKey, null, msg.getBytes());
}
System.out.println("生产端消息已发送==" + msg);
}
}
MyConsumer.java
public class MyConsumer {
public static void main(String[] args) throws Exception {
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setHost("192.168.0.125");
connectionFactory.setPort(5672);
connectionFactory.setVirtualHost("/");
Connection connection = connectionFactory.newConnection();
Channel channel = connection.createChannel