SpringAMQP 二 (Work Queue 工作队列)

1. Work Queue 工作队列

SpringAMQP 二 (Work Queue 工作队列)_第1张图片
消息是阅后即焚,如果消息来的过多,可以使用两个消费者

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来控制消费者预取的消息数量

你可能感兴趣的:(微服务,RabbitMQ,java-rabbitmq,rabbitmq,java)