接着上一篇:https://blog.csdn.net/qq_36357242/article/details/107664806,这篇开始学习工作模式。
工作模式
工作模式是指向多个互相竞争的消费者发送消息的模式,它包含一个生产者、两个消费者和一个队列。两个消费者同时绑定到一个队列上去,当消费者获取消息处理耗时任务时,空闲的消费者从队列中获取并消费消息。
公平发放
声明一个新的队列,防止混淆。公平发放,能让效率高的消费的接受更多消息,举个例子,如果消费者一启动一个线程sleep(10000),那么这时候肯定就是消费者二效率高!
//申明一个工作模式队列
@Bean
public Queue workQueue() {
return new Queue("work");
}
创建一个生产者(发送者)
//创建消息发送者
public void sendToWork() {
String context = "工作模式发送的消息";
System.out.println("工作模式发送者: " + context);
this.rabbitTemplate.convertAndSend("work", context);
}
创建俩个消费者(接受者)
//创建消息接收者
@RabbitListener(queues = "work")
@RabbitHandler
public void process2(String work) throws InterruptedException {
//Thread.sleep(20000);
System.err.println("工作模式 消费者1: " + work);
}
@RabbitListener(queues = "work")
@RabbitHandler
public void process3(String work) {
System.out.println("工作模式 消费者2: " + work);
}
测试一下
@Test
public void contextLoads2() {
for (int i = 0;i<10; i++){
senderConfig.sendToWork();
}
}
运行结果
上边说到了公平发放,能者多劳,现在说一下轮训发放,效率没有公平发放高。
轮训发放
发送方式改为有序即可:
this.rabbitTemplate.convertSendAndReceive("work", context);