关于rabbitmq:RabbitMQ-消费者获取队列消息的两种模式

5次阅读

共计 1094 个字符,预计需要花费 3 分钟才能阅读完成。

订阅模式 -Push API

消息中间件被动将音讯推送给订阅的消费者,实时性好。

利用能够通过订阅特定的队列,获取到 RabbitMQ 被动推送(主动投递) 的队列音讯。通过在队列中注册一个消费者实现。订阅胜利后,RabbitMQ 将开始投递音讯。每一次音讯投递都会调用用户提供的处理程序。处理程序须要遵循特定的接口。

订阅胜利会返回订阅标识符,能够用来勾销订阅。

boolean autoAck = false;
channel.basicConsume(queueName, autoAck, "myConsumerTag",
     new DefaultConsumer(channel) {
         @Override
         public void handleDelivery(String consumerTag,
                                    Envelope envelope,
                                    AMQP.BasicProperties properties,
                                    byte[] body)
             throws IOException
         {String routingKey = envelope.getRoutingKey();
             String contentType = properties.getContentType();
             long deliveryTag = envelope.getDeliveryTag();
             // (process the message components here ...)
             channel.basicAck(deliveryTag, false);
         }
     });

检索模式 -Pull API

消费者被动从消息中间件中拉取音讯,实时性差。

利用能够通过 basic.get 办法, 一条一条地从 RabbitMQ 中拉取音讯 ,音讯以先进先出的程序被拉取,能够主动或手动确认。

不倡议应用检索模式,与订阅模式相比效率极低。尤其在音讯公布数量少、队列长时间为空的利用中会造成大量资源节约。

boolean autoAck = false;
GetResponse response = channel.basicGet(queueName, autoAck);
if (response == null) {// No message retrieved.} else {AMQP.BasicProperties props = response.getProps();
    byte[] body = response.getBody();
    long deliveryTag = response.getEnvelope().getDeliveryTag();
    // (process the message components here ...)
    channel.basicAck(deliveryTag, false);
}
正文完
 0