RabbitMQ(二)——Work Queues

一个发送者,多个接收者,这是应工作队列,使用场景
web应用程序中处理复杂的任务且不能在一个短的HTTP请求内完成
RabbitMQ(二)——Work Queues_第1张图片
创建多个接收者
我们在一的代码基础上新建第二个接收者


@Component
@RabbitListener(queues = "hello")
public class Receiver2 {
    @RabbitHandler
    public void process(String hello) {
        System.out.println("Receiver2  : " + hello);
    }
}

测试,这里发送50个消息

 /**
     * 测试消息
     */
    @RequestMapping(value = "/sender", method = RequestMethod.GET)
    @ResponseBody
    public ResponseResult sender() {
        for (int i=0;i<50;i++){
            sender.send();
        }

        return ResponseResult.success("ok");
    }

同样,两者都能交替接收。

...
Receiver  : 0你好 Wed Nov 15 14:15:09 CST 2017
Receiver2  : 1你好 Wed Nov 15 14:15:09 CST 2017
Receiver  : 2你好 Wed Nov 15 14:15:09 CST 2017
Receiver2  : 3你好 Wed Nov 15 14:15:09 CST 2017
Receiver  : 4你好 Wed Nov 15 14:15:09 CST 2017
Receiver2  : 5你好 Wed Nov 15 14:15:09 CST 2017
Receiver  : 6你好 Wed Nov 15 14:15:09 CST 2017
Receiver2  : 7你好 Wed Nov 15 14:15:09 CST 2017
Receiver  : 8你好 Wed Nov 15 14:15:09 CST 2017
Receiver2  : 9你好 Wed Nov 15 14:15:09 CST 2017
Receiver  : 10你好 Wed Nov 15 14:15:09 CST 2017

...

当然还有可能有多个发送者,复制发送者即可,结果和一对多一样,仍然会均匀接收到消息

你可能感兴趣的:(经验总结)