rabbitMq四种模式及同springboot简单整合

本文详细介绍了RabbitMQ的五种工作模式:简单模式、工作者模式、发布订阅模式、路由模式和主题模式,并提供了Java实现示例。此外,还展示了如何将RabbitMQ与SpringBoot进行整合,使用RabbitTemplate简化消息发送。
摘要由CSDN通过智能技术生成

1. 回顾

RabbitMQ由五种模式:
上篇:https://editor.csdn.net/md/?articleId=116211410
(1)简单模式:特点:只有生产者消费者和队列组成。

2. 工作者模式:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-oVm8xnhp-1619660455670)(assets\1618900602190.png)]

特点:
    1. 一个生产者
    2. 由多个消费。
    3. 统一个队列。
    4. 这些消费者之间存在竞争关系。

用处:
    比如批量处理上. rabbitMQ里面积压了大量的消息。 

生产者,这里设置的是自动确定模式,所以两个消费者消费的个数一样

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
public class Product {
    public static void main(String[] args)throws  Exception {
        //创建连接工厂 --配置连接信息
        ConnectionFactory factory=new ConnectionFactory();
        factory.setHost("192.168.31.195");
        //创建连接对象Connection
        Connection connection=factory.newConnection();
        //创建信道
        Channel channel = connection.createChannel();

        //创建队列
        /**
         * String queue, 队列的名称
         * boolean durable, 是否该队列持久化 rabbitMQ服务重启后该存放是否存在。
         * boolean exclusive, 是否独占 false
         * boolean autoDelete, 是否自动删除  如果长时间没有发生消息 则自动删除
         * Map<String, Object> arguments 额外参数  先给null
         */
        channel.queueDeclare("queue_work",true,false,false,null);
        //发生消息
        /**
         * String exchange: 交换机的名称 如果没有则使用“” 它回自动采用默认
         * String routingKey, 路由key  如果没有交换机的绑定 使用队列的名称
         * BasicProperties props, 消息的一些额外配置 目前先不加 null
         * byte[] body 消息的内容
         */
        for(int i=0;i<10;i++) {
            String msg = "冯昱凯真帅!!!!!!!!!!!"+i;
            channel.basicPublish("", "queue_work", null, msg.getBytes());
        }
        //生产者这里可以管理资源  消费者不能关闭资源。
        channel.close();
        connection.close();
    }
}

消费者01:

import com.rabbitmq.client.*;

import java.io.IOException;
public class Consumer01 {
    public static void main(String[] args) throws Exception{
        //创建连接工厂 --配置连接信息
        ConnectionFactory factory=new ConnectionFactory();
        factory.setHost("192.168.31.195");
        //创建连接对象Connection
        Connection connection=factory.newConnection();
        //创建信道
        Channel channel = connection.createChannel();

        //接受消息
        /**
         * (String queue, 队列的名称
         *  boolean autoAck, 是否自动确认
         *  Consumer callback: 回调方法 当队列中存在信息后 会自动触发回调函数。
         */
        DefaultConsumer callback=new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                //body 接受的信息
                try {
                    Thread.sleep(1000L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("消费者01:"+new String(body));
            }
        };
        channel.basicConsume("queue_work",true,callback);
    }
}

消费者02:

import com.rabbitmq.client.*;

import java.io.IOException;
public class Consumer02 {
    public static void main(String[] args) throws Exception{
        //创建连接工厂 --配置连接信息
        ConnectionFactory factory=new ConnectionFactory();
        factory.setHost("192.168.31.195");
        //创建连接对象Connection
        Connection connection=factory.newConnection();
        //创建信道
        Channel channel = connection.createChannel();

        //接受消息
        /**
         * (String queue, 队列的名称
         *  boolean autoAck, 是否自动确认
         *  Consumer callback: 回调方法 当队列中存在信息后 会自动触发回调函数。
         */
        DefaultConsumer callback=new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                //body 接受的信息
                try {
                    Thread.sleep(1000L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("消费者01:"+new String(body));
            }
        };
        channel.basicConsume("queue_work",true,callback);

    }
}

3. 发布订阅模式(广播模式)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-B7rKjukV-1619660455673)(assets\1618901774090.png)]

1. 特点:
    1.一个生产者
    2.多个消费者
    3.多个队列。(永远是队列中拿消息)
    4.交换机 转发消息。

