0
点赞
收藏
分享

微信扫一扫

SpringBoot 整合 RabbitMQ之优先级队列

洲行 2022-02-27 阅读 99

优先级队列

什么是优先级队列?
假如,我们一共有100万的订单消息,需要进行催单消费,而这100万的订单信息又是不同的催付时间。需要RabbitMQ进行消费的时候就需要用到RabbitMQ的优先级队列,通过对不同的订单进行设置优先级,使得优先级高的消息先被优先处理。

RabbitMQ的优先级大小最小至最大的数值是0~255也就是说,数字越大,会优先被消费。不过一般设置的数值会在0~10之间【因为如果设置0-255,会考验服务器的硬件性能问题;如果你的服务器硬件性能好的话,可以随便设置,不太好,并且消息量又大的话,还是建议使用0-10的这个优先级范围】,这个有点像是线程的优先级设置。

RabbitMQ控制台添加优先级队列
在这里插入图片描述
SpringBoot整合RabbitMQ

创建交换机、队列并绑定


    @Bean("exchange_priority")
    public DirectExchange exchangePriority() {
        return new DirectExchange("exchange_priority");
    }

    @Bean("priority_queue")
    public Queue createPriorityQueue() {
        Map<String,Object> map = new HashMap<>();
        map.put("x-max-priority",10);//设置最大的优先级数量
        return new Queue("priority_queue",true,false,false,map);
    }

    @Bean
    public Binding bingPriority(@Qualifier("priority_queue")Queue queue,
                             @Qualifier("exchange_priority") DirectExchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with("priority");
    }

发送消息

    @RequestMapping("/sendPriorityMessage/{message}")
    public ResponseEntity<String> sendPriorityMessage(@PathVariable("message") String message) {
        for (int i = 1; i <= 10; i++) {
            CorrelationData data = new CorrelationData(i+"");
            if (i == 5) {
                rabbitTemplate.convertAndSend("exchange_priority", "priority", message+i, msg-> {
                    MessageProperties properties = msg.getMessageProperties();
                    properties.setPriority(5);
                    return msg;
                },data);
            } else {
                rabbitTemplate.convertAndSend("exchange_priority", "priority", message+i,  msg-> {
                    MessageProperties properties = msg.getMessageProperties();
                    properties.setPriority(1);
                    return msg;
                },data);
            }
        }
        return new ResponseEntity<>("ok",HttpStatus.OK);
    }

注意事项:
要让队列实现优先级需要做的事情有如下事情:队列需要设置为优先级队列,消息需要设置消息的优先级,消费者需要等待消息已经发送到队列中才去消费因为,这样才有机会对消息进行排序,同时不要一条一条发,发一条消费一条,消费者每次接收到的消息只有一条,还怎么玩,队列怎么给消息排序???

举报

相关推荐

优先级队列

堆(优先级队列)

优先级队列(堆)

优先级队列(堆)

Java 优先级队列

优先级队列的实现

0 条评论