SpringBoot整合RabbitMQ的5种模式实战


Posted in Java/Android onAugust 02, 2021

一、环境准备

SpringBoot整合RabbitMQ的5种模式实战

1、pom依赖

<!-- 父工程依赖 -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.6.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.6.0</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.6.0</version>
        </dependency>
    </dependencies>

2、配置文件

server:
  port: 8080

spring:
  rabbitmq:
    host: 192.168.131.171
    port: 5672
    username: jihu
    password: jihu
    virtual-host: /jihu

3、启动类

@SpringBootApplication
public class RabbitMQApplication {
   public static void main(String[] args) {
       SpringApplication.run(RabbitMQApplication.class);
   }
}

5、Swagger2类

@Configuration
@EnableSwagger2
public class Swagger2 {
    // http://127.0.0.1:8080/swagger-ui.html
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.jihu"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("极狐-Spring Boot中使用spring-boot-starter-amqp集成rabbitmq")
                .description("测试SpringBoot整合进行各种工作模式信息的发送")
/*
	                .termsOfServiceUrl("https://www.jianshu.com/p/c79f6a14f6c9")
*/
                .contact("roykingw")
                .version("1.0")
                .build();
    }
}

6、ProducerController

@RestController
public class ProducerController {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    //helloWorld 直连模式
    @ApiOperation(value = "helloWorld发送接口", notes = "直接发送到队列")
    @GetMapping(value = "/helloWorldSend")
    public Object helloWorldSend(String message) throws AmqpException, UnsupportedEncodingException {
        //设置部分请求参数
        MessageProperties messageProperties = new MessageProperties();
        messageProperties.setContentType(MessageProperties.CONTENT_TYPE_TEXT_PLAIN);

        //发消息
        rabbitTemplate.send("helloWorldqueue", new Message(message.getBytes("UTF-8"), messageProperties));
        return "message sended : " + message;
    }


    //工作队列模式
    @ApiOperation(value = "workqueue发送接口", notes = "发送到所有监听该队列的消费")
    @GetMapping(value = "/workqueueSend")
    public Object workqueueSend(String message) throws AmqpException, UnsupportedEncodingException {
        MessageProperties messageProperties = new MessageProperties();
        messageProperties.setContentType(MessageProperties.CONTENT_TYPE_TEXT_PLAIN);
        //制造多个消息进行发送操作
        for (int i = 0; i < 10; i++) {
            rabbitTemplate.send("work_sb_mq_q", new Message(message.getBytes("UTF-8"), messageProperties));
        }
        return "message sended : " + message;
    }


    // pub/sub 发布订阅模式   交换机类型 fanout
    @ApiOperation(value = "fanout发送接口", notes = "发送到fanoutExchange。消息将往该exchange下的所有queue转发")
    @GetMapping(value = "/fanoutSend")
    public Object fanoutSend(String message) throws AmqpException, UnsupportedEncodingException {
        MessageProperties messageProperties = new MessageProperties();
        messageProperties.setContentType(MessageProperties.CONTENT_TYPE_TEXT_PLAIN);
        //fanout模式只往exchange里发送消息。分发到exchange下的所有queue
        rabbitTemplate.send("fanoutExchange", "", new Message(message.getBytes("UTF-8"), messageProperties));
        return "message sended : " + message;
    }


    //routing路由工作模式  交换机类型 direct
    @ApiOperation(value = "direct发送接口", notes = "发送到directExchange。exchange转发消息时,会往routingKey匹配的queue发送")
    @GetMapping(value = "/directSend")
    public Object routingSend(String routingKey, String message) throws AmqpException, UnsupportedEncodingException {

        if (null == routingKey) {
            routingKey = "china.changsha";
        }
        MessageProperties messageProperties = new MessageProperties();
        messageProperties.setContentType(MessageProperties.CONTENT_TYPE_TEXT_PLAIN);
        //fanout模式只往exchange里发送消息。分发到exchange下的所有queue
        rabbitTemplate.send("directExchange", routingKey, new Message(message.getBytes("UTF-8"), messageProperties));
        return "message sended : routingKey >" + routingKey + ";message > " + message;
    }


    //topic 工作模式   交换机类型 topic
    @ApiOperation(value = "topic发送接口", notes = "发送到topicExchange。exchange转发消息时,会往routingKey匹配的queue发送,*代表一个单词,#代表0个或多个单词。")
    @GetMapping(value = "/topicSend")
    public Object topicSend(String routingKey, String message) throws AmqpException, UnsupportedEncodingException {

        if (null == routingKey) {
            routingKey = "changsha.kf";
        }
        MessageProperties messageProperties = new MessageProperties();
        messageProperties.setContentType(MessageProperties.CONTENT_TYPE_TEXT_PLAIN);
        //fanout模式只往exchange里发送消息。分发到exchange下的所有queue
        rabbitTemplate.send("topicExchange", routingKey, new Message(message.getBytes("UTF-8"), messageProperties));
        return "message sended : routingKey >" + routingKey + ";message > " + message;
    }

}

7、ConcumerReceiver

