rabbitmq 消费端代码获取队列名称_RabbitMQ 消费者获取队列消息的两种模式

订阅模式-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);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值