1. 程式人生 > 實用技巧 >訊息佇列 (5) RabbtMQ SpringBoot整合

訊息佇列 (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])