(直连&主题&扇形)交换机

目录

一、交换机简介

1. Exchange(交换机)的作用

2.Exchange(交换机)的类型

①.直连交换机:Direct Exchange

② 主题交换机:Topic Exchange

③ 扇形交换机:Fanout Exchange

④ 首部交换机:Headers Exchange

⑤ 默认交换机

3.交换机的属性

4.综合案例:交换机的使用

二、直连交换机的使用(Direct Exchange)

① 给子模块添加依赖 

② 给消费者添加连接配置

③ 创建类 RabbitmqDirectConfig

④ 创建 SendMessageController

⑤ 运行

⑥  创建消息接收监听类 DirectReceiver

⑦ 运行 

三、主题交换机(Topic Exchange)

① 创建类 RabbitTopicConfig

② 主题交换机发送消息方法 

③ 访问 

④ 消费者监听消息 

 三、扇形交互机(Fanout Exchange)


一、交换机简介

交换机是有6种的,我们只讲常见的3种 直连交换机、主题交换机、扇形交换机。

类似amq.的名称的交换机: 

1. Exchange(交换机)的作用

在RabbitMQ中,生产者发送消息不会直接将小计投递到队列中,而是先将消息投递到交换机中,在由交换机转发到具体的队列,队列再将消息以推送或者拉取方式给消费者进行消费

        创建消息              路由键         pull/push
   生产者------------>交换机------------>队列------------>消费者

生产者是把我们的消息投入到交换机,交换机跟队列是存在绑定关系的 

RabbitMQ交换机的作用: 

2.Exchange(交换机)的类型

①.直连交换机:Direct Exchange

直连交换机是一种带路由功能的交换机,一个队列会和一个交换机绑定,除此之外再绑定一个routing_key,当消息被发送的时候,需要指定一个bingding_key,这个消息被送达交换机的时候,就会被这个交换机送到指定的队列里面去。同样的一个binding_key也是支持应用到多个队列中的.

这样当一个交换机绑定多个队列,就会被送到对应的队列去处理。

     注1:什么是路由键 
          每个消息都有一个称为路由键(routing key)的属性,它其实就是一个简单的字符串

     注2:直连交换机适用场景
          有优先级的任务,根据任务的优先级把消息发送到对应的队列,这样可以指派更多的资源去处理高优先级的队列。

 直连交换机-单个绑定:

直连交换机-多个绑定: 

 

② 主题交换机:Topic Exchange

     直连交换机的缺点!
     直连交换机的routing_key方案非常简单,如果我们希望一条消息发送给多个队列,那么这个交换机需要绑定上非常多的routing_key,
     假设每个交换机上都绑定一堆的routing_key连接到各个队列上。那么消息的管理就会异常地困难。
     
     所以RabbitMQ提供了一种主题交换机,发送到主题交换机上的消息需要携带指定规则的routing_key,
     主题交换机会根据这个规则将数据发送到对应的(多个)队列上。

     主题交换机的routing_key需要有一定的规则,交换机和队列的binding_key需要采用*.#.*.....的格式,每个部分用.分开,其中
     *表示一个单词 
     #表示任意数量(零个或多个)单词。

 示例:
     队列Q1绑定键为 *.TT.*
     队列Q2绑定键为TT.#

     如果一条消息携带的路由键为 A.TT.B,那么队列Q1将会收到 
     如果一条消息携带的路由键为TT.AA.BB,那么队列Q2将会收到

③ 扇形交换机:Fanout Exchange

扇形交换机是最基本的交换机类型,它所能做的事情非常简单————广播消息。

扇形交换机会把能接收到的消息全部发送给绑定在自己身上的队列。因为广播不需要"思考",所以扇形交换机处理消息的速度也是所有的交换机类型里面最快的。

这个交换机没有路由键概念,就算你绑了路由键也是无视的。

④ 首部交换机:Headers Exchange

