我们可以通过从https://www.rabbitmq.com/community-plugins.html安装插件 rabbitmq-priority-queue ,使RabbitMQ成为分布式优先级队列。我将元素推入队列(每个元素都以优先级推送),我能够根据需要在消费者中接收队列的内容 - 首先出现更高优先级的元素。
问题是,当这种情况持续发生时,优先级轮询概念不起作用:
我需要的是队列项的每次轮询都应该首先在队列的整个内容中具有最高优先级。
谁能告诉我这里发生的错误是什么?谢谢。
以下是发布者和消费者(Java)的片段:
发布商
public class RabbitMQPublisher {
private static final String QUEUE = "my-priority-queue-3";
public static void main(String[] argv) throws Exception {
final ConnectionFactory factory = new ConnectionFactory();
final Connection conn = factory.newConnection();
final Channel ch = conn.createChannel();
final Map<String, Object> args = new HashMap<String, Object>();
args.put("x-max-priority", 100);
ch.queueDeclare(QUEUE, true, false, false, args);
publish(ch, 24);
publish(ch, 11);
publish(ch, 75);
//second run
//publish(ch, 27);
//publish(ch, 77);
//publish(ch, 12);
conn.close();
}
private static void publish(Channel ch, int priority) throws IOException {
final BasicProperties props = MessageProperties.PERSISTENT_BASIC.builder().priority(priority).build();
final String body = "message with priority " + priority;
ch.basicPublish("", QUEUE, props, body.getBytes());
}
消费
while (true) {
final QueueingConsumer.Delivery delivery = consumer.nextDelivery();
final String message = new String(delivery.getBody());
System.out.println(message);
}
输出
message with priority 75
message with priority 24
message with priority 11
message with priority 27
message with priority 77
message with priority 12
答案 0 :(得分:0)
我能够使用basicGet来解决这个问题,而不是使用consumer.nextDelivery()来轮询队列。 final String message = new String(channel.basicGet(QUEUE_NAME, true).getBody());
这会从队列中提取具有最高优先级的项目。