💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
![](https://img.kancloud.cn/56/40/5640f2ad18960fe09aa24de445f46675_1295x499.jpg) 轮询分发消息演示:启动两个工作线程,一个消息发送线程,我们来看看两个工作线程是如何工作的。 <br/> 步骤如下: **1. 工具类** ```java public class RabbitMQUtils { /** * 连接RabbitMQ服务器 */ public static Channel getChannel() throws Exception { ConnectionFactory factory = new ConnectionFactory(); factory.setHost("192.168.0.107"); factory.setUsername("admin"); factory.setPassword("admin"); Connection connection = factory.newConnection(); Channel channel = connection.createChannel(); return channel; } } ``` **2. 启动两个工作线程** ```java public class Worker01 { private static final String QUEUE_NAME = "hello"; public static void main(String[] args) throws Exception { Channel channel = RabbitMQUtils.getChannel(); DeliverCallback deliverCallback = (consumerTag, delivery) -> { String receivedMessage = new String(delivery.getBody()); System.out.println("接收到消息:" + receivedMessage); }; CancelCallback cancelCallback = (consumerTag) -> { System.out.println(consumerTag + "消费者取消消费接口回调逻辑"); }; System.out.println("C1 消费者启动等待消费......"); channel.basicConsume(QUEUE_NAME, true, deliverCallback, cancelCallback); } } ``` 按照下面步骤使用同一个Worker01来模拟启动两个工作线程。 ![](https://img.kancloud.cn/47/19/4719b80f29d69426e354acb30d3e7d02_1416x294.jpg) ![](https://img.kancloud.cn/ed/56/ed56bce06468421a61d7697dd1cd63a0_1337x267.jpg) ![](https://img.kancloud.cn/b5/18/b51826b5e3f40fb54b8d02354da18be1_1426x381.jpg) **3. 启动一个消息发送线程** ```java public class Task01 { private static final String QUEUE_NAME = "hello"; public static void main(String[] args) throws Exception { try (Channel channel = RabbitMQUtils.getChannel();) { channel.queueDeclare(QUEUE_NAME, false, false, false, null); //从控制台当中接受信息 Scanner scanner = new Scanner(System.in); while (scanner.hasNext()) { String message = scanner.next(); channel.basicPublish("", QUEUE_NAME, null, message.getBytes()); System.out.println("发送消息完成:" + message); } } } } ``` **4. 测试** (1)生产者生产4条消息。 ![](https://img.kancloud.cn/df/88/df88d605be1bd2a522999c55ed55571e_1498x371.jpg) (2)两个消费者消费到的消息。 ![](https://img.kancloud.cn/64/e4/64e46a1d01d2d1f18dd5e606723a46e8_1438x283.jpg) ![](https://img.kancloud.cn/c6/87/c687401f1e52a30a8956ae396f759601_1417x277.jpg) 通过程序执行发现生产者总共发送 4 个消息,消费者 1 和消费者 2 分别分得两个消息,并且是按照有序的一个接收一次消息。