工作队列又叫任务队列,避免立即执行资源密集型任务,而不得不等待它完成。把任务封装成消息并将其发送到队列,当有多个工作线程时,这些工作线程将一起处理这些任务。
多个工作线程也就是多个消费者,采用轮训分发。
工具类
package com.xkj.org.utils;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
public class RabbitMQUtil {
public static Channel getChannel() {
try {
//创建连接工厂
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setHost("192.168.171.128");
connectionFactory.setUsername("admin");
connectionFactory.setPassword("123");
//创建连接
Connection connection = connectionFactory.newConnection();
//创建信道
Channel channel = connection.createChannel();
return channel;
}catch (Exception e){
e.printStackTrace();
}
return null;
}
}
消费者工作线程(启动多个)
package com.xkj.org.mq.work;
import com.rabbitmq.client.CancelCallback;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.DeliverCallback;
import com.xkj.org.utils.RabbitMQUtil;
import java.io.IOException;
public class Work01 {
private static final String QUEUE_NAME = "hello";
public static void main(String[] args) throws IOException {
Channel channel = RabbitMQUtil.getChannel();
DeliverCallback deliverCallback = (consumerTag, message) -> {
System.out.println("work1 接受到消息:"+ new String(message.getBody()));
};
CancelCallback cancelCallback = consumerTag -> {
System.out.println("work1 消息消费被中断");
};
System.out.println("work1等待接收......");
channel.basicConsume(QUEUE_NAME, true, deliverCallback, cancelCallback);
}
}
生产者
package com.xkj.org.mq.work;
import com.rabbitmq.client.Channel;
import com.xkj.org.utils.RabbitMQUtil;
import java.io.IOException;
import java.util.Scanner;
public class Task01 {
private static final String QUEUE_NAME = "hello";
public static void main(String[] args) throws IOException {
Channel channel = RabbitMQUtil.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);
}
}
}