⑤ 默认交换机

        实际上是一个由RabbitMQ预先声明好的名字为空字符串的直连交换机(direct exchange)。它有一个特殊的属性使得它对于
     简单应用特别有用处:那就是每个新建队列(queue)都会自动绑定到默认交换机上,绑定的路由键(routing key)名称与队列名称相同。

     如:当你声明了一个名为”hello”的队列,RabbitMQ会自动将其绑定到默认交换机上,绑定(binding)的路由键名称也是为”hello”。
     因此,当携带着名为”hello”的路由键的消息被发送到默认交换机的时候,此消息会被默认交换机路由至名为”hello”的队列中
  
     类似amq.*的名称的交换机:
     这些是RabbitMQ默认创建的交换机。这些队列名称被预留做RabbitMQ内部使用,不能被应用使用,否则抛出403 (ACCESS_REFUSED)错误 

   6.Dead Letter Exchange(死信交换机)
     在默认情况,如果消息在投递到交换机时,交换机发现此消息没有匹配的队列,则这个消息将被悄悄丢弃。
     为了解决这个问题,RabbitMQ中有一种交换机叫死信交换机。当消费者不能处理接收到的消息时,将这个消息重新发布到另外一个队列中,
     等待重试或者人工干预。这个过程中的exchange和queue就是所谓的”Dead Letter Exchange 和 Queue

3.交换机的属性

除交换机类型外,在声明交换机时还可以附带许多其他的属性,其中最重要的几个分别是:
   Name:交换机名称
   Durability:是否持久化。如果持久性,则RabbitMQ重启后,交换机还存在
   Auto-delete:当所有与之绑定的消息队列都完成了对此交换机的使用后,删掉它
   Arguments:扩展参数

4.综合案例:交换机的使用

注意:当我们新建的项目时,注意要配置一下maven,它默认的是在C盘。 

     rabbitmq02                     #主模块        maven项目
     rabbitmq-provider            #生产者        springboot项目
     rabbitmq-consumer            #消费者        springboot项目

主模块: 

生产者:

消费者:

二、直连交换机的使用(Direct Exchange)

打开我们的虚拟机--->连接虚拟机连接工具

由于我们执行了开机自启动。打开浏览器访问:192.168.29.128:15672 进行登录。

① 给子模块添加依赖 

 pom.xml  生产者和消费者

<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.projectlombok</groupId>
       <artifactId>lombok</artifactId>
       <optional>true</optional>
     </dependency>

② 给消费者添加连接配置

server.port=8080
## rabbitmq config
spring.rabbitmq.host=192.168.29.128
spring.rabbitmq.port=5672
spring.rabbitmq.username=jwj
spring.rabbitmq.password=123456

## 与启动容器时虚拟主机名字一致~~~与启动容器时虚拟主机名字一致~~~与启动容器时虚拟主机名字一致~~~
spring.rabbitmq.virtual-host=my_vhost

③ 创建类 RabbitmqDirectConfig

package com.jwj.rabbitmqprovider.config;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


/**
 * @author 敢敢
 * @site www.javajwj.com
 * @company xxx公司
 * @create  2022-12-16 21:02
 *
 * 由于它是配置类所以我们要添加 @configuration
 */
@Configuration
public class RabbitmqDirectConfig {
//    直连交换机对应的队列
    @Bean
    public Queue directQueue(){
        return new Queue("jwj-direct-Queue");
    }

//    直连交换机
    @Bean
    public DirectExchange directExchange(){
        return new DirectExchange("jwj-direct-Exchange");
    }

//    直连交换机与队列的绑定关系
    @Bean
    public Binding directBinding(){
        return BindingBuilder.bind(directQueue())
                .to(directExchange())
                .with("direct_routing_key");
    }
}

④ 创建 SendMessageController

关键代码:rabbitTemplate.convertAndSend("testDirectExchange", "testDirectRouting", map);
                   sendDirectMessage:进行消息推送(也可以改为定时任务,具体看需求)

