Spring Boot整合RabbitMq

1.整合Spring boot

1.1添加依赖

Spring Boot为AMQP提供了自动化配置spring-boot-starter-amqp,因此首先创建Spring boot项目并添加依赖

<?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.5.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>11</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-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.amqp</groupId>
            <artifactId>spring-rabbit-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

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

</project>

1.2添加application.properties的配置

spring.rabbitmq.host=192.168.248.128
spring.rabbitmq.port=5672
spring.rabbitmq.username=yuminghuai
spring.rabbitmq.password=123456789

这里的话是默认的RabbitMq端口,还有就是我当初设置的用户名和密码,如果这里有疑问的可以查看我上一章节写的关于RabbitMQ的文章,应该对你会有所帮助
接下来就是对RabbitMQ进行配置了,在RabbitMQ当中,所有的消息生产者提交的信息都会交给Exchange进行再分配,Exchange有四种分配策略,下面我来依依介绍一下

1.3Direct

DirectExchange的路由策略是将消息队列绑定到一个DirectExchange上,当一条消息到达DirectExchange时会被转发到与该条消息routing key相同的Queue上,例如消息队列名为“hello-queue”,则routingkey为“hello-queue”的消息会被该消息队列接收。DirectExchange的配置如下:

package com.example.demo;

import com.rabbitmq.client.AMQP;
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import java.util.Collection;
import java.util.Iterator;
@ComponentScan("com.example.demo")
@Configuration
public class RabbitDirectConfig {
    public final static String DIRECTANAME="yuminghuai-direct";
   @Bean
    Queue queue(){
       return new Queue("hello-queue");
   }
    @Bean
    DirectExchange directExchange(){
        return new DirectExchange(DIRECTANAME,true,false);
    }
    @Bean
    Binding binding(){
        return BindingBuilder.bind(queue()).to(directExchange()).with("direct");

    }

}

代码解释:

• 首先提供一个消息队列Queue,然后创建一个DirectExchange对象,三个参数分别是名字、重启后是否依然有效以及长期未用时是否删除。
• 创建一个Binding对象,将Exchange和Queue绑定在一起。
• DirectExchange和Binding两个Bean的配置可以省略掉,即如果使用DirectExchange,只配置一个Queue的实例即可。

接下来配置一个消费者,代码如下:

package com.example.demo;

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

@Component
public class DirectReceiver {
    @RabbitListener(queues = "hello-queue")
    public void handler1(String msg){
        System.out.println("DirectReceiver:"+msg);
    }
}

通过@RabbitListener注解指定一个方法是一个消息消费方法,方法参数就是所接收到的消息。然后在单元测试类中注入一个RabbitTemplate对象来进行消息发送,代码如下:

package com.example.demo;

import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@ComponentScan("com.example.demo")
@SpringBootTest
class DemoApplicationTests {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Test
    void directTest(){
        rabbitTemplate.convertAndSend("hello-queue","hello direct!");
    }

}

确认RabbitMQ已经启动,然后启动Spring Boot项目,启动成功后,运行该单元测试方法,在Spring Boot控制台打印日志
在这里插入图片描述

1.4Fanout

FanoutExchange的数据交换策略是把所有到达FanoutExchange的消息转发给所有与它绑定的Queue,在这种策略中,routingkey将不起任何作用,FanoutExchange的配置方式如下:

package com.example.demo;

import com.rabbitmq.client.AMQP;
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import java.util.Collection;
import java.util.Iterator;
@ComponentScan("com.example.demo")
@Configuration
public class RabbitFanoutConfig {
    public final static String FANOUTNAME="sang-fanout";
   @Bean
    Queue queueOne(){
       return new Queue("queue-one");
   }
   @Bean
    Queue queueTwo(){
       return  new Queue("queue-two");
   }
    @Bean
    FanoutExchange fanoutExchange(){
       return new FanoutExchange(FANOUTNAME,true,false);
    }
    @Bean
    Binding bindingOne(){
        return BindingBuilder.bind(queueOne()).to(fanoutExchange());

    }
    @Bean
    Binding bindingTwo(){
       return  BindingBuilder.bind(queueTwo()).to(fanoutExchange());
    }

}

在这里首先创建FanoutExchange,参数的含义与创
建DirectExchange参数的含义一致,然后创建两个Queue,再将这两个Queue都绑定到FanoutExchange上。接下来创建两个消费者,代码如下:

package com.example.demo;

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

