案例:模拟WorkQueue,实现一个队列绑定多个消费者
基本思路如下:
1.
在
publisher
服务中定义测试方法,每秒产生
50
条消息,发送到
simple.queue
2.
在
consumer
服务中定义两个消息监听者,都监听
simple.queue
队列
3.
消费者
1
每秒处理
50
条消息,消费者
2
每秒处理
10
条消息
代码实现:
消息发送代码
@Test
public void testSimpleQueue2() throws InterruptedException {
// 队列名称
String queueName = "simple.queue";
//发送信息
String message = "hello,message__";
for (int i = 0; i <50; i++) {
rabbitTemplate.convertAndSend(queueName,message+i);
Thread.sleep(20);
}
}
消息接收代码:
@RabbitListener(queues = "simple.queue")
public void listenWorkQueueMessage(String massage) throws InterruptedException{
System.out.println("spring 1消费者接收到消息:【" + massage + "】"+ LocalTime.now());
Thread.sleep(20);
}
@RabbitListener(queues = "simple.queue")
public void listenWorkQueueMessage2(String massage) throws InterruptedException{
System.err.println("spring 2--消费者接收到消息:【" + massage + "】"+LocalTime.now());
Thread.sleep(200);
}
问题:
启动ConsumerApplication后,在执行publisher服务中刚刚编写的发送测试方法testWorkQueue,可以看到消费者1很快完成了自己的25条消息。消费者2却在缓慢的处理自己的25条消息。也就是说消息是平均分配给每个消费者,并没有考虑到消费者的处理能力。这样显然是有问题的。
解决方法:
在spring中有一个简单的配置,可以解决这个问题。我们修改consumer服务的application.yml文件,添加配置:
spring:
rabbitmq:
listener:
simple:
prefetch: 1 # 每次只能获取一条消息,处理完成才能获取下一个消息
Work模型的使用:
•
多个消费者绑定到一个队列,同一条消息只会被一个消费者处理
•
通过设置
prefetch
来控制消费者预取的消息数量