Work Queue(任务模型)
Work quenes也被称为(Task queues),任务模型。当消息处理比较耗时的时候,可能生产消息的速度远远大于消息的消费速度。长此以往,消息就会堆积越来越多,无法及时处理。此时就可以使用work模型:让多个消费者绑定到同一个队列,共同消费队列中的消息。队列中的消息一旦消费,就会消失,因此任务是不会被重复执行的。
默认情况下消费者1和消费者2消费的消息是一致的,也就是平均分配消息
RabbitMQ连接工具类在RabbitMQ工作原理中已经介绍这里不在赘述了
Provider
public class Provider {
public static void main(String[] args) throws IOException {
//获取连接对象
Connection connection = RabbitMqUtils.getConnection();
//获取通道
Channel channel = connection.createChannel();
//通过通道声明队列
channel.queueDeclare("work", true, false, false, null);
for (int i = 1; i <= 20; i++) {
//生产消息
channel.basicPublish("", "work", MessageProperties.PERSISTENT_TEXT_PLAIN,
(i + "hello work queue").getBytes());
}
//关闭资源
RabbitMqUtils.closeConnectionAndChannel(channel, connection);
}
}
Consumer1
public class Consumer1 {
public static void main(String[] args) throws IOException {
//获取连接对象
Connection connection = RabbitMqUtils.getConnection();
//获取通道
Channel channel = connection.createChannel();
//通过通道声明队列
channel.queueDeclare("work", true, false, false, null);
channel.basicConsume("work", true, new DefaultConsumer(channel) {
//最后一个参数
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
byte[] body) {
System.out.println("消费者-1" + new String(body));
try{
Thread.sleep(1000);
}catch(Exception e){
e.printStackTrace();
}
}
});
//使用工具类关闭连接
RabbitMqUtils.closeConnectionAndChannel(channel, connection);
}
}
Consumer2
public class Consumer2 {
public static void main(String[] args) throws IOException {
//获取连接对象
Connection connection = RabbitMqUtils.getConnection();
//获取通道
Channel channel = connection.createChannel();
//通过通道声明队列
channel.queueDeclare("work", true, false, false, null);
channel.basicConsume("work", true, new DefaultConsumer(channel) {
//最后一个参数
@Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
byte[] body) {
System.out.println("消费者-2 " + new String(body));
}
});
//使用工具类关闭连接
RabbitMqUtils.closeConnectionAndChannel(channel, connection);
}
}