rabbitMq 动态申明和监听

基于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.消费者端监听代码

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}"))//动态申明,这里面不能在有queues ="" 注解了否则会报错
    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.启动类

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.测试效果

image.png

可以看到自动申明成功了

4.1 发布消息

image.png

4.1 控制台打印结果

image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容