RabbitMq:如何通过DefaultConsumer接收消息?

时间:2014-07-21 14:37:50

标签: java rabbitmq

我使用DefaultConsumer而不是QueueingConsumer因为在这个消费者中我将连接到数据库并运行程序,之后我将发回ACK。

我的问题非常愚蠢,我觉得很简单...如何通过扩展DefaultConsumer的类接收消息?

使用QueueingConsumer时,您会通过QueueingConsumer.Delivery delivery = consumer.nextDelivery();

收到消息。

1 个答案:

答案 0 :(得分:2)

这是主要的:

 Connection connection = factory.newConnection();
 Channel channel = connection.createChannel();
 channel.queueDeclare("myQueue", false, false, false, null);
 MyConsumer consumer = new MyConsumer(channel);
 String consumerTag = channel.basicConsume("myQueue", false, consumer);
 System.out.println("press any key to terminate");
 System.in.read();
 channel.basicCancel(consumerTag);
 channel.close();
 connection.close();

实际的消费者类是:

public class MyConsumer extends DefaultConsumer {


    public void handleDelivery(String consumerTag, Envelope envelope,
            BasicProperties properties, byte[] body) throws java.io.IOException {

        /// byte[] body = body Message
        /// here you have your message

        getChannel().basicAck(envelope.getDeliveryTag(), false);
    }


}