💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
优先级的范围为`[0, 255]`,通常选择`[0, 10]`,数字越大优先级越高。因为需要排序,所以数字越大消耗的 cpu 也越多。设置优先级可以有下面两种方法。 [TOC] # 1. 通过UI页面添加一个具有优先级的队列 ![](https://img.kancloud.cn/8c/14/8c14742a88fa08a4f4074cadd8448b66_1566x637.jpg) <br/> # 2. 通过代码创建一个优先级队列 需要在消费端设置队列的优先级,也需要在生产者对消息设置优先级,消息的优先级必须小于等于队列的优先级。 **1. 封装连接 MQ 服务器的工具类** ```java public class RabbitMQUtils { /** * 连接RabbitMQ服务器 */ public static Channel getChannel() throws Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("me.rabbitmq.com"); factory.setUsername("admin"); factory.setPassword("admin"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); return channel; } } ``` **2. 生产者** ```java public class MessageProducer { private static final String QUEUE_NAME = "queue.hello.priority"; public static void main(String[] args) throws Exception { try (Channel channel = RabbitMQUtils.getChannel()) { //给消息添加priority属性,该属性就是优先级 AMQP.BasicProperties properties = new AMQP.BasicProperties().builder().priority(5).build(); for (int i = 1; i < 11; i++) { String message = "info" + i; if (i == 5) { channel.basicPublish("", QUEUE_NAME, properties, message.getBytes()); } else { channel.basicPublish("", QUEUE_NAME, null, message.getBytes()); } System.out.println(MessageProducer.class.getSimpleName() + "[生产了消息]: " + message); } } } } ``` **3. 消费者** ```java public class MessageConsumer { private static final String QUEUE_NAME = "queue.hello.priority"; public static void main(String[] args) throws Exception { Channel channel = RabbitMQUtils.getChannel(); Map<String, Object> params = new HashMap(16); //设置队列的优先级 params.put("x-max-priority", 10); channel.queueDeclare(QUEUE_NAME, true, false, false, params); System.out.println(MessageConsumer.class.getSimpleName() + "[等待消费..]"); DeliverCallback deliverCallback = (consumerTag, delivery) -> { String message = new String(delivery.getBody()); System.out.println(MessageConsumer.class.getSimpleName() + "[收到消息]: " + message); }; channel.basicConsume(QUEUE_NAME, true, deliverCallback, (consumerTag) -> { }); } } ``` **3. 测试** (1)先启动生产者,生产如下消息。 ``` MessageProducer[生产了消息]: info1 MessageProducer[生产了消息]: info2 MessageProducer[生产了消息]: info3 MessageProducer[生产了消息]: info4 MessageProducer[生产了消息]: info5 MessageProducer[生产了消息]: info6 MessageProducer[生产了消息]: info7 MessageProducer[生产了消息]: info8 MessageProducer[生产了消息]: info9 MessageProducer[生产了消息]: info10 ``` (2)启动消费者,消费了如下消息。消息`info5`优先级最高,所以最先被消费。 ``` MessageConsumer[收到消息]: info5 MessageConsumer[收到消息]: info1 MessageConsumer[收到消息]: info2 MessageConsumer[收到消息]: info3 MessageConsumer[收到消息]: info4 MessageConsumer[收到消息]: info6 MessageConsumer[收到消息]: info7 MessageConsumer[收到消息]: info8 MessageConsumer[收到消息]: info9 MessageConsumer[收到消息]: info10 ``` **** 案例代码:https://gitee.com/flymini/codes01/tree/master/rabbitmq_/com-learn-rabbitmq04