RabbitMQ consumer which consumes only one message, acknowledges it and stops listening

时间:2016-07-11 19:13:19

标签: java rabbitmq message-queue

I am looking at the RabbitMQ HelloWorld example in Java https://www.rabbitmq.com/tutorials/tutorial-one-java.html

Producer:

        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(host);
        factory.setPort(Integer.parseInt(port));
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.queueDeclare(queueName, false, false, false, null);

        channel.basicPublish("", queueName, null, message.getBytes());
        System.out.println(" [x] Sent '" + message + "'");

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

Consumer:

        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(host);
        factory.setPort(Integer.parseInt(port));
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.queueDeclare(queueName, false, false, false, null);
        System.out.println(" [*] Waiting for messages.");

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

        QueueingConsumer.Delivery delivery = consumer.nextDelivery(1000);
        if (delivery != null) {
            String message = new String(delivery.getBody());
            System.out.println(" [x] Received '" + message + "'");
        } else {
            System.out.println(" [x] No messages received");
        }

Is there a way to write my consumer such that it receives only message and stops listening?

1 个答案:

答案 0 :(得分:2)

Modified the consumer code to the following. That worked for me.

        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost(host);
        factory.setPort(Integer.parseInt(port));
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.queueDeclare(queueName, false, false, false, null);
        System.out.println(" [*] Waiting for messages.");

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

        QueueingConsumer.Delivery delivery = consumer.nextDelivery(1000);
        while (delivery != null) {
            String message = new String(delivery.getBody());
            System.out.println(" [x] Received '" + message + "'");
            delivery = consumer.nextDelivery(1000);
        }
        channel.close();
        connection.close();