SpringBoot Rabbit 整合

SpringBoot整合RabbitMQ非常简单!因为SpringBoot太强大了,话不多说直接上demo,项目的整体框架如下所示:

image.png

resources文件夹下的 application.properties的文件如下:

spring.rabbitmq.host=10.**.***.**
spring.rabbitmq.port=5672
spring.rabbitmq.username=******
spring.rabbitmq.password=******
spring.rabbitmq.publisher-confirms=true
spring.rabbitmq.publisher-returns=true
spring.rabbitmq.template.mandatory=true

项目的pom.xml文件如下所示:

<?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 http://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>1.5.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>SpringBoot.rabbitMq</groupId>
    <artifactId>rabbtt</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>rabbtt</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <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>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

SpringBoot启动类:RabbttApplication


package SpringBoot.rabbitMq.rabbtt;

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.amqp.core.TopicExchange;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class RabbttApplication {
    
    
    @Bean
    public Queue helloQueue() {
        return new Queue("hello");
    }
    
    @Bean
    public Queue userQueue() {
        return new Queue("entity");
    }
    
    
    //===============以下是验证topic Exchange的队列==========
    @Bean
    public Queue topicMessageA() {
        return new Queue("topic.A");
    }
    
    @Bean
    public Queue topicMessageB() {
        return new Queue("topic.B");
    }
    
    @Bean
    TopicExchange exchange() {
        return new TopicExchange("exchange");
    }
    
    @Bean
    Binding bindingtopicMessageA(Queue topicMessageA,TopicExchange exchange) {
        return BindingBuilder.bind(topicMessageA).to(exchange).with("topic.A");
    }
    
    @Bean
    Binding bindingtopicMessageB(Queue topicMessageB,TopicExchange exchange) {
        return BindingBuilder.bind(topicMessageB).to(exchange).with("topic.#");//*表示一个词,#表示零个或多个词
    }
    
    //===============以上是验证topic Exchange的队列==========
    
    
    
    
    //===============以下是验证Fanout Exchange的队列==========
    @Bean
    public Queue fanoutMessageA() {
        return new Queue("fanout.A");
    }

    @Bean
    public Queue fanoutMessageB() {
        return new Queue("fanout.B");
    }

    @Bean
    public Queue fanoutMessageC() {
        return new Queue("fanout.C");
    }
    
    @Bean
    FanoutExchange fanoutExchange() {
        return new FanoutExchange("fanoutExchange");
    }
    
    
    @Bean
    Binding bindingExchangeA(Queue fanoutMessageA,FanoutExchange fanoutExchange) {
        return BindingBuilder.bind(fanoutMessageA).to(fanoutExchange);
    }
    
    @Bean
    Binding bindingExchangeB(Queue fanoutMessageB,FanoutExchange fanoutExchange) {
        return BindingBuilder.bind(fanoutMessageB).to(fanoutExchange);
    }
    
    @Bean
    Binding bindingExchangeC(Queue fanoutMessageC,FanoutExchange fanoutExchange) {
        return BindingBuilder.bind(fanoutMessageC).to(fanoutExchange);
    }

    public static void main(String[] args) {
        SpringApplication.run(RabbttApplication.class, args);
    }
    
    

}

二.SpringBoot整合RabbitMQ(Direct模式)

任何发送到Direct Exchange 上的消息都会转发到RouteKey指定的queue中。
1.一般使用RabbitMp自带的Exchange。
2.这种模式不需要对Exhange进行任何绑定(binding)操作。
3.消息传递时只需要一个简单的RouteKey,可理解为接收消息队列的名字,如RabbttApplication启动类中的“hello”,代码如下所示。
4.如果vhost中不存在RouteKey中指定的队列名,则该消息会被抛弃。

image.png

直接在启动类RabbttApplication中添加queues消息队列如下所示,

@Bean
   public Queue helloQueue() {
       return new Queue("hello");
   }

在hello文件夹中创建SingletonHello类发送消息,在SpringBoot中直接使用AmqpTemplate去发送消息,代码如下:

package SpringBoot.rabbitMq.rabbtt.hello;

import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class SingletonHello {
    
    @Autowired
    private AmqpTemplate amqpTemplate;
    
    public void send() {
        String sendMsg = "wan :" + "*****hello rabbit****";
        System.out.println("wan :" + sendMsg);
        amqpTemplate.convertAndSend("hello", sendMsg);
    }

}

在hello文件夹中创建SingletonHelloReceiver类来接受消息,代码如下所示:

package SpringBoot.rabbitMq.rabbtt.hello;

