问题
My question is very similar to this one: RabbitTemplate receive and requeue Unfortunately it has been marked as answered though the answer doesn't suit my needs.
I want to mimic the functionality of the Rabbit Admin UI, i.e. I want to synchronously read messages from a queue, but don't want the queue to lose them, i.e. something like having a peek.
The answer here RabbitTemplate receive and requeue suggests using a listener, but in that case it'll read and requeue indefinitely. I want to get and requeue the messages just once, so I guess I should be using RabbitTemplate, not a listener.
回答1:
class Peeker implements ChannelCallback<Message> {
final MessagePropertiesConverter propertiesConverter = new DefaultMessagePropertiesConverter();
@Override
public Message doInRabbit(Channel channel) throws Exception {
GetResponse result = channel.basicGet("someQ", false);
if (result == null) {
return null;
}
channel.basicReject(result.getEnvelope().getDeliveryTag(), true);
return new Message(result.getBody(), propertiesConverter.toMessageProperties(
result.getProps(), result.getEnvelope(), "UTF-8"));
}
}
Peeker peeker = new Peeker();
...
Message peek = this.rabbitTemplate.execute(peeker);
来源:https://stackoverflow.com/questions/33890701/rabbittemplate-receive-messages-and-requeue