package com.jwj.rabbitmqprovider.controller;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 敢敢
 * @site www.javajwj.com
 * @company xxx公司
 * @create  2022-12-16 21:47
 */
@RestController
public class SendMessageController {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @RequestMapping("/sendDirect")
    public Map sendDirect(String routingKey){
        Map msg=new HashMap();
        msg.put("msg","直连交换机 jwj-direct-Exchange 发送的消息");
        msg.put("time", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd hh-mm-ss")));

        rabbitTemplate.convertAndSend("jwj-direct-Exchange",
                routingKey,
                msg);

        Map res=new HashMap();
        res.put("code",200);
        res.put("msg","成功");
        return res;

    }
}

⑤ 运行

运行:

 如果一点没有对上就会没有。

⑥  创建消息接收监听类 DirectReceiver

 3.查看rabbitmq管理界面
       我们目前还创建消费者rabbitmq-consumer,消息没有被消费的,我们去rabbitMq管理页面看看,是否推送成功 
       Overview选项卡,可以查看到刚刚创建的消息

package com.jwj.rabbitmqconsumer.config;

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

import java.util.Map;

@Component
		@RabbitListener(queues = {"jwj-direct-Queue"})
		public class DirectReceiver {
			// @RabbitListener(queues = {"direct-queue"})
			@RabbitHandler
			public void handler(Map msg){
				System.out.println(msg);
			}
		}
server.port=8081
spring.rabbitmq.host=192.168.29.128
spring.rabbitmq.port=5672
spring.rabbitmq.username=jwj
spring.rabbitmq.password=123456
## 与启动容器时虚拟主机名字一致~~~与启动容器时虚拟主机名字一致~~~与启动容器时虚拟主机名字一致~~~
spring.rabbitmq.virtual-host=my_vhost

 注1:新版jdk日期及格式化
          LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

     注2:rabbitTemplate和amqpTemplate有什么关系
          查看源码中会发现rabbitTemplate实现自amqpTemplate接口,两者使用起来并无区别,功能一致

     注3:不要@Configuration写成了@Configurable,这两个长得很像
          @Configuration该注解是可以用来替代XML文件。
          手动new出来的对象,正常情况下,Spring是无法依赖注入的,这个时候可以使用@Configurable注解

⑦ 运行 

三、主题交换机(Topic Exchange)

① 创建类 RabbitTopicConfig

package com.jwj.rabbitmqprovider.config;

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

/**
 * @author 敢敢
 * @site www.javajwj.com
 * @company xxx公司
 * @create  2022-12-16 22:28
 */
@Configuration
public class RabbitTopicConfig {
//    队列
    @Bean
    public Queue topicQueueA(){
    return new Queue("jwj-topic-Queue-a");
}

    @Bean
    public Queue topicQueueB(){
        return new Queue("jwj-topic-Queue-b");
    }

    @Bean
    public Queue topicQueueC(){
        return new Queue("jwj-topic-Queue-c");
    }

//    交换机
    @Bean
    public TopicExchange topicExchange(){
        return new TopicExchange("jwj-topic-Queue");
    }

//    绑定关系
    @Bean
    public Binding binding1(){
        return BindingBuilder.bind(topicQueueA())
                .to(topicExchange())
                .with("jwj.person.xx");
    }

    @Bean
    public Binding binding2(){
        return BindingBuilder.bind(topicQueueB())
                .to(topicExchange())
                .with("jwj.person.yy");
    }