import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
@RabbitListener(queues =  "hello")
public class SingletonHelloReceiver {
    
    @RabbitHandler
    public void receiver(String hello) {
        System.out.println("*****SingletonHelloReceiver*****" + hello);
    }

}

验证测试代码,在controller文件夹中创建RabbitTestController类来测试,代码如下所示:

@RestController
@RequestMapping("/rabbit")
public class RabbitTestController {
    
    @Autowired
    private SingletonHello singletonHello;
     
        
    @GetMapping("/hello")
    public void hello () {
        singletonHello.send();
    }
}

在网页中输入:http://localhost:8080/rabbit/hello;控制台输出如下所示:

wan :wan :*****hello rabbit****
*****SingletonHelloReceiver*****wan :*****hello rabbit****

三.SpringBoot整合RabbitMQ(topic模式)

任何发送到Topic Exchange的消息都会被转发到RouteKey中匹配到的Queue上。
1.所有的队列(queue)都有一个标签,所有的消息也都带有一个标签(RouteKey),Exchange会将消息转发到与它相匹配的队列(queue)中,这里的匹配是模糊匹配。
3.这种模式需要RouteKey,且需要提前绑定Exchange和Queue。
4如果Exchange没有发现能够与RouteKey匹配的Queue,则会抛弃此消息。
5.“#”表示0个或若干个关键字,“*”表示一个关键字。


image.png

在启动类里添加如下代码,首先会Exchange和队列(queue)匹配,如消息发送者amqpTemplate.convertAndSend("exchange","topic.A", topicA),topic.A可以匹配到两个queue,一个是bindingtopicMessageA,另一个是bindingtopicMessageB。因为topic.A可以匹配到topic.A和topic.#。

//===============以下是验证topic Exchange的队列==========
    @Bean
    public Queue topicMessageA() {
        return new Queue("topic.A");
    }
    
    @Bean
    public Queue topicMessageB() {
        return new Queue("topic.B");
    }
    
    @Bean
    TopicExchange exchange() {
        return new TopicExchange("exchange");
    }
    
    @Bean
    Binding bindingtopicMessageA(Queue topicMessageA,TopicExchange exchange) {
        return BindingBuilder.bind(topicMessageA).to(exchange).with("topic.A");
    }
    
    @Bean
    Binding bindingtopicMessageB(Queue topicMessageB,TopicExchange exchange) {
        return BindingBuilder.bind(topicMessageB).to(exchange).with("topic.#");//*表示一个词,#表示零个或多个词
    }

在topic文件夹下穿件topicsend类来发送消息,代码如下:

package SpringBoot.rabbitMq.rabbtt.topic;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class TopicSend {
    private static final Logger LOGGER = LoggerFactory.getLogger(TopicSend.class);
    
    @Autowired
    private AmqpTemplate amqpTemplate;
    
    public void send() {
        String topicA = "*******yangnima******";
        LOGGER.info(topicA);
        amqpTemplate.convertAndSend("exchange","topic.A", topicA);
        
        String topicB = "******wanguniang*****";
        LOGGER.info(topicB);
        amqpTemplate.convertAndSend("exchange","topic.B", topicB);
    }

}

在topic文件下创建两个接收类TopicReceiverA 和TopicReceiverB去接收TopicSend的消息,TopicReceiverB代码如下:

package SpringBoot.rabbitMq.rabbtt.topic;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
@RabbitListener(queues = "topic.B")
public class TopicReceiverB {
    private static final Logger LOGGER = LoggerFactory.getLogger(TopicReceiverB.class);
    
    @RabbitHandler
    public void receiver(String topicB) {
        LOGGER.info("*****TopicReceiverB*****"+topicB);
    }

}

TopicReceiverA代码如下:

package SpringBoot.rabbitMq.rabbtt.topic;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
@RabbitListener(queues = "topic.A")
public class TopicReceiverA {
    private static final Logger LOGGER = LoggerFactory.getLogger(TopicReceiverA.class);
    
    @RabbitHandler
    public void receiver(String topicA) {
        LOGGER.info("*****TopicReceiverA*****" + topicA);
    }

}

在RabbitTestController类中添加如下代码,


@Autowired
private TopicSend topicSend;

@GetMapping("/topic")
    public void testTopic() {
        topicSend.send();
    }

验证,访问http://localhost:8080/rabbit/topic控制台输出:

*******yangnima******
******wanguniang*****
*****TopicReceiverB************yangnima******
*****TopicReceiverA************yangnima******
*****TopicReceiverB***********wanguniang*****

三.SpringBoot整合RabbitMQ(Fanout模式)

