如何轮询RabbitMQ以按优先级顺序获取消息?

时间:2014-09-11 19:38:21

标签: rabbitmq priority-queue

我们可以通过从https://www.rabbitmq.com/community-plugins.html安装插件 rabbitmq-priority-queue ,使RabbitMQ成为分布式优先级队列。我将元素推入队列(每个元素都以优先级推送),我能够根据需要在消费者中接收队列的内容 - 首先出现更高优先级的元素。

问题是,当这种情况持续发生时,优先级轮询概念不起作用:

  1. 运行发布者以在队列中填充具有不同优先级的3个项目。
  2. 消耗队列中的消息 - 运行良好 - 按照消耗 优先。现在,消费者等待队列中的任何消息 现在队列是空的。
  3. 我再次运行发布商以填充大约5个元素。
  4. 消费者不会优先使用队列中的5个项目,而是消耗在发布者发布的第3步中。
  5. 我需要的是队列项的每次轮询都应该首先在队列的整个内容中具有最高优先级。

    谁能告诉我这里发生的错误是什么?谢谢。

    以下是发布者和消费者(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
    

1 个答案:

答案 0 :(得分:0)

我能够使用basicGet来解决这个问题,而不是使用consumer.nextDelivery()来轮询队列。 final String message = new String(channel.basicGet(QUEUE_NAME, true).getBody());这会从队列中提取具有最高优先级的项目。