springboot+rabbitmq两小时入门(二):消费者多线程

概要:

消费一条消息往往比产生一条消息慢很多,为了防止消息积压,一般需要开启消费者多线程同时消费消息。

 

application.properties配置:

spring.rabbitmq.host=localhost

# TCP/IP端口为5672,http端口为15672
spring.rabbitmq.port=5672

spring.rabbitmq.username=root

spring.rabbitmq.password=root

生产者:

package com.example.rabbitmq;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RabbitMQController {
    
    // 这里用的是RabbitTemplate发消息,也可以用AmqpTemplate,推荐使用RabbitTemplate。
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @GetMapping(value = "/helloRabbit")
    public String sendMQ(){
        for (int i = 0; i < 100; i++) {
            rabbitTemplate.convertAndSend("myExchange1", "routingKey1", "消费者多线程");
        }
        return "success";
    }
}

消费者:

package com.example.rabbitmq;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.stereotype.Component;

@Component
public class Receiver {

    /**
     * @RabbitListener:加了该注解的方法表示该方法是一个消费者
     * concurrency:并发数量。
     * 其他属性和注解想了解的话,自己按Ctrl点进去看
     */
    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(value = "myQueue1"),
                    exchange = @Exchange(value = "myExchange1"),
                    key = "routingKey1"
            ),
            concurrency =  "10"
    )
    public void process1(Message message) throws Exception {
        System.out.println("myQueue1:" + new String(message.getBody()));
        Thread.sleep(1000);
    }
}

启动项目,访问http://localhost:8080/helloRabbit,控制台每隔1秒打印10条“myQueue1:消费者多线程”,打印10次。 

你可能感兴趣的:(springboot+rabbitmq两小时入门(二):消费者多线程)