任何发送到Fanout Exchange上的消息都会转发到与Exchange绑定(binding)的queue上。
1.可以理解为路由表的模式
2.这种模式不需要RouteKey
3.这种模式需要提前将Exchange与Queue进行绑定,一个Exchange可以绑定多个Queue,一个Queue可以同多个Exchange进行绑定。
4.如果接受到消息的Exchange没有与任何Queue绑定,则消息会被抛弃。


image.png

在启动类RabbttApplication中添加如下代码:

//===============以下是验证Fanout Exchange的队列==========
    @Bean
    public Queue fanoutMessageA() {
        return new Queue("fanout.A");
    }

    @Bean
    public Queue fanoutMessageB() {
        return new Queue("fanout.B");
    }

    @Bean
    public Queue fanoutMessageC() {
        return new Queue("fanout.C");
    }
    
    @Bean
    FanoutExchange fanoutExchange() {
        return new FanoutExchange("fanoutExchange");
    }
    
 
    @Bean
    Binding bindingExchangeA(Queue fanoutMessageA,FanoutExchange fanoutExchange) {
        return BindingBuilder.bind(fanoutMessageA).to(fanoutExchange);
    }
    
    @Bean
    Binding bindingExchangeB(Queue fanoutMessageB,FanoutExchange fanoutExchange) {
        return BindingBuilder.bind(fanoutMessageB).to(fanoutExchange);
    }
    
    @Bean
    Binding bindingExchangeC(Queue fanoutMessageC,FanoutExchange fanoutExchange) {
        return BindingBuilder.bind(fanoutMessageC).to(fanoutExchange);
    }

在fanout文件夹下创建FanoutSender类去发送消息,代码如下:

package SpringBoot.rabbitMq.rabbtt.fanout;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class FanoutSender {
    
    private static final Logger LOGGER = LoggerFactory.getLogger(FanoutSender.class);
    
    @Autowired
    private AmqpTemplate amqpTemplate;
    
    public void send() {
        String msg = "*****hello yangnima!! *******";
        LOGGER.info("*****FanoutSender******" + msg);
        amqpTemplate.convertAndSend("fanoutExchange","", msg);
    }

}

在fanout下面创建三个消息接收类去接受消息,FanoutReceiverA、FanoutReceiverB、FanoutReceiverC,FanoutReceiverA类的代码如下:

package SpringBoot.rabbitMq.rabbtt.fanout;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
@RabbitListener(queues = "fanout.A")
public class FanoutReceiverA {
    
    private static final Logger LOGGER = LoggerFactory.getLogger(FanoutReceiverA.class);
    
    @RabbitHandler
    public void receiver(String msg) {
        LOGGER.info("*******FanoutReceiverA*******" + msg);
    }

}

FanoutReceiverB类的代码如下:

package SpringBoot.rabbitMq.rabbtt.fanout;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
@RabbitListener(queues = "fanout.B")
public class FanoutReceiverB {
    
    private static final Logger LOGGER = LoggerFactory.getLogger(FanoutReceiverB.class);
    
    @RabbitHandler
    public void receiver(String msg) {
        LOGGER.info("*******FanoutReceiverB*******" + msg);
    }

}

FanoutReceiverC类的代码如下:

package SpringBoot.rabbitMq.rabbtt.fanout;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
@RabbitListener(queues = "fanout.C")
public class FanoutReceiverC {
    
    private static final Logger LOGGER = LoggerFactory.getLogger(FanoutReceiverC.class);
    
    @RabbitHandler
    public void receiver(String msg) {
        LOGGER.info("*******FanoutReceiverC*******" + msg);
    }

}

在RabbitTestController类中添加如下代码,


@Autowired
private FanoutSender fanoutSender;

@GetMapping("/fanout")
    public void testFanout() {
        fanoutSender.send();
    }

验证,访问http://localhost:8080/rabbit/fanout,控制台输出如下:

*****FanoutSender***********hello yangnima!! *******
*******FanoutReceiverA************hello yangnima!! *******
*******FanoutReceiverC************hello yangnima!! *******
*****TopicReceiverB**********hello yangnima!! *******
*******FanoutReceiverB************hello yangnima!! *******
*****TopicReceiverA**********hello yangnima!! *******
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 215,634评论 6 497
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,951评论 3 391
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 161,427评论 0 351
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,770评论 1 290
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,835评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,799评论 1 294
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,768评论 3 416
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,544评论 0 271
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,979评论 1 308
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,271评论 2 331
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,427评论 1 345
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,121评论 5 340
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,756评论 3 324
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,375评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,579评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,410评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,315评论 2 352