rabbitMq 動(dòng)態(tài)申明和監(jiān)聽

基于springboot簡化版配置

1.maven配置

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

2.application.yml配置

spring:
  rabbitmq:
    host: localhost
    port: 5672
    username: admin
    password: asdD#5123@
    virtual-host: soa
rabbit:
    queue: test888
    exchange: test888
    routingkey: test888

3.消費(fèi)者端監(jiān)聽代碼

package com.example.amqp_test.receiver;
 
 
 
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
 
import java.util.Objects;
 
@Component
public class PaymentReceiver {
 

    @RabbitListener(bindings = @QueueBinding(
            value=@Queue(value = "${rabbit.queue}",durable = "true"),
            exchange = @Exchange(value = "${rabbit.exchange}"),
            key="${rabbit.routingkey}"))//動(dòng)態(tài)申明,這里面不能在有queues ="" 注解了否則會(huì)報(bào)錯(cuò)
    private void handleMessage(Message message) {
 
        try {
            if(Objects.isNull(message)){
                return;
            } 
            String ss =new String(message.getBody());
            System.out.println("msg is {}"+ss);
           // LogUtils.COMMON.info("subscribe :{}"+ new String(message.getBody()));
            //todo
 
        } catch (Exception e) {
            e.printStackTrace();
        } 
    } 
}

3.啟動(dòng)類

package com.example.amqp_test;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class AmqpTestApplication {

    public static void main(String[] args) {
        SpringApplication.run(AmqpTestApplication.class, args);
    }
}

4.測(cè)試效果

image.png

可以看到自動(dòng)申明成功了

4.1 發(fā)布消息

image.png

4.1 控制臺(tái)打印結(jié)果

image.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容