springboot与rabbitMQ整合步骤

springboot整合rabbitMQ

  • 1、添加依赖。springboot提供了与rabbitMQ进行整合的依赖,因此需要将springboot与rabbitMQ的依赖添加到pom.xml文件中。
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
  • 2、编写springboot与rabbitMQ的整合配置类。
    @Configuration
    public class SpringRabbitMQConfig {

        final static String queueName = "queue.demo";   //这里是队列的名称,交换机和队列进行绑定有个匹配模式,当producer 发送数据到指定路由键queue.demo或与 绑定的匹配模式进行匹配。
        /**
         * 定义一个队列
         * @return
         */
        @Bean
        Queue queue() {
            return new Queue(queueName, false);
        }
        /**
         * 定义一个topic交换机
         * @return
         */
        @Bean
        public TopicExchange topicExchange(){
            TopicExchange exchange=new TopicExchange("spring-boot-topicExchange");
            return exchange;
        }
        /**
         * 让队列和交换机绑定
         * @param queue   参数名称必须是queue,springboot默认使用的时方法名。-->对应上面的queue()方法
         * @param topicExchange 参数必须是topicExchange ,springboot默认使用的是方法名-->对应上面的topicExchange()方法
         * @return
         */
        @Bean
        public Binding bindingQueueAndTopicExchange(Queue queue,TopicExchange topicExchange){
            return BindingBuilder.bind(queue).to(topicExchange).with("queue.#");//路由匹配,这里是路由匹配规则。
        }

    }

-3、编写生产者处理类

@Component
public class MQSendHandler {
    @Autowired
    private AmqpTemplate amqpTemplate;//springboot会帮我们创建。
    public void send(){
        String sendMsg = "hello " + new Date();
        System.out.println("rabbit生产者发送消息 : " + sendMsg);
        amqpTemplate.convertAndSend("spring-boot-topicExchange", "queue.demo", sendMsg); 
        //第一个参数:交换机的名字,我们在第二步,声明了topic交换机名称为spring-boot-topicExchange的交换机,因此这里写spring-boot-topicExhchange
        第二个参数:队列的名称,我们在第二步,配置了名字为queue.demo的队列,因此这里写的是queue.demo
        第三个参数:要发送的消息数据。
        说明:当生成这发送数据到mq后,首先会寻找与路由键匹配的绑定模式,而我们的匹配规则是queue.#  (其中#标示0个或多个,*标示至少有一个),因此这里发送的数据会被被queue.demo的队列消费。
    }
}
  • 4、编写消费者处理类
@Component
@RabbitListener(queues = "queue.demo")//这里写的是监听的是哪个队列。
public class MQReceiverHandler {
    @RabbitHandler
    public void process(String message) {
        System.out.println("接受端  : " + message);
    }
}

-5、springboot配置文件application.properties或者application.yml配置rabbitMQ的配置

spring.rabbitmq.host=192.168.1.215
spring.rabbitmq.port=5672
spring.rabbitmq.username=admin
spring.rabbitmq.password=123456
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值