priority queue

生产者

    public void prioritySms() throws InterruptedException {
        byte[] body = "hello world".getBytes();

        for (int i = 0; i < 10; i++) {
            int priority = new Random().nextInt(5);
            MessageProperties properties = new MessageProperties();
            properties.setContentType("text");
            properties.setPriority(priority);
            rabbitTemplate.send("priority-exchange", "priority.test", new Message(body, properties));
            log.info("第{}条=====优先级:{}=======", i, priority);
        }
        TimeUnit.SECONDS.sleep(30);
    }

消费端

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "priority-queue", durable = "true",
                    arguments = {@Argument(name = "x-max-priority", value = "5", type = "java.lang.Long")}),
            exchange = @Exchange(name = "priority-exchange", type = "topic"),
            key = "priority.#"
    ))
    @RabbitHandler
    public void priorityMessage(Message message, @Headers Map<String, Object> headers, Channel channel) throws IOException {
        log.info("消息的优先级{},消息体内容:{}", message.getMessageProperties().getPriority(), new String(message.getBody()));
        Long deliveryTag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);
        channel.basicAck(deliveryTag, false);
    }
  • 创建优先级队列,需要增加x-max-priority参数,指定一个数字。表示最大的优先级,建议优先级设置为1~10之间。
  • 发送消息的时候,需要设置priority属性,最好不要超过上面指定的最大的优先级。
  • 如果生产端发送很慢,消费者消息很快,则有可能不会严格的按照优先级来进行消费。

  第一,如果发送的消息的优先级属性小于设置的队列属性x-max-priority值,则按优先级的高低进行消费,数字越高则优先级越高。
  第二,如果发送的消息的优先级属性都大于设置的队列属性x-max-priority值,则设置的优先级失效,按照入队列的顺序进行消费。
  第三,如果消费端一直进行监听,而发送端一条条的发送消息,优先级属性也会失效。

  RabbitMQ不能保证消息的严格的顺序消费。

posted on 2020-01-18 19:06  溪水静幽  阅读(151)  评论(0)    收藏  举报