SpringAMQP 工作队列 Workqueue

发布时间:2022-07-01 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了SpringAMQP 工作队列 Workqueue脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

Work queue,工作队列,可以提高消息处理速度,避免队列消息堆积

SpringAMQP 工作队列 Workqueue

 

 

模拟WorkQueue,实现一个队列绑定多个消费者

基本思路如下:

  • 在Publisher服务中定义测试方法,每秒产生50条消息,发送到simple.queue
  • 在consumer服务中定义两个消息监听者,都监听simple.queue队列
  • 一个消息监听者每秒处理50条消息,另一个消费者每秒处理10条消息
@H_360_23@生产者循环发送消息到simple.queue
    @test
    public void testWorkQueue() throws InterruptedException {
        String queueName = "simple.queue";
        String message = "hello, work queue message=====";
        for (int i = 0; i < 50; i++) {

            rabbITTemplate.convertAndSend(queueName, message + i);
            Thread.sleep(20);
        }
    }

编写两个消费者,都监听simple.queue

    @RabbitListener(queues = "simple.queue")
    public void listenWorkQueue1(String msg) throws InterruptedException {
        System.out.PRintln("listenWorkQueue1 消费者接收到消息 :【" + msg + "】");
        Thread.sleep(25);
    }

    @RabbitListener(queues = "simple.queue")
    public void listenWorkQueue2(String msg) throws InterruptedException {
        System.err.println("listenWorkQueue2 消费者接收到消息 :【" + msg + "】");
        Thread.sleep(100);
    }

SpringAMQP 工作队列 Workqueue

 

运行结果发现消费者监听不会因为监听性能好而多处理消息,而是信息被平均分配处理,这是由RabbitMQ内部消息预取机制造成

 

消息预取:当有大量的消息发送到队列,队列会提前将消息依次投递给每个消息消费者,不会关心消费者处理能力。

消息预取限制

修改application.yML文件,设置preFetch这个值,可以控制预取消息的上限

spring:
  rabbitmq:
    host: 192.168.223.128 # 主机名
    port: 5672 # 端口
    virtual-host: / # 虚拟主机
    username: guest # 用户名
    password: guest # 密码
    listener:
      simple:
        prefetch: 1 # 每次只能获取一条消息,处理完成才能获取下一个消息

 

脚本宝典总结

以上是脚本宝典为你收集整理的SpringAMQP 工作队列 Workqueue全部内容,希望文章能够帮你解决SpringAMQP 工作队列 Workqueue所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。