rabbitMQ 消费者ack机制与拉取模式

1:拉取模式

    public static void main(String[] args) throws Exception {

        Connection connection = ConnectionUtil.getConnection();
        Channel channel = connection.createChannel();
        //拉取消息
        // queue,  autoAck:false  设置自动ack=false
        GetResponse response = channel.basicGet("dlx.queue", false);
        channel.basicAck(response .getEnvelope() .getDeliveryTag() ,false);
        String message = new String(response.getBody(), "UTF-8");
        System.out.println(message);

    }

2:ack机制

以下三种根据实际情况使用

long deliveryTag = envelope.getDeliveryTag();// 消息序列号
boolean multiple = false; // 是否多条消息
boolean requeue = false; // 拒绝消息后是否移除队列
channel.basicNack(deliveryTag, multiple, requeue); // 通过multiple属性可以拒绝多条消息
channel.basicAck(envelope.getDeliveryTag(), multiple); // 接收成功消息
channel.basicReject(envelope.getDeliveryTag(), requeue); // 每次只能拒绝一次消息

 

 推送模式

channel.basicConsume(queueName, autoAck, consumer);
 

    final Consumer consumer = new DefaultConsumer(channel) {
        @Override
        public void handleDelivery(String consumerTag, Envelope envelope,
                                   AMQP.BasicProperties properties, byte[] body) throws IOException {
            String message = new String(body, "UTF-8");
            System.out.println("消费者读取:" + message + "失败");
            // requeue为true 表示 拒绝消息后马上从队列中移除消息
            channel.basicNack(envelope.getDeliveryTag(),true,false);
        }
    };
    boolean autoAck = false;
    channel.basicConsume(queueName, autoAck, consumer);


拉取模式
channel.basicGet(queueName, false);

GetResponse response = channel.basicGet("dlx.queue", false);
channel.basicAck(response .getEnvelope() .getDeliveryTag() ,false);

 

你可能感兴趣的:(mq消息队列)