文章目录
- 其他文章地址
- 1、pom依赖
- 2、配置文件
- 3、Swagger配置
- 4、5种工作模式的配置类
- 4.1、HelloWorld(简单)
- 4.2、WorkQueue(工作队列)
- 4.3、Fanout(广播)
- 4.4、Direct(路由)
- 4.5、Topic(通配符)
- 5、生产者
- 6、消费者
- 7、启动类
1、RabbitMQ——单机版安装(3.6.5)
2、RabbitMQ——入门篇
3、RabbitMQ——实战篇1(原生API)
4、RabbitMQ——实战篇2(Spring集成)
5、RabbitMQ——实战篇3(Spring集成高级特性:死信队列,消息丢失,延迟队列)
6、RabbitMQ——实战篇4(SpringBoot集成)
项目地址:https://gitee.com/zhouzhz/rabbitmq
1、pom依赖<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.1.4.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.zhz</groupId><artifactId>boot_mq</artifactId><version>0.0.1-SNAPSHOT</version><name>boot_mq</name><description>boot集成mq</description><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><maven.compiler.source>1.8</maven.compiler.source><maven.compiler.target>1.8</maven.compiler.target><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-amqp</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger2</artifactId><version>2.9.2</version></dependency><dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger-ui</artifactId><version>2.9.2</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.13</version><scope>test</scope></dependency></dependencies><build><finalName>springboot_rabbitmq</finalName><pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --><plugins><plugin><artifactId>maven-clean-plugin</artifactId><version>3.1.0</version></plugin><!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging --><plugin><artifactId>maven-resources-plugin</artifactId><version>3.0.2</version></plugin><plugin><artifactId>maven-compiler-plugin</artifactId><version>3.8.0</version></plugin><plugin><artifactId>maven-surefire-plugin</artifactId><version>2.22.1</version></plugin><plugin><artifactId>maven-war-plugin</artifactId><version>3.2.2</version></plugin><plugin><artifactId>maven-install-plugin</artifactId><version>2.5.2</version></plugin><plugin><artifactId>maven-deploy-plugin</artifactId><version>2.8.2</version></plugin></plugins></pluginManagement></build></project>2、配置文件
application.yml
#端口配置 server: port: 8080#集成配置 spring: rabbitmq:port: 5672addresses: 192.168.0.66username: zhzmq password: zhzmq virtual-host: /zhztest #集群地址配置 #spring.rabbitmq.addresses=172.16.48.10:5672,172.16.48.11:5672,172.16.48.12:5672
日志配置
#Set everything to be logged to the console #log4j.rootCategory=INFO, console, D log4j.rootCategory=INFO, console,log4j.appender.console=org.apache.log4j.ConsoleAppender #log4j.appender.console.target=System.err log4j.appender.console.layout=org.apache.log4j.PatternLayout log4j.appender.console.layout.ConversionPattern=%d{yyyyMMdd HH:mm:ss} %p %c{1}:%L - %m%n log4j.additivity.com.hisun.swordrisk = false log4j.logger.org.apache.hadoop.ipc.Server = WARN log4j.appender.D=org.apache.log4j.DailyRollingFileAppender log4j.appender.D.File= logs/task.log log4j.appender.D.Append=truelog4j.appender.D.Threshold=DEBUG log4j.appender.D.layout=org.apache.log4j.PatternLayout log4j.appender.D.layout.ConversionPattern=%d{yyyyMMdd HH:mm:ss} %p %c{1} %m%n3、Swagger配置
package com.zhz.swagger;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import springfox.documentation.builders.ApiInfoBuilder;import springfox.documentation.builders.PathSelectors;import springfox.documentation.builders.RequestHandlerSelectors;import springfox.documentation.service.ApiInfo;import springfox.documentation.spi.DocumentationType;import springfox.documentation.spring.web.plugins.Docket;import springfox.documentation.swagger2.annotations.EnableSwagger2;@Configuration@EnableSwagger2public class Swagger2 { // http://127.0.0.1:8080/swagger-ui.html @Beanpublic Docket createRestApi() {return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select().apis(RequestHandlerSelectors.basePackage("com.zhz")).paths(PathSelectors.any()).build();}private ApiInfo apiInfo() {return new ApiInfoBuilder().title("springboot集成rabbitmq").description("springboot集成rabbitmq的5种工作模式").termsOfServiceUrl("https://editor.csdn.net/md?articleId=113616890").contact("zhz").version("1.0").build();}}4、5种工作模式的配置类
4.1、HelloWorld(简单)
package com.zhz.config;import org.springframework.amqp.core.Queue;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;/** * @author :zhz * @date :Created in 2021/02/07 * @version: V1.0 * @slogan: 天下风云出我辈,一入代码岁月催 * @description: **/@Configurationpublic class HelloWorldConfig {//队列@Beanpublic Queue setQueue(){return new Queue("helloWorldQueue");}}
4.2、WorkQueue(工作队列)
package com.zhz.config;import org.springframework.amqp.core.Queue;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;/** * @author :zhz * @date :Created in 2021/02/07 * @version: V1.0 * @slogan: 天下风云出我辈,一入代码岁月催 * @description: **/@Configurationpublic class WorkConfig {//队列//声明队列@Beanpublic Queue workQ1() {return new Queue("work_sb_mq_q");}}
4.3、Fanout(广播)
package com.zhz.config;import org.springframework.amqp.core.Binding;import org.springframework.amqp.core.BindingBuilder;import org.springframework.amqp.core.FanoutExchange;import org.springframework.amqp.core.Queue;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;/** * @author :zhz * @date :Created in 2021/02/07 * @version: V1.0 * @slogan: 天下风云出我辈,一入代码岁月催 * @description: Fanout模式需要声明exchange,并绑定queue,由exchange负责转发到queue上。 * 广播模式 交换机类型设置为:fanout **/@Configurationpublic class FanoutConfig {//队列@Beanpublic Queue fanoutQ1(){return new Queue("fanout.q1");}@Beanpublic Queue fanoutQ2(){return new Queue("fanout.q2");}//交换机@Beanpublic FanoutExchange setFanoutExchange(){return new FanoutExchange("fanoutExchange");}//绑定交换机和队列@Beanpublic Binding bindQ1(){return BindingBuilder.bind(fanoutQ1()).to(setFanoutExchange());}@Beanpublic Binding bindQ2(){return BindingBuilder.bind(fanoutQ2()).to(setFanoutExchange());}}
4.4、Direct(路由)
package com.zhz.config;import org.springframework.amqp.core.Binding;import org.springframework.amqp.core.BindingBuilder;import org.springframework.amqp.core.DirectExchange;import org.springframework.amqp.core.Queue;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;/** * @author :zhz * @date :Created in 2021/02/07 * @version: V1.0 * @slogan: 天下风云出我辈,一入代码岁月催 * @description: 路由模式|Routing模式 交换机类型:direct ==>需要交换机 **/@Configurationpublic class DirectConfig {//声明队列@Beanpublic Queue directQ1(){return new Queue("direct_sb_mq_q1");}@Beanpublic Queue directQ2(){return new Queue("direct_sb_mq_q2");}//声明交换机exchange@Beanpublic DirectExchange setDirectExchange(){return new DirectExchange("directExchange");}//绑定交换机和队列@Beanpublic Binding bindDirectBinding1(){return BindingBuilder.bind(directQ1()).to(setDirectExchange()).with("china.changsha");}@Beanpublic Binding bindDirectBinding2(){return BindingBuilder.bind(directQ2()).to(setDirectExchange()).with("china.beijing");}}
4.5、Topic(通配符)
package com.zhz.config;import org.springframework.amqp.core.*;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;/** * @author :zhz * @date :Created in 2021/02/07 * @version: V1.0 * @slogan: 天下风云出我辈,一入代码岁月催 * @description: **/@Configurationpublic class TopicConfig {//队列@Beanpublic Queue topicQ1(){return new Queue("topic_sb_mq_q1");}@Beanpublic Queue topicQ2(){return new Queue("topic_sb_mq_q2");}//交换机@Beanpublic TopicExchange setTopicExchange(){return new TopicExchange("topicExchange");}//绑定交换机和队列,声明binding,需要声明一个routingKey@Beanpublic Binding bindTopic1(){return BindingBuilder.bind(topicQ1()).to(setTopicExchange()).with("changsha.*");}@Beanpublic Binding bindQ2(){return BindingBuilder.bind(topicQ2()).to(setTopicExchange()).with("#.beijing");}}5、生产者
package com.zhz.controller;import io.swagger.annotations.ApiOperation;import org.springframework.amqp.AmqpException;import org.springframework.amqp.core.Message;import org.springframework.amqp.core.MessageProperties;import org.springframework.amqp.rabbit.core.RabbitTemplate;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RestController;import java.io.UnsupportedEncodingException;/** * @author :zhz * @date :Created in 2021/02/07 * @version: V1.0 * @slogan: 天下风云出我辈,一入代码岁月催 * @description: **/@RestControllerpublic class ProducerController {@Autowiredprivate RabbitTemplate rabbitTemplate;//helloWord直连@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 send: " + 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 send: " + 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下的所有queuerabbitTemplate.send("fanoutExchange", "", new Message(message.getBytes("UTF-8"), messageProperties));return "message send: " + 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 (routingKey == null) {routingKey = "china.changsha";}//设置部分请求参数MessageProperties messageProperties = new MessageProperties();messageProperties.setContentType(MessageProperties.CONTENT_TYPE_TEXT_PLAIN);rabbitTemplate.send("directExchange", routingKey, new Message(message.getBytes("UTF-8"), messageProperties));return "message send : 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 (routingKey == null) {routingKey = "changsha.kf";}//设置部分请求参数MessageProperties messageProperties = new MessageProperties();messageProperties.setContentType(MessageProperties.CONTENT_TYPE_TEXT_PLAIN);rabbitTemplate.send("topicExchange", routingKey, new Message(message.getBytes("UTF-8"), messageProperties));return "message send : routingKey >" + routingKey + ";message > " + message;}}6、消费者
package com.zhz.controller;import org.springframework.amqp.rabbit.annotation.RabbitListener;import org.springframework.stereotype.Component;/** * @author :zhz * @date :Created in 2021/02/07 * @version: V1.0 * @slogan: 天下风云出我辈,一入代码岁月催 * @description: 监听 **/@Componentpublic class ConsumerReceiver {//直连模式的多个消费者,会分到其中一个消费者进行消费。类似task模式//通过注入RabbitContainerFactory对象,来设置一些属性,相当于task里的channel.basicQos@RabbitListener(queues = "helloWorldQueue")public void helloWorldReceive(String message){System.out.println("hello world:"+message);}//工作队列模式@RabbitListener(queues = "work_sb_mq_q")public void wordQueueReceiveQ1(String message){System.out.println("工作队列模式1:"+message);}@RabbitListener(queues = "work_sb_mq_q")public void wordQueueReceiveQ2(String message){System.out.println("工作队列模式2:"+message);}//pub/sub模式进行消息监听@RabbitListener(queues = "fanout.q1")public void fanoutReceiveQ1(String message){System.out.println("发布订阅模式1:"+message);}@RabbitListener(queues = "fanout.q2")public void fanoutReceiveQ2(String message){System.out.println("发布订阅模式1:"+message);}//Routing路由模式@RabbitListener(queues="direct_sb_mq_q1")public void routingReceiveQ1(String message) {System.out.println("Routing路由模式1: " +message);}@RabbitListener(queues="direct_sb_mq_q2")public void routingReceiveQ2(String message) {System.out.println("Routing路由模式2: " +message);}//topic 模式//注意这个模式会有优先匹配原则。例如发送routingKey=guangzhou.IT,那匹配到guangzhou.*(guangzhou.IT,guangzhou.eco),之后就不会再去匹配*.ITd@RabbitListener(queues="topic_sb_mq_q1")public void topicReceiveQ1(String message) {System.out.println("Topic模式1: " +message);}@RabbitListener(queues="topic_sb_mq_q2")public void topicReceiveQ2(String message) {System.out.println("Topic模式2: " +message);}}7、启动类
package com.zhz;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic class BootMqApplication {public static void main(String[] args) {SpringApplication.run(BootMqApplication.class, args);}}