栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 前沿技术 > 大数据 > 大数据系统

SpringBoot集成RabbitMQ消息中间件

SpringBoot集成RabbitMQ消息中间件

有了SpringBoot框架,我们开发RabbitMQ会十分便捷。
	首先需要引入pom文件:
		
		
			org.springframework.boot
			spring-boot-starter-amqp
		
	然后我们需要在配置文件加入  rabbitMq相关的配置信息,这个需要在发送方和接收方同时配置。
spring
   rabbitmq:
      host: 127.0.0.1
      port: 5672
      username: guest
      password: guest
      virtual-host: /

发送方:
	加入配置文件:
package org.jeecg.rabbitmq发送方.boot.config;


import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;




@Configuration
public class RabbitMQConfig {
    public static final String EXCHANGE_NAME = "boot_topic_exchange";
    public static final String QUEUE_NAME = "boot_queue";

    //1.交换机
    @Bean("botExchange")
    public Exchange  botExchange(){
        return ExchangeBuilder.topicExchange(EXCHANGE_NAME).durable(true).build();
    }



    //2.queue 队列
    @Bean("bootQueue")
    public Queue bootQueue(){
        return QueueBuilder.durable(QUEUE_NAME).build();
    }



    //3.队列和交换的绑定
    @Bean
    public Binding bindQueueExchange(@Qualifier("bootQueue") Queue queue, @Qualifier("botExchange") Exchange exchange ){
        return BindingBuilder.bind(queue).to(exchange).with("boot.#").noargs();
    }


}

	测试Controller:
package org.jeecg.rabbitmq发送方.boot;

import org.jeecg.rabbitmq发送方.boot.config.RabbitMQConfig;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;


@RestController
@RequestMapping("/rabbitmq")
public class TestController {


    //1.注入 RabbitTemplate
    @Resource
    private RabbitTemplate rabbitTemplate;

    @GetMapping("/testSend")
    public String testSend(){

        rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME,"boot.haha","哈哈 今天 是2021-12-16");

        return "发送成功!";
    }


}

	开始测试:

接受方:
	接收方我们只用 监听消息后消费即可,代码相对较少.
package org.jeecg.rabbitmq接收方.boot;

import com.sun.org.apache.xpath.internal.operations.String;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;


@Component
public class RabbitMQListener {

    @RabbitListener(queues = "boot_queue")
    public void ListenerQueue( Message  message){

        System.out.println(message);
    }

}

	当消费方发送消息他将自动接收并 消费。


消息接收成功。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/673491.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号