生产者:

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
public class Product {
    public static void main(String[] args)throws  Exception {
        //创建连接工厂 --配置连接信息
        ConnectionFactory factory=new ConnectionFactory();
        factory.setHost("192.168.31.195");
        //创建连接对象Connection
        Connection connection=factory.newConnection();
        //创建信道
        Channel channel = connection.createChannel();

        //创建队列
        /**
         * String queue, 队列的名称
         * boolean durable, 是否该队列持久化 rabbitMQ服务重启后该存放是否存在。
         * boolean exclusive, 是否独占 false
         * boolean autoDelete, 是否自动删除  如果长时间没有发生消息 则自动删除
         * Map<String, Object> arguments 额外参数  先给null
         */
        channel.queueDeclare("ban129_queue_fanout01",true,false,false,null);
        channel.queueDeclare("ban129_queue_fanout02",true,false,false,null);

        //创建交换机
        /**
         * String exchange,交换机的名称
         * BuiltinExchangeType type, 交换机的类型
         * boolean durable:是否持久化
         */
        channel.exchangeDeclare("exchange", BuiltinExchangeType.FANOUT,true);
        /**
         * String queue,  队列名
         * String exchange, 交换机的名称
         * String routingKey:路由key 如果交换机为fanout模式则不需要路由key
         */
        channel.queueBind("queue_fanout01","exchange","");
        channel.queueBind("queue_fanout02","exchange","");
        //发生消息
        /**
         * String exchange: 交换机的名称 如果没有则使用“” 它回自动采用默认
         * String routingKey, 路由key  如果没有交换机的绑定 使用队列的名称
         * BasicProperties props, 消息的一些额外配置 目前先不加 null
         * byte[] body 消息的内容
         */
        for(int i=0;i<10;i++) {
            String msg = "真帅!!!!!!!!!!!"+i;
            channel.basicPublish("exchange", "", null, msg.getBytes());
        }
        //生产者这里可以管理资源  消费者不能关闭资源。
        channel.close();
        connection.close();
    }
}

消费者:

import com.rabbitmq.client.*;

import java.io.IOException;
public class Consumer01 {
    public static void main(String[] args) throws Exception{
        //创建连接工厂 --配置连接信息
        ConnectionFactory factory=new ConnectionFactory();
        factory.setHost("192.168.31.195");
        //创建连接对象Connection
        Connection connection=factory.newConnection();
        //创建信道
        Channel channel = connection.createChannel();

        //接受消息
        /**
         * (String queue, 队列的名称
         *  boolean autoAck, 是否自动确认
         *  Consumer callback: 回调方法 当队列中存在信息后 会自动触发回调函数。
         */
        DefaultConsumer callback=new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                //body 接受的信息
                try {
                    Thread.sleep(1000L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("消费者01:"+new String(body));
            }
        };
        channel.basicConsume("queue_fanout01",true,callback);

    }
}

注意: 同样名字的交换机但是交换机的类型不同(BuiltinExchangeType type, 交换机的类型),不能一起使用,否则在生产者或者消费端会报错!

还有routingkey如果没有赋值为“ ”,不可以将其设置为null;

4.路由模式

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-6hKQqGq0-1619660455674)(assets\1618904756029.png)]

特点:
    1.一个生产者
    2.多个消费者
    3.多个队列。
    4.交换机 转发消息。
    5.routekey:路由key 只要routekey匹配的消息可以到达对应队列。
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
public class Product {
    public static void main(String[] args)throws  Exception {
        //创建连接工厂 --配置连接信息
        ConnectionFactory factory=new ConnectionFactory();
        factory.setHost("192.168.31.195");
        //创建连接对象Connection
        Connection connection=factory.newConnection();
        //创建信道
        Channel channel = connection.createChannel();

        //创建队列
        /**
         * String queue, 队列的名称
         * boolean durable, 是否该队列持久化 rabbitMQ服务重启后该存放是否存在。
         * boolean exclusive, 是否独占 false
         * boolean autoDelete, 是否自动删除  如果长时间没有发生消息 则自动删除
         * Map<String, Object> arguments 额外参数  先给null
         */
        channel.queueDeclare("queue_direct01",true,false,false,null);
        channel.queueDeclare("queue_direct02",true,false,false,null);

        //创建交换机
        /**
         * String exchange,交换机的名称
         * BuiltinExchangeType type, 交换机的类型
         * boolean durable:是否持久化
         */
        channel.exchangeDeclare("exchange_direct", BuiltinExchangeType.DIRECT,true);
        /**
         * String queue,  队列名
         * String exchange, 交换机的名称
         * String routingKey:路由key 如果交换机为fanout模式则不需要路由key
         */
        channel.queueBind("queue_direct01","exchange_direct","error");


        channel.queueBind("queue_direct02","exchange_direct","info");
        channel.queueBind("queue_direct02","exchange_direct","error");
        channel.queueBind("queue_direct02","exchange_direct","warning");
        //发生消息
        /**
         * String exchange: 交换机的名称 如果没有则使用“” 它回自动采用默认
         * String routingKey, 路由key  如果没有交换机的绑定 使用队列的名称
         * BasicProperties props, 消息的一些额外配置 目前先不加 null
         * byte[] body 消息的内容
         */
        for(int i=0;i<10;i++) {
            String msg = "你们有没有打疫苗!!!!!!!!!!!"+i;
            channel.basicPublish("exchange_direct", "error", null, msg.getBytes());
        }
        //生产者这里可以管理资源  消费者不能关闭资源。
        channel.close();
        connection.close();
    }
}

