优级队列
在队列中默认都是先进先出,但每个消息都会伴随一个默认的优先级,如果需要提高某个消息的被处理的优先级,那么就可以通过优级队列来实现。
代码实现
添加配置文件
spring.rabbitmq.host=192.168.136.128
spring.rabbitmq.port=5672
spring.rabbitmq.username=admin
spring.rabbitmq.password=admin
引入rabbitmq的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
添加配类
@Configuration
public class MqConfig {
//队列名称
public static final String QUEUE_NAME = "queue1";
//延迟交换机名称
public static final String EXCHANGE_NAME = "exchange1";
//routingkey
public static final String ROUTING_KEY = "routingkey1";
//声明优先级队列
@Bean("queue1")
public Queue queue1() {
Map<String, Object> params = new HashMap();
//声明并设置队列的最大优先级
params.put("x-max-priority", 10);
return new Queue(QUEUE_NAME,true,true,false,params);
}
//声明交换机
@Bean("exchange1")
public DirectExchange exchange1(){
return new DirectExchange(EXCHANGE_NAME);
}
//将队列与交换机绑定
@Bean
public Binding bindingDelayedQueue(@Qualifier("queue1") Queue queue,
@Qualifier("exchange1") DirectExchange directExchange ) {
return BindingBuilder.bind(queue).to(directExchange).with(ROUTING_KEY).noargs();
}
}
在声明队列时,添加x-max-priority并设置优先级的取值范围0-255,官网推荐 1-10 如果设置太高比较吃内存和cpu
添加生产者
@RestController
@RequestMapping("/sendMessage")
@Slf4j
public class Producer {
public static final String EXCHANGE_NAME = MqConfig.EXCHANGE_NAME;
@Autowired
private RabbitTemplate rabbitTemplate;
private String routingKey = MqConfig.ROUTING_KEY;
@GetMapping
public void sendMessage(){
for (int i = 1; i <11; i++){
String content = "info"+i;
if(i == 5){
//设置消息的优先级,注意优先级不能超过
rabbitTemplate.convertAndSend(EXCHANGE_NAME,routingKey,content,
message -> {
message.getMessageProperties().setPriority(5);
return message;
});
}else{
rabbitTemplate.convertAndSend(EXCHANGE_NAME, routingKey, content);
}
}
}
}
添加消费者
@Slf4j
@Component
public class Consumer{
//指定消费的队列
@RabbitListener(queues = MqConfig.QUEUE_NAME)
public void receiveDelayedQueue(Message message)
{
String msg = new String(message.getBody());
log.info("收到消息:{}", msg);
}
}
需要注意的是,通过优先级队列提高消息的优先级,是需要比较信道中每个消息的优先级,在消费端速度大于生产端速度,且broker中没有消息堆积的话,对发送的消息设置优先级也没什么实际意义,因为发送端刚发送完一条消息就被消费端消费了,那么就相当于broker至多只有一条消息,那么对于单条消息来说优先级是没有什么意义的。