美文网首页
rabbitMq 动态申明和监听

rabbitMq 动态申明和监听

作者: 他是人间惆怅客 | 来源:发表于2019-10-12 17:05 被阅读0次

    基于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

    相关文章

      网友评论

          本文标题:rabbitMq 动态申明和监听

          本文链接:https://www.haomeiwen.com/subject/hetcmctx.html