RabbitMQ——实战篇4(SpringBoot集成)

阅读: 评论:0

RabbitMQ——实战篇4(SpringBoot集成)

RabbitMQ——实战篇4(SpringBoot集成)

文章目录

  • 其他文章地址
  • 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集成)

项目地址:

1、pom依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns=".0.0" xmlns:xsi=""xsi:schemaLocation=".0.0 .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><mavenpiler.source>1.8</mavenpiler.source><mavenpiler.target>1.8</mavenpiler.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 .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、配置文件

#端口配置
server:port: 8080#集成配置
spring:rabbitmq:port: 5672addresses: 192.168.0.66username: zhzmqpassword: zhzmqvirtual-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
#Category=INFO, console, D
Category=INFO, console,sole=org.apache.log4j.ConsoleAppender
#sole.target&#
sole.layout=org.apache.log4j.PatternLayout
sole.layout.ConversionPattern=%d{yyyyMMdd HH:mm:ss} %p %c{1}:%L - %m%nlog4j.additivity.hisun.swordrisk = false  
log4j.logger.apache.hadoop.ipc.Server = WARNlog4j.appender.D=org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File= logs/task.log
log4j.appender.D.Append=true
log4j.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%n

3、Swagger配置

package com.zhz.swagger;import t.annotation.Bean;
import t.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
@EnableSwagger2
public class Swagger2 {// 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("=113616890").contact("zhz").version("1.0").build();}
}

4、5种工作模式的配置类

4.1、HelloWorld(简单)

package fig;import org.Queue;
import t.annotation.Bean;
import t.annotation.Configuration;/*** @author :zhz* @date :Created in 2021/02/07* @version: V1.0* @slogan: 天下风云出我辈,一入代码岁月催* @description:**/
@Configuration
public class HelloWorldConfig {//队列@Beanpublic Queue setQueue(){return new Queue("helloWorldQueue");}}

4.2、WorkQueue(工作队列)

package fig;import org.Queue;
import t.annotation.Bean;
import t.annotation.Configuration;/*** @author :zhz* @date :Created in 2021/02/07* @version: V1.0* @slogan: 天下风云出我辈,一入代码岁月催* @description:**/
@Configuration
public class WorkConfig {//队列//声明队列@Beanpublic Queue workQ1() {return new Queue("work_sb_mq_q");}
}

4.3、Fanout(广播)

package fig;import org.Binding;
import org.BindingBuilder;
import org.FanoutExchange;
import org.Queue;
import t.annotation.Bean;
import t.annotation.Configuration;/*** @author :zhz* @date :Created in 2021/02/07* @version: V1.0* @slogan: 天下风云出我辈,一入代码岁月催* @description: Fanout模式需要声明exchange,并绑定queue,由exchange负责转发到queue上。*              广播模式 交换机类型设置为:fanout**/
@Configuration
public 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 fig;import org.Binding;
import org.BindingBuilder;
import org.DirectExchange;
import org.Queue;
import t.annotation.Bean;
import t.annotation.Configuration;/*** @author :zhz* @date :Created in 2021/02/07* @version: V1.0* @slogan: 天下风云出我辈,一入代码岁月催* @description: 路由模式|Routing模式   交换机类型:direct  ==>需要交换机**/
@Configuration
public 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 fig;import org.*;
import t.annotation.Bean;
import t.annotation.Configuration;/*** @author :zhz* @date :Created in 2021/02/07* @version: V1.0* @slogan: 天下风云出我辈,一入代码岁月催* @description:**/
@Configuration
public 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 ller;import io.swagger.annotations.ApiOperation;
import org.springframework.amqp.AmqpException;
import org.Message;
import org.MessageProperties;
import org.springframework.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:**/
@RestController
public 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 Bytes("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 Bytes("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 Bytes("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 Bytes("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 Bytes("UTF-8"), messageProperties));return "message send : routingKey >" + routingKey + ";message > " + message;}
}

6、消费者

package ller;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: 监听**/
@Component
public 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.),之后就不会再去匹配*.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;@SpringBootApplication
public class BootMqApplication {public static void main(String[] args) {SpringApplication.run(BootMqApplication.class, args);}}

我是小白弟弟,一个在互联网行业的小白,立志成为一名架构师
=1

本文发布于:2024-01-31 12:29:47,感谢您对本站的认可!

本文链接:https://www.4u4v.net/it/170667538728521.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:实战篇   RabbitMQ   SpringBoot
留言与评论(共有 0 条评论)
   
验证码:

Copyright ©2019-2022 Comsenz Inc.Powered by ©

网站地图1 网站地图2 网站地图3 网站地图4 网站地图5 网站地图6 网站地图7 网站地图8 网站地图9 网站地图10 网站地图11 网站地图12 网站地图13 网站地图14 网站地图15 网站地图16 网站地图17 网站地图18 网站地图19 网站地图20 网站地图21 网站地图22/a> 网站地图23