首页 > 编程语言 > 详细

SpringBoot整合RabbitMQ入门~~

时间:2020-01-12 10:17:51      阅读:81      评论:0      收藏:0      [点我收藏+]

SpringBoot整合RabbitMQ 入门2020-01-12

            创建生产者类,并且在yml配置文件中配置5要素连接MQ
yml配置文件
        spring:  
                rabbitmq:    
                    host: xx.xx.xx.xx   
                    port: 5672    
                    virtual-host: /    
                    username: 默认guest    
                    password: 默认guest
编写生产者代码
            使用@Configuration 表名它是配置类
 
再类中声明三要素
         //交换机名称
@Bean("itemTopicExchange")    
    public Exchange topicExchange(){        
    return  ExchangeBuilder.topicExchange(交换机名称).durable(true).build();   
    }
 
        //队列名称
@Bean("itemQueue")    
     public Queue itemQueue(){        
     return QueueBuilder.durable(队列名称).build();    
}
        //绑定交换机和队列
@Bean    
public Binding itemQueueExchange(@Qualifier("队列id") Queue queue,@Qualifier("交换机id") Exchange exchange){
         return BindingBuilder.bind(队列).to(交换机).with("item.#").noargs();
}
 
编写一个发送消息的测试类
@RunWith(SpringRunner.class)
@SpringBootTest
public class Test {
    /*
    * 测试类,测试发送消息是否成功
    * */
    @Autowired
    private RabbitTemplate template;
 
 
    @org.junit.Test
    public void test() {
        template.convertAndSend(TestProducer.EXCHANGE_TEST, "test.hh", "你好呀~~~~");
    }
}
来测试声明的交换机和队列是否绑定,能否正常的发送消息
http://xx.xx.xx.xx:15672/#/queues 访问mq的服务,查看消息是否存入到队列中
 
接下来编写消费方,只需要编写一个消息接听类,用来监听队列中未被消费的消息,运行启动类即可
/*
* 监听队列消息
* */
@Component
public class MyListener {
 
    @RabbitListener(queues ="test_queue")
    public void test1(String message){
        System.out.println("队列中的消息是"+message);
    }
}

  

 

SpringBoot整合RabbitMQ入门~~

原文:https://www.cnblogs.com/zxfirst/p/12181910.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!