@Component
public class ConcumerReceiver {


    //直连模式的多个消费者,会分到其中一个消费者进行消费。类似task模式
    //通过注入RabbitContainerFactory对象,来设置一些属性,相当于task里的channel.basicQos
    @RabbitListener(queues = "helloWorldqueue")
    public void helloWorldReceive(String message) {

        System.out.println("helloWorld模式 received message : " + message);
    }

    //工作队列模式
    @RabbitListener(queues = "work_sb_mq_q")
    public void wordQueueReceiveq1(String message) {

        System.out.println("工作队列模式1 received message : " + message);
    }

    @RabbitListener(queues = "work_sb_mq_q")
    public void wordQueueReceiveq2(String message) {

        System.out.println("工作队列模式2 received message : " + message);
    }


    //pub/sub模式进行消息监听
    @RabbitListener(queues = "fanout.q1")
    public void fanoutReceiveq1(String message) {

        System.out.println("发布订阅模式1received message : " + message);
    }

    @RabbitListener(queues = "fanout.q2")
    public void fanoutReceiveq2(String message) {

        System.out.println("发布订阅模式2 received message : " + message);
    }


    //Routing路由模式
    @RabbitListener(queues = "direct_sb_mq_q1")
    public void routingReceiveq1(String message) {

        System.out.println("Routing路由模式routingReceiveq11111 received message : " + message);
    }

    @RabbitListener(queues = "direct_sb_mq_q2")
    public void routingReceiveq2(String message) {

        System.out.println("Routing路由模式routingReceiveq22222 received message : " + message);
    }


    //topic 模式
    //注意这个模式会有优先匹配原则。例如发送routingKey=hunan.IT,那匹配到hunan.*(hunan.IT,hunan.eco),之后就不会再去匹配*.ITd
    @RabbitListener(queues = "topic_sb_mq_q1")
    public void topicReceiveq1(String message) {
        System.out.println("Topic模式 topic_sb_mq_q1 received message : " + message);
    }

    @RabbitListener(queues = "topic_sb_mq_q2")
    public void topicReceiveq2(String message) {
        System.out.println("Topic模式 topic_sb_mq_q2 received  message : " + message);
    }

}

二、简单模式

队列配置:

/**
 * HelloWorld rabbitmq第一个工作模式
 * 直连模式只需要声明队列,所有消息都通过队列转发。
 * 无需设置交换机
 */
@Configuration
public class HelloWorldConfig {

	@Bean
	public Queue setQueue() {
		return new Queue("helloWorldqueue");
	}
}

三、工作队列模式

@Configuration
public class WorkConfig {

    //声明队列
    @Bean
    public Queue workQ1() {
        return new Queue("work_sb_mq_q");
    }
}

四、广播模式(Fanout)

/**
 * Fanout模式需要声明exchange,并绑定queue,由exchange负责转发到queue上。
 * 广播模式 交换机类型设置为:fanout
 */
@Configuration
public class FanoutConfig {

	//声明队列
	@Bean
	public Queue fanoutQ1() {
		return new Queue("fanout.q1");
	}
	@Bean
	public Queue fanoutQ2() {
		return new Queue("fanout.q2");
	}


	//声明exchange
	@Bean
	public FanoutExchange setFanoutExchange() {
		return new FanoutExchange("fanoutExchange");
	}


	//声明Binding,exchange与queue的绑定关系
	@Bean
	public Binding bindQ1() {
		return BindingBuilder.bind(fanoutQ1()).to(setFanoutExchange());
	}
	@Bean
	public Binding bindQ2() {
		return BindingBuilder.bind(fanoutQ2()).to(setFanoutExchange());
	}
}

五、直连模式(Direct)

/*
   路由模式|Routing模式   交换机类型:direct
*/
@Configuration
public class DirectConfig {

	//声明队列
	@Bean
	public Queue directQ1() {
		return new Queue("direct_sb_mq_q1");
	}
	@Bean
	public Queue directQ2() {
		return new Queue("direct_sb_mq_q2");
	}


	//声明exchange
	@Bean
	public DirectExchange setDirectExchange() {
		return new DirectExchange("directExchange");
	}

	//声明binding,需要声明一个routingKey
	@Bean
	public Binding bindDirectBind1() {
		return BindingBuilder.bind(directQ1()).to(setDirectExchange()).with("china.changsha");
	}
	@Bean
	public Binding bindDirectBind2() {
			return BindingBuilder.bind(directQ2()).to(setDirectExchange()).with("china.beijing");
	}

}

六、通配符模式(Topic)

/*
Topics模式  交换机类型 topic
* */
@Configuration
public class TopicConfig {

	//声明队列
	@Bean
	public Queue topicQ1() {
		return new Queue("topic_sb_mq_q1");
	}
	@Bean
	public Queue topicQ2() {
		return new Queue("topic_sb_mq_q2");
	}


	//声明exchange
	@Bean
	public TopicExchange setTopicExchange() {
		return new TopicExchange("topicExchange");
	}

