SpringBoot2+rabbitMQ 集成入门——消息消费

1:添加依赖


    org.springframework.boot
    spring-boot-starter-amqp

2:参数配置

spring.rabbitmq.host = 192.168.0.1
spring.rabbitmq.port = 5672
spring.rabbitmq.username = admin
spring.rabbitmq.password = 123456
spring.rabbitmq.virtual-host = /
spring.rabbitmq.connection-timeout = 5000

spring.rabbitmq.listener.simple.concurrency = 5
spring.rabbitmq.listener.simple.max-concurrency = 10
spring.rabbitmq.listener.simple.acknowledge-mode = manual
spring.rabbitmq.listener.simple.prefetch = 1

3:设置消息消费的监听器

@Component
public class OrderConsumer {
    
    @RabbitListener(bindings = @QueueBinding(
            value=@Queue(value="order-queue",durable = "true"),
            exchange = @Exchange(name = "order-exchange", durable = "true" ,type = "topic"),
            key = "order.#"
            )
    )
    @RabbitHandler
    public void receiveOrder(@Payload JSONObject vo,@Headers Map headers , Channel channel) throws Exception{
        System.out.println("--------消费者已经获取到消息-------");
        System.out.println("order>>"+vo.toString());
        long id = Long.valueOf(headers.get(AmqpHeaders.DELIVERY_TAG).toString());
        channel.basicAck(id , false);
    }

}

注意@RabbitListener的使用方式,其中binding操作以及exchange和queue的关系生成

4:启动项目

如果在rabbitMQ中有消息生成,那么在同一个路由exchange和同一个规则下的queue队列中,即可获取消息对象。

你可能感兴趣的:(Spring,Boot入门学习)