    @Bean
    public Binding binding3(){
        return BindingBuilder.bind(topicQueueC())
                .to(topicExchange())
                .with("jwj.person.*");
    }

}

② 主题交换机发送消息方法 

@RequestMapping("/sendTopic")
    public Map sendTopic(String routingKey){
        Map msg=new HashMap();
        msg.put("msg","主题交换机 jwj-topic-Exchange 发送的消息");
        msg.put("time", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd hh-mm-ss")));

        rabbitTemplate.convertAndSend("jwj-topic-Exchange",
                routingKey,
                msg);

        Map res=new HashMap();
        res.put("code",200);
        res.put("msg","成功");
        return res;

    }

③ 访问 

 哪怕我们第一次访问写的不对,但它的队列也要给我们生产出来来。

 

④ 消费者监听消息 

 TopicReceiver

package com.jwj.rabbitmqconsumer.config;

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

import java.util.Map;

/**
 * @author 敢敢
 * @site www.javajwj.com
 * @company xxx公司
 * @create  2022-12-16 22:58
 */
@Component
public class TopicReceiver {
     @RabbitListener(queues = {"jwj-topic-Queue-a"})
    @RabbitHandler
    public void handler1(Map msg){
        System.out.println("消费者订阅jwj-topic-Queue-a队列的消息为:"+msg);
    }

    @RabbitListener(queues = {"jwj-topic-Queue-b"})
    @RabbitHandler
    public void handler2(Map msg){
        System.out.println("消费者订阅jwj-topic-Queue-b队列的消息为:"+msg);
    }

    @RabbitListener(queues = {"jwj-topic-Queue-c"})
    @RabbitHandler
    public void handler(Map msg){
        System.out.println("消费者订阅jwj-topic-Queue-c队列的消息为:"+msg);
    }
}

 三、扇形交互机(Fanout Exchange)

RabbitmqFanoutConfig

package com.jwj.rabbitmqprovider.config;

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

/**
 * @author 敢敢
 * @site www.javajwj.com
 * @company xxx公司
 * @create  2022-12-17 0:59
 */
@Configuration
public class RabbitmqFanoutConfig {

        //    队列
        @Bean
        public Queue fanoutQueueA(){
            return new Queue("jwj-fanout-Queue-a");
        }

        @Bean
        public Queue fanoutQueueB(){
            return new Queue("jwj-fanout-Queue-b");
        }

        @Bean
        public Queue fanoutQueueC(){
            return new Queue("jwj-fanout-Queue-c");
        }

        //    交换机
        @Bean
        public FanoutExchange fanoutExchange(){
            return new FanoutExchange("jwj-fanout-Queue");
        }

        //    绑定关系
        @Bean
        public Binding bindingFanout1(){
            return BindingBuilder.bind(fanoutQueueA())
                    .to(fanoutExchange());
        }

        @Bean
        public Binding bindingFanout2(){
            return BindingBuilder.bind(fanoutQueueB())
                    .to(fanoutExchange());
        }

        @Bean
        public Binding bindingFanout3(){
            return BindingBuilder.bind(fanoutQueueC())
                    .to(fanoutExchange());
        }


}

 //因为是扇型交换机, 路由键无需配置,配置也不起作用,两处地方均未配置路由键
     BindingBuilder.bind(queueA()).to(fanoutExchange()); 
     rabbitTemplate.convertAndSend(RabbitFanoutConfig.EXCHANGE_NAME,null, map);

FanoutReceiver

package com.jwj.rabbitmqconsumer.config;

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

import java.util.Map;

/**
 * @author 敢敢
 * @site www.javajwj.com
 * @company xxx公司
 * @create  2022-12-16 22:58
 */
@Component
public class FanoutReceiver {
     @RabbitListener(queues = {"jwj-fanout-Queue-a"})
    @RabbitHandler
    public void handler1(Map msg){
        System.out.println("消费者订阅jwj-fanout-Queue-a队列的消息为:"+msg);
    }

    @RabbitListener(queues = {"jwj-fanout-Queue-b"})
    @RabbitHandler
    public void handler2(Map msg){
        System.out.println("消费者订阅jwj-fanout-Queue-b队列的消息为:"+msg);
    }

    @RabbitListener(queues = {"jwj-fanout-Queue-c"})
    @RabbitHandler
    public void handler(Map msg){
        System.out.println("消费者订阅jwj-fanout-Queue-c队列的消息为:"+msg);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值