> 1.队列设置最大优先级,限定优先级范围0-max,通过参数`x-max-priority`
> 2.发送消息指定优先级
> 3.在消息有积压时,会优先处理优先级高的消息
1. 配置优先队列
```
@Slf4j
@Component
public class PriorityConfig {
public static final String EXCHANGE = "priority-exchange";
public static final String QUEUE = "priority-queue";
public static final String ROUTING_KEY = "priority_key";
/**
* 定义优先级队列
*/
@Bean
Queue queue() {
Map<String, Object> args= new HashMap<>();
args.put("x-max-priority", 10); //设置优先级,范围0-255,此处设为10,则允许优先级的范围为0-10
return new Queue(QUEUE, false, false, false, args);
}
/**
* 定义交换器
*/
@Bean
DirectExchange exchange() {
return new DirectExchange(EXCHANGE);
}
@Bean
Binding binding(Queue queue, DirectExchange exchange) {
return BindingBuilder.bind(queue).to(exchange).with(ROUTING_KEY);
}
}
```
2. 生产者
```
/**
* 模拟发送多条数据
*/
@GetMapping("/sendPriorityMessage")
public void sendPriorityMessage(){
String message = "";
for (int i = 0; i < 10;i++){
message = "info" + i;
if (i == 5){ // i= 5 设置优先级为10 ,优先级也可以作为形参接受
rabbitTemplate.convertAndSend(PriorityConfig.EXCHANGE,PriorityConfig.ROUTING_KEY,message,msg -> {
msg.getMessageProperties().setPriority(10);
return msg;
});
}else {
rabbitTemplate.convertAndSend(PriorityConfig.EXCHANGE,PriorityConfig.ROUTING_KEY,message,msg -> {
msg.getMessageProperties().setPriority(5);
return msg;
});
}
}
log.info("发出消息success");
}
```
场者