@Component
public class FanoutReceiver {
    @RabbitListener(queues = "queue-one")
    public void handler1(String message){
        System.out.println("FanoutReceiver:handlerl:"+message);
    }
    @RabbitListener(queues = "queue-two")
    public void handler2(String message){
        System.out.println("FanoutReceiver:handler2:"+message);
    }
}

两个消费者分别消费两个消息队列中的消息,然后在单元测试中发送消息,代码如下:

package com.example.demo;

import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@ComponentScan("com.example.demo")
@SpringBootTest
class DemoApplicationTests {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Test
    void directTest(){
        rabbitTemplate.convertAndSend(RabbitFanoutConfig.FANOUTNAME,null,"hello fanout!");
    }

}

注意,这里发送消息时不需要routingkey,指定exchange即可,routingkey可以直接传一个null。
确认RabbitMQ已经启动,然后启动Spring Boot项目,启动成功后,执行单元测试方法,控制台打印日志如图12-8所示。
在这里插入图片描述
在这里插入图片描述

图12-8
可以看到,一条消息发送出去之后,所有和该FanoutExchange绑定的Queue都收到了消息。

1.5Topic

TopicExchange是比较复杂也比较灵活的一种路由策略,在TopicExchange中,Queue通过routingkey绑定到TopicExchange上,当消息到达TopicExchange后,TopicExchange根据消息的routingkey将消息路由到一个或者多个Queue上。TopicExchange配置如下:

package com.example.demo;

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@ComponentScan("com.example.demo")
@Configuration
public class RabbitTopicConfig {
    public final static String TOPICNAME="sang-fanout";
   @Bean
    Queue xiaomi(){
       return new Queue("xiaomi");
   }
   @Bean
    Queue huaiwei(){
       return  new Queue("huaiwei");
   }
   @Bean
    Queue phone(){
       return new Queue("phone");
   }
    @Bean
    TopicExchange topicExchange(){
       return new TopicExchange(TOPICNAME,true,false);
    }
    @Bean
    Binding xiaomiBinding(){
        return BindingBuilder.bind(xiaomi()).to(topicExchange()).with("xiaomi.#");

    }
    @Bean
    Binding huaweiBinding(){
       return  BindingBuilder.bind(huaiwei()).to(topicExchange()).with("huaiwo.#");
    }
    @Bean
    Binding phoneBinding(){
        return  BindingBuilder.bind(phone()).to(topicExchange()).with("#.phone.#");
    }

}

代码解释:

• 首先创建TopicExchange,参数和前面的一致。然后创建三个Queue,第一个Queue用来存储和“xiaomi”有关的消息,第二个Queue用来存储和“huawei”有关的消息,第三个Queue用来存储和“phone”有关的消息。
• 将三个Queue分别绑定到TopicExchange上,第一个Binding中的“xiaomi.#”表示消息的routingkey凡是以“xiaomi”开头的,都将被路由到名称为“xiaomi”的Queue上;第二个Binding中的“huawei.#”表示消息的routingkey凡是以“huawei”开头的,都将被路由到名称为“huawei”的Queue上;第三个Binding中的“#.phone.#”则表示消息的routingkey中凡是包含“phone”的,都将被路由到名称为“phone”的Queue上。

接下来针对三个Queue创建三个消费者,代码如下:

package com.example.demo;

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

@Component
public class FanoutReceiver {
    @RabbitListener(queues = "phone")
    public void handler1(String message){
        System.out.println("PhoneReceiver:"+message);
    }
    @RabbitListener(queues = "xiaomi")
    public void handler2(String message){
        System.out.println("xiaomiReceiver:"+message);
    }
    @RabbitListener(queues="huawei")
    public void handler3(String message){
        System.out.println("Huaiwei:"+message);
    }
}

然后在单元测试中进行消息的发送,代码如下:
在这里插入图片描述

根据RabbitTopicConfig中的配置,第一条消息将被路由到名称为“xiaomi”的Queue上,第二条消息将被路由到名为“huawei”的Queue上,第三条消息将被路由到名为“xiaomi”以及名为“phone”的Queue上,第四条消息将被路由到名为“huawei”以及名为“phone”的Queue上,最后一条消息则将被路由到名为“phone”的Queue上。
确认RabbitMQ已经启动,然后启动Spring Boot项目,启动成功后,运行单元测试方法,控制台打印日志如图12-9、图12-10所示。

在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值