有适当的方法来保证 RabbitMQ 订阅中的消息顺序。
如果您使用多个消费者,他们将使用共享的ExecutorService 处理消息。另见ConnectionFactory.setSharedExecutor(...)。你可以设置一个Executors.newSingleThreadExecutor()。
如果您将一个Consumer 与单个队列一起使用,您可以使用多个bindingKeys 绑定此队列(它们可能有通配符)。消息将按照消息代理接收它们的顺序放入队列中。
例如,您有一个发布者发布重要顺序的消息:
try (Connection connection2 = factory.newConnection();
Channel channel2 = connection.createChannel()) {
// publish messages alternating to two different topics
for (int i = 0; i < messageCount; i++) {
final String routingKey = i % 2 == 0 ? routingEven : routingOdd;
channel2.basicPublish(exchange, routingKey, null, ("Hello" + i).getBytes(UTF_8));
}
}
您现在可能希望接收来自 队列 中两个 主题 的消息,它们的发布顺序与它们的发布顺序相同:
// declare a queue for the consumer
final String queueName = channel.queueDeclare().getQueue();
// we bind to queue with the two different routingKeys
final String routingEven = "even";
final String routingOdd = "odd";
channel.queueBind(queueName, exchange, routingEven);
channel.queueBind(queueName, exchange, routingOdd);
channel.basicConsume(queueName, true, new DefaultConsumer(channel) { ... });
Consumer 现在将按照消息发布的顺序接收消息,而不管您使用不同的主题。
RabbitMQ 文档中有一些不错的 5 分钟教程可能会有所帮助:
https://www.rabbitmq.com/tutorials/tutorial-five-java.html