	//声明binding,需要声明一个roytingKey
	@Bean
	public Binding bindTopicHebei1() {
		return BindingBuilder.bind(topicQ1()).to(setTopicExchange()).with("changsha.*");
	}
	@Bean
	public Binding bindTopicHebei2() {
		return BindingBuilder.bind(topicQ2()).to(setTopicExchange()).with("#.beijing");
	}
}

测试

我们启动上面的SpringBoot项目。

然后我们访问swagger地址:http://127.0.0.1:8080/swagger-ui.html

SpringBoot整合RabbitMQ的5种模式实战

然后我们就可以使用swagger测试接口了。

SpringBoot整合RabbitMQ的5种模式实战

SpringBoot整合RabbitMQ的5种模式实战

或者可以使用postman进行测试。

到此这篇关于SpringBoot整合RabbitMQ的5种模式实战的文章就介绍到这了,更多相关SpringBoot整合RabbitMQ模式内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Java/Android 相关文章推荐
springboot如何初始化执行sql语句
Jun 22 Java/Android
Java中使用Filter过滤器的方法
Jun 28 Java/Android
logback如何自定义日志存储
Aug 30 Java/Android
logback 实现给变量指定默认值
Aug 30 Java/Android
springboot 多数据源配置不生效遇到的坑及解决
Nov 17 Java/Android
alibaba seata服务端具体实现
Feb 24 Java/Android
RestTemplate如何通过HTTP Basic Auth认证示例说明
Mar 17 Java/Android
Java 超详细讲解数据结构中的堆的应用
Apr 02 Java/Android
解决springboot druid数据库连接失败后一直重连的方法
Apr 19 Java/Android
Spring Data JPA框架持久化存储数据到数据库
Apr 28 Java/Android
Java中生成微信小程序太阳码的实现方案
Jun 01 Java/Android
Java中的Kafka为什么性能这么快及4大核心详析
Sep 23 Java/Android
Log4j.properties配置及其使用
Aug 02 #Java/Android
一篇文章带你学习Mybatis-Plus(新手入门)
Spring Boot 排除某个类加载注入IOC的操作
Aug 02 #Java/Android
SpringBoot+VUE实现数据表格的实战
springboot 启动如何排除某些bean的注入
Aug 02 #Java/Android
idea 在springboot中使用lombok插件的方法
Spring Boot mybatis-config 和 log4j 输出sql 日志的方式
Jul 26 #Java/Android
You might like
php基础知识:类与对象(3) 构造函数和析构函数
2006/12/13 PHP
php对mongodb的扩展(初出茅庐)
2012/11/11 PHP
php删除文件夹及其文件夹下所有文件的函数代码
2013/01/23 PHP
PHP Filter过滤器全面解析
2016/08/09 PHP
在laravel中使用Symfony的Crawler组件分析HTML
2017/06/19 PHP
让你的PHP,APACHE,NGINX支持大文件上传
2021/03/09 PHP
JQuery中使用Ajax赋值给全局变量异常的解决方法
2014/01/10 Javascript
浅谈JavaScript正则表达式分组匹配
2015/04/10 Javascript
js实现的彩色方块飞舞奇幻效果
2016/01/27 Javascript
获取input标签的所有属性的方法
2016/06/28 Javascript
js仿腾讯QQ的web登陆界面
2016/08/19 Javascript
XMLHttpRequest Level 2 使用指南
2016/08/26 Javascript
bootstrap jquery dataTable 异步ajax刷新表格数据的实现方法
2017/02/10 Javascript
js生成word中图片处理方法
2018/01/06 Javascript
React Native自定义控件底部抽屉菜单的示例
2018/02/08 Javascript
[04:44]显微镜下的DOTA2第二期——你所没有注意到的细节
2014/06/20 DOTA
python抓取京东价格分析京东商品价格走势
2014/01/09 Python
Python3基础之list列表实例解析
2014/08/13 Python
Python中optionParser模块的使用方法实例教程
2014/08/29 Python
python使用fcntl模块实现程序加锁功能示例
2017/06/23 Python
Python抽象和自定义类定义与用法示例
2018/08/23 Python
python实现转圈打印矩阵
2019/03/02 Python
详解如何管理多个Python版本和虚拟环境
2019/05/10 Python
Puppeteer使用示例详解
2019/06/20 Python
如何通过50行Python代码获取公众号全部文章
2019/07/12 Python
Python如何实现邮件功能
2020/05/27 Python
html5各种页面切换效果和模态对话框用法总结
2014/12/15 HTML / CSS
耐克美国官网:Nike.com
2016/08/01 全球购物
Sam’s Club山姆会员商店:沃尔玛旗下高端会员制商店
2017/01/16 全球购物
比利时家具购买网站:Home24
2019/01/03 全球购物
C#实现对任一张表的数据进行增,删,改,查要求,运用Webservice,体现出三层架构
2014/07/11 面试题
酒店保安员岗位职责
2014/01/31 职场文书
写求职信有什么意义
2014/02/17 职场文书
诚信考试倡议书
2014/04/15 职场文书
实习评语大全
2014/04/26 职场文书
Python中的min及返回最小值索引的操作
2021/05/10 Python