rabbitmq使用springboot实现fanout模式

一、fanout模式

  • 类型:fanout
  • 特点:Fanout—发布与订阅模式,是一种广播机制,它是没有路由key的模式。

 二、实现

1、引入相应的pom文件 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 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.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.xpf</groupId>
    <artifactId>rabbitmq-springboot</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>rabbitmq-springboot</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>8</java.version>
    </properties>
    <dependencies>
        <!--rabbitmq依赖-->
        <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>
        <dependency>
            <groupId>org.springframework.amqp</groupId>
            <artifactId>spring-rabbit-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter</artifactId>
            <version>RELEASE</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>

            <scope>test</scope>
        </dependency>
    </dependencies>


</project>

2、配置文件 application.properties

server.port=8080
spring.rabbitmq.username=admin
spring.rabbitmq.password=admin
spring.rabbitmq.virtual-host=/
spring.rabbitmq.host=192.168.199.20
spring.rabbitmq.port=5672

3、使用springboot写一个配置文件 RabbitMqConfiguration.java

(当然此配置类就是用来声明交换机类型以及交换机队列绑定关系的,将此配置类放在生产者中,或者放在消费者中都可以,或者两边都放。不管是生产者还是消费者,当生产者发送消息(或者消费者监听队列时),如果发现rabbitmq中没有所发送的交换机(或者监听的队列),都会根据此配置类自动创建交换机和队列以及绑定关系。但是一般建议下,放在消费者会更好一些,因为一般消费者在springboot系统启动时,就会开启监听,如果没有相应的rabbitmq连接有问题能在项目启动时就发现)

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;

@Configuration
public class RabbitMqConfiguration {

    //1、声明注册fanout模式交换机 (生产者发送消息给rabbitmq,其实就是发送到交换机)
    @Bean
    public FanoutExchange fanoutExchange(){
        return new FanoutExchange("fanout_order_exchange", true, false);
    }

    //2、声明队列 sms.fanout.queue、email.fanout.queue、duanxin.fanout.queue
    @Bean
    public Queue smsQueue(){
        return new Queue("sms.fanout.queue", true);
    }

    @Bean
    public Queue emailQueue(){
        return new Queue("email.fanout.queue", true);
    }

    @Bean
    public Queue duanxinQueue(){
        return new Queue("duanxin.fanout.queue", true);
    }

    //3、完成绑定关系(队列绑定交换机)
    @Bean
    public Binding smsBinding(){
        return BindingBuilder.bind(smsQueue()).to(fanoutExchange());
    }

    @Bean
    public Binding emailBinding(){
        return BindingBuilder.bind(emailQueue()).to(fanoutExchange());
    }

    @Bean
    public Binding duanxinBinding(){
        return BindingBuilder.bind(duanxinQueue()).to(fanoutExchange());
    }
}

4、写一个生产者 FanoutOrderService.java

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
public class FanoutOrderService {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 模拟用户下单,发送消息给下游系统
     * @param user
     * @param num
     */
    public void makerOrder(String user,  int num){
        //1、查询库存是否有剩余
        //2、保存订单
        String orderId = UUID.randomUUID().toString();
        System.out.println("订单生产成功:" + orderId);
        //3、通过mq给下游系统发送消息(交换机的名字千万别写错,和上述配置类应相同)
        String exchangeName = "fanout_order_exchange";
        String routingkey = "";
        rabbitTemplate.convertAndSend(exchangeName, routingkey, orderId);
        System.out.println("完成");
    }
}

5、到这一步就可以再写一个测试类来测试生产者发送消息

import com.xpf.rabbitmqspringboot.service.DirectOrderService;
import com.xpf.rabbitmqspringboot.service.FanoutOrderService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class RabbitmqSpringbootApplicationTests {

    @Autowired
    private FanoutOrderService fanoutOrderService;

    @Autowired
    private DirectOrderService directOrderService;

    /**
     * Fanout模式生成者发送消息
     */
    @Test
    void setFanoutOrderService() {
        fanoutOrderService.makerOrder("用户1", 10);
    }
}

发送完消息可以检查rabbitmq是否生成新交换机fanout_order_exchange和三个队列sms.fanout.queue、email.fanout.queue、duanxin.fanout.queue,以及是否有在三个队列看到一条刚刚发送的消息(因为是Fanout—发布与订阅模式,是一种没有路由key的广播机制,所有队列都能收到消息)

6、写一个消费者。(可以另启一个springboot项目,模拟另外的系统来消费我们发送的消息,也可像我一样在原项目编写,自己消费)

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

/**
 * @Author xpf
 * @Date 2023/7/9 0:44
 * @Version 1.0
 * Fanout—发布与订阅模式消费者(广播机制)
 */
@Component
@RabbitListener(queues = "sms.fanout.queue")
public class smsFanoutConsumer {

    @RabbitHandler
    public void receiveMessage(String message){
        System.out.println("接收到来自队列sms.fanout.queue消息订单的message是:" + message);
    }
}

这里写了一个监听sms发送消息的消费者,剩下两个email和duanxin类似。

特别注意:如果生成者发送的消息是什么类型,消费者接收时,

public void receiveMessage(String message)方法中的参数应该也是相同的类型,否则会报错。比如这里的string类型,因为生产者发送的也是sting类型

直接启动会发现sms.fanout.queue队列中的消息被消费掉了

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot使用RabbitMQFanout模式,需要在项目的配置文件中添加RabbitMQ的相关配置信息。根据提供的引用内容,可以看到有三个配置文件中都包含了RabbitMQ的配置信息,分别是server: port: 10002的配置文件\[1\],application.properties的配置文件\[2\],以及server: port: 10001的配置文件\[3\]。 你可以根据自己的需求选择其中一个配置文件进行配置。在配置文件中,需要设置RabbitMQ的主机地址、端口号、虚拟主机、用户名和密码等信息。根据提供的引用内容,可以得到以下配置信息: RabbitMQ主机地址:127.0.0.1 RabbitMQ端口号:5672 虚拟主机:/ 用户名:admin 密码:admin 你可以将这些配置信息添加到你选择的配置文件中,确保配置信息正确无误。这样就完成了Spring Boot使用RabbitMQFanout模式的配置。 #### 引用[.reference_title] - *1* *3* [Spring Boot整合RabbitMQ之发布与订阅模式fanout)](https://blog.csdn.net/cssweb_sh/article/details/125194004)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down1,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [RabbitMQSpringBoot+RabbitMQ的简单实现Fanout模式](https://blog.csdn.net/qq_29229567/article/details/86510358)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值