How to consume one message?

ε祈祈猫儿з 提交于 2019-12-30 10:34:32

问题


With example in rabbitmq, consumer get all messages from queue at one time. How to consume one message and exit?

QueueingConsumer consumer = new QueueingConsumer(channel);
channel.basicConsume(QUEUE_NAME, true, consumer);

while (true) {
  QueueingConsumer.Delivery delivery = consumer.nextDelivery();
  String message = new String(delivery.getBody());
  System.out.println(" [x] Received '" + message + "'");
}

回答1:


You have to declare basicQos setting to get one message at a time from ACK to NACK status and disable auto ACK to give acknowledgement explicitly.

ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();
    channel.basicQos(1);
    channel.queueDeclare(QUEUE_NAME, true, false, false, null);
    System.out.println("[*] waiting for messages. To exit press CTRL+C");

    QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(QUEUE_NAME, consumer);
    while(true) {
        QueueingConsumer.Delivery delivery = consumer.nextDelivery();
        int n = channel.queueDeclarePassive(QUEUE_NAME).getMessageCount();
        System.out.println(n);
        if(delivery != null) {
            byte[] bs = delivery.getBody();
            System.out.println(new String(bs));
            //String message= new String(delivery.getBody());
            channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
            //System.out.println("[x] Received '"+message);
        }
    }

Hope it helps!




回答2:


Use AMQP 0.9.1 basic.get to synchronously get just one message.

ConnectionFactory factory = new ConnectionFactory();
factory.setUri(uri);

Connection connection = factory.newConnection();
Channel channel = connection.createChannel();

channel.queueDeclare(QUEUE_NAME, true, false, false, null);

GetResponse response = channel.basicGet(QUEUE_NAME, true);
if (response != null) {
    String message = new String(response.getBody(), "UTF-8");
}

channel.close();
connection.close();


来源:https://stackoverflow.com/questions/29841690/how-to-consume-one-message

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!