1、限流的概念
上图中
- 第一个参数是消费端,消息限制的大小
- 第二个参数是指在消费端一次能处理多少条消息
- 第三个参数是说限流这个功能是在channel上作用呢还是在消费端作用,一般设置为false,在消费端限制。
一定要注意的是,如果做限流,那么no_ask是要设置为false,也就是手工签收而不是自动签收的情况下才可以做限流。
2、实战
producer:
public static void main(String[] args) throws IOException, TimeoutException {
//1 创建ConnectionFactory
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setHost("127.0.0.1");
connectionFactory.setPort(5672);
connectionFactory.setVirtualHost("/");
//2 获取Connection
Connection connection = connectionFactory.newConnection();
//3 通过Connection创建一个新的Channel
Channel channel = connection.createChannel();
//4 指定我们的消息投递模式: 消息的确认模式
channel.confirmSelect();
String exchangeName = "qos_exchange";
String routingKey = "qos.save";
//5 发送一条消息
String msg = "Hello RabbitMQ Send custom message!";
for(int i=0;i<5;i++){
channel.basicPublish(exchangeName, routingKey, null, msg.getBytes());
}
}
consumer:
public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
//1 创建ConnectionFactory
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setHost("127.0.0.1");
connectionFactory.setPort(5672);
connectionFactory.setVirtualHost("/");
//2 获取Connection
Connection connection = connectionFactory.newConnection();
//3 通过Connection创建一个新的Channel
Channel channel = connection.createChannel();
String exchangeName = "qos_exchange";
String routingKey = "qos.#";
String queueName = "qos_queue";
//4 声明交换机和队列 然后进行绑定设置, 最后制定路由Key
channel.exchangeDeclare(exchangeName, "topic", true);
channel.queueDeclare(queueName, true, false, false, null);
channel.queueBind(queueName, exchangeName, routingKey);
//5 创建消费者
channel.basicQos(0,1,false);
//限流方式 一定要设置autoAck为false
channel.basicConsume(queueName, false, new MyConsumer(channel));
}
myConsumer:
public class MyConsumer extends DefaultConsumer {
private Channel channel;
/**
* Constructs a new instance and records its association to the passed-in channel.
*
* @param channel the channel to which this consumer is attached
*/
public MyConsumer(Channel channel) {
super(channel);
this.channel = channel;
}
@Override
public void handleDelivery(String consumerTag, Envelope envelope,
AMQP.BasicProperties properties, byte[] body) throws IOException {
super.handleDelivery(consumerTag, envelope, properties, body);
System.out.println("-----consume message------");
System.out.println("consumerTag:"+consumerTag);
System.out.println("envelope:"+envelope);
System.out.println("properties:"+properties);
System.out.println("body:"+new String(body));
channel.basicAck(envelope.getDeliveryTag(),false);
}
}
接下来我们就可以测试一下,可以先把下面这段代码给注释掉:
channel.basicAck(envelope.getDeliveryTag(),false);
如果注释掉之后,先启动consumer,然后再启动producer,之后可以发现控制台就打印了一个消息,总共五个消息 ,而五个消息都没有消费,其中有一个是没有ack也就是没有确认,因为是手动确认模式,而我们并没有做任何手动确认的逻辑,所以broker端就认为你没有消费消息,那么自然就不会给你发送下一条消息了:
我们可以打开rabbitmq的管理界面查看消息的数量情况:
image.png
而控制台也仅仅打印了一个消息:
image.png
然后服务都关闭掉,再把consumer中那段代码注释放开,然后再启动,就会发现消息都消费掉了,然后控制台也是打印了五个消息的信息。
网友评论