RabbitMQ消息优先级队列不起作用

时间:2015-07-11 08:43:21

标签: rabbitmq spring-rabbitmq

我在日食中运行优先级队列java program,我遇到了问题,第一次得到了正确答案。另一次我在队列中添加了一条消息,但这次我得到了不同的结果。

public static void main(String[] argv) throws Exception {
     ConnectionFactory factory = new ConnectionFactory();
        Connection conn = factory.newConnection();
        Channel ch = conn.createChannel();
        Map<String, Object> args = new HashMap<String, Object>();
        args.put("x-max-priority", 10);
        ch.queueDeclare(QUEUE_UPDATE, true, false, false, args);

         publish(ch, 141);   
         publish(ch, 250);   

        final CountDownLatch latch = new CountDownLatch(2);
        ch.basicConsume(QUEUE_UPDATE, true, new DefaultConsumer(ch) {
            public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties, byte[] body) throws IOException {
                System.out.println("Received " + new String(body));
                latch.countDown();
            }
        });

        latch.await();
        conn.close();           
        System.out.println("Finished");
}

private static void publish(Channel ch, int priority) throws Exception {
     BasicProperties props = MessageProperties.PERSISTENT_BASIC.builder().priority(priority).build();
     String body = QUEUE_UPDATE + " message with priority " + priority ;
     ch.basicPublish("", QUEUE_UPDATE, props, body.getBytes());         
}

正确输出:

Received update-queue message with priority 250
Received update-queue message with priority 141
Finished

再添加一个队列消息

         publish(ch, 141);    
         publish(ch, 250);   
         publish(ch, 110); // newly added

预期输出

Received update-queue message with priority 250
Received update-queue message with priority 141
Received update-queue message with priority 110
Finished

实际输出

Received update-queue message with priority 141
Received update-queue message with priority 250
Received update-queue message with priority 110
Finished

这是怎么回事?我做错了什么?

1 个答案:

答案 0 :(得分:2)

我遇到了同样的问题。对我有用的是定义consumer prefetch定义的限制,例如{...}, {...}, {...}。 如果您未设置此限制,则消息将在到达代理时传递给使用者,因此永远不会使用优先级对消息进行排序。

设置下限时,代理一次不会发送超过此限制的消息,从而在发送前对消息进行排序。

相关问题