5. topic主体模式

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-l0DWFwGt-1619660455676)(assets\1618905526157.png)]

1. 绑定按照通配符的模式。
     *: 统配一个单词。
     #: 统配n个单词
例子
hello.orange.rabbit  Q1和Q2都可接到消息

lazy.orange      Q2可接到消息

注意:这里的通配符内容不仅仅局限与图中所给的内容

生产者

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
public class Product {
    public static void main(String[] args)throws  Exception {
        //创建连接工厂 --配置连接信息
        ConnectionFactory factory=new ConnectionFactory();
        factory.setHost("192.168.31.195");
        //创建连接对象Connection
        Connection connection=factory.newConnection();
        //创建信道
        Channel channel = connection.createChannel();

        //创建队列
        /**
         * String queue, 队列的名称
         * boolean durable, 是否该队列持久化 rabbitMQ服务重启后该存放是否存在。
         * boolean exclusive, 是否独占 false
         * boolean autoDelete, 是否自动删除  如果长时间没有发生消息 则自动删除
         * Map<String, Object> arguments 额外参数  先给null
         */
        channel.queueDeclare("queue_topic01",true,false,false,null);
        channel.queueDeclare("queue_topic02",true,false,false,null);

        //创建交换机
        /**
         * String exchange,交换机的名称
         * BuiltinExchangeType type, 交换机的类型
         * boolean durable:是否持久化
         */
        channel.exchangeDeclare("exchange_topic", BuiltinExchangeType.TOPIC,true);
        /**
         * String queue,  队列名
         * String exchange, 交换机的名称
         * String routingKey:路由key 如果交换机为fanout模式则不需要路由key
         */
        channel.queueBind("queue_topic01","exchange_topic","*.orange.*");
       channel.queueBind("queue_topic02","exchange_topic","*.*.rabbit");
        channel.queueBind("queue_topic02","exchange_topic","lazy.#");

        //发生消息
        /**
         * String exchange: 交换机的名称 如果没有则使用“” 它回自动采用默认
         * String routingKey, 路由key  如果没有交换机的绑定 使用队列的名称
         * BasicProperties props, 消息的一些额外配置 目前先不加 null
         * byte[] body 消息的内容
         */
        for(int i=0;i<10;i++) {
            String msg = "你们!!!!!!!!!!!"+i;
            channel.basicPublish("exchange_topic", "lazy.orange.rabbit", null, msg.getBytes());
        }
        //生产者这里可以管理资源  消费者不能关闭资源。
        channel.close();
        connection.close();

    }
}

5. rabbitMQ整合springboot

springboot引入了相关的依赖后,提供一个工具类RabbitTemplate(模板).封装了上面生产者消费者的发送消息的整个代码流程,使用这个工具类可以发送消息。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-UyqTDFUe-1619660455677)(assets\1618910290294.png)]

(1)父工程引入相关的依赖

<?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>
    <packaging>pom</packaging>
    <modules>
        <module>product</module>
        <module>consumer</module>
    </modules>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.5</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.aaa</groupId>
    <artifactId>springboot-rabbit-parent</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-rabbit-parent</name>
    <description>springboot整合rabbitMQ</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <!--rabbitMQ的依赖: 启动类加载。读取配置文件:
           springboot自动装配原理: 引用starter启动依赖时,把对应的自动装配类加载进去,该自动装配类可以读取application配置文件中
           内容。 DispatherServlet
        -->
        <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>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.72</version>
        </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>
    </dependencies>

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

</project>

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-8Las4avK-1619660455678)(assets/1618921998878.png)]

(2)相应的生产者和消费的配置(文件名一定要是application的名字)

server:
  port: 9999
#rabbit的配置
spring:
  rabbitmq:
    host: 192.168.31.195

(3)生产者

import com.alibaba.fastjson.JSON;
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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
@RestController
public class HelloController {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @GetMapping("hello")
    public String hello(){ //业务层
        System.out.println("下单成功");
        //String exchange, String routingKey, Object message
        Map<String,Object> map=new HashMap<>();
        map.put("productId",1);
        map.put("num",10);
        map.put("price",12);
        rabbitTemplate.convertAndSend("exchange","", JSON.toJSONString(map)); //序列化过程
        return "下单成功";
    }
}

消费者监听消息

import com.alibaba.fastjson.JSON;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
@Component
public class MyRabbitListener {

    //队列中存在消息则立即回调该方法
    @RabbitListener(queues = {"queue_fanout01"})
    public void listener(String msg){//参数也可使用Message msg类型,里面包含各种消息类型和内容
        Map map = JSON.parseObject(msg, Map.class);
        System.out.println(map);
    }
  
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值