RabbitMQ(12)RabbitMQ高级特性:消费端限流

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


    <rabbit:listener-container connection-factory="connectionFactory" acknowledge="manual" prefetch="1" >
       <rabbit:listener ref="QosListener" queue-names="test_queue_confirm">rabbit:listener>
    rabbit:listener-container>
package com.yy.listener;

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

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

@Component
public class QosListener implements ChannelAwareMessageListener {

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

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

        //2. 处理业务逻辑

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

    }
}

总结

在< rabbit:listener-container>中配置prefetch属性设置消费端一次拉去多少消息

消费端的确认模式一定为手动确认。acknowledge= “manual”

你可能感兴趣的:(#,RabbitMQ,rabbitmq,分布式,java)