消息队列 (5) RabbtMQ SpringBoot整合

pom文件引入依赖

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>

application.ml 配置文件编写

server:
  port: 9999
spring:
  rabbitmq:
    host: 10.211.55.4
    virtual-host: local
    port: 5672
    username: admin
    password: admin

RabbitMQConfig 配置类编写

@Configuration
public class RabbitMQConfig {
    public static final String EXCHANGE_NAME = "boot_topic";
    public static final String QUEUE_NAME = "boot_queue";
    public static final String Routing_Key = "boot.#";


    // 1.交换机
    @Bean("bootExchange")
    public Exchange bootExchange(){
        return ExchangeBuilder.topicExchange(EXCHANGE_NAME).durable(true).build();
    }


    //2.Queue队列
    @Bean("bootQueue")
    public Queue bootQueue(){
        return QueueBuilder.durable(QUEUE_NAME).build();
    }

    //3.绑定交换机和队列
    @Bean
    public Binding bindQueueExchange(@Qualifier("bootQueue") Queue queue,@Qualifier("bootExchange") Exchange exchange){
        return BindingBuilder.bind(queue).to(exchange).with(Routing_Key).noargs();
    }
}

发送消息

@RestController
public class rabiitController {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @RequestMapping("/")
    public void home(){
        rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME,"boot.test","spring boot rabbit mq");
    }
}

启动项目并访问 localhost:9999 没有报错说明调用成功了,这时访问rabiitmq 控制台 http://10.211.55.4:15672/

接下来编写消费者

package com.rabiitmq.demo;

import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
public class RabbitMQListener {

    @RabbitListener(queues = RabbitMQConfig.QUEUE_NAME)
    public void bootConsumer(org.springframework.amqp.core.Message message){
        System.out.println(message);
    }
}

注入bean 持续监听队列

输出内容

(Body:'spring boot rabbit mq' MessageProperties [headers={}, contentType=text/plain, contentEncoding=UTF-8, contentLength=0, receivedDeliveryMode=PERSISTENT, priority=0, redelivered=false, receivedExchange=boot_topic, receivedRoutingKey=boot.test, deliveryTag=1, consumerTag=amq.ctag-lminlXccIxo288o4leEVDg, consumerQueue=boot_queue])

原文地址:https://www.cnblogs.com/baidawei/p/13293564.html