SpringAMQP 二 (Work Queue 工作队列)

1. Work Queue 工作队列

在这里插入图片描述
消息是阅后即焚,如果消息来的过多,可以使用两个消费者

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

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

基本思路如下:
1.在publisher服务中定义测试方法,每秒产生50条消息,发送到simple.queue

public void testSendMessage2WorkQueue() throws InterruptedException {
        String queuqname = "simple.queue";
        String message = "hello,message__!";
        for(int i=1;i<=50;i++){
            rabbitTemplate.convertAndSend(queuqname,message+i);
            Thread.sleep(20);

        }

    }

2.在consumer服务中定义两个消息监听者,都监听simple.queue队列

 @RabbitListener(queues = "simple.queue")
    public void listenWorkQueue(String msg) throws InterruptedException {
        System.out.println("消费者1接收到simple.queue的消息:【"+msg+"】"+ LocalTime.now());
        Thread.sleep(20);
    }
    @RabbitListener(queues = "simple.queue")
    public void listenWorkQueue2(String msg) throws InterruptedException {
        System.err.println("消费者2接收到simple.queue.......的消息:【"+msg+"】");
        Thread.sleep(200);
    }

3 消费者1每秒处理50条消息,消费者2每秒处理10条消息

结果是两个消费者平均处理了50条消息,是由于rabbitmq内部的 消息预取机制,消息预期指当大量消息到达队列时,两个消费者会提前将消息取过去(轮流拿)

消费预取限制

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

spring:
  rabbitmq:
      host: 192.168.138.100  # 自己的虚拟机ip地址
      port: 5672 # 端口
      username: itcast
      password: 123321
      virtual-host: /
      listener:
        simple:
          prefetch: 1

总结 Work模型的使用:

  • 多个消费者绑定到一个队列,同一条消息只会被一个消费者处理
  • 通过设置prefetch来控制消费者预取的消息数量
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阿岳316

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值