RabbitMQ交换机

1.交换机的作用

(1)接收publisher发送消息

(2)将消息按照规则路由到与之绑定的队列

2.交换机类型

(1)Fanout(广播)

Fanout Exchange会将接受到的消息广播到每一个跟其绑定的queue,所以也叫广播模式

(2)Direct(定向)

Direct Exchange会将接收到的消息根据规则路由到指定的Queue,因此称为定向路由

  • 每一个Queue都与Exchange设置一个BindingKey
  • 发布者发送消息时,指定消息的RoutingKey
  • Exchange将消息路由到BindingKey与消息RoutingKey一直的Queue

(3)Topic(话题)

TopicExchange与DirectExchange类似,区别在于routingKey可以是多个单词的列表,并且以"."号分割,且Queue与Exchange指定BindingKey时可以使用通配符

  • " # ":代指0个或多个单词
  • " * ":代指一个单词

3.声明队列和交换机(一般在消费者中声明)

(1)定义一个配置类,使用SpringAMQP提供了几个类,用来声明队列,交换机及其绑定关系

java 复制代码
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class TopicConfiguration {
    //定义一个交换机
    @Bean
    public TopicExchange topicExchange() {
        return ExchangeBuilder.topicExchange("topic_Exchange").build();
    }

    //定义一个消息队列
    @Bean
    public Queue topicQueue() {
        return QueueBuilder.durable("topic_Queue").build();
    }

    //定义绑定关系
    @Bean
    public Binding topicBinding() {
        return BindingBuilder.bind(topicQueue()).to(topicExchange()).with("topic.queue.test");
    }
}

(2)使用SpringAMQP提供的@RabbitListener注解来声明队列和交换机

java 复制代码
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class RabbitListener {
    //使用注解定义交换机,消息队列,routingKey值
    @org.springframework.amqp.rabbit.annotation.RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "topic_Queue",durable = "true"),//设置队列
            exchange = @Exchange(name = "topic_Exchange",type = ExchangeTypes.TOPIC),//设置交换机
            key = {"topic.queue.test"}//设置routingKey值,多个routingKey值以数组的形式定义
            ))
    public void pay(String message) throws InterruptedException {
        System.out.println("支付模块处理的任务:"+message);
    }
相关推荐
一嘴一个橘子4 小时前
springmvc 全局异常处理【补充】
java
Wang's Blog4 小时前
Vibe Coding一人即团队系列35: 基于Claude Code的Spring Boot项目初始化实践
java·spring boot·后端
Dovis(誓平步青云)5 小时前
拍视频前先把镜头想清楚:做一个分镜取景辅助器
android·java·服务器·javascript·人工智能
AI人工智能+电脑小能手5 小时前
大白话说Java设计模式-45-解释器模式(源码剖析篇)
java·设计模式·解释器模式·源码分析·pattern·spel·javacc
吴声子夜歌5 小时前
Java——开发中通用的方法和准则(二)
java·开发语言·php
袁震5 小时前
HarmonyOS 应用包体积优化与上架自检实战:从 76.2MB 到 3.6MB
java·华为·性能优化·harmonyos
zcmodeltech5 小时前
反应装置模型控制系统设计与实现:多设备协同联动方案
java·网络·数据库·stm32·嵌入式硬件·能源·制造
码视野6 小时前
基于 Spring Boot + Vue3 的【城市地下燃气管网微泄漏感知与相邻地下空间燃爆预警中台】设计与实现(含PRD/三端高保真源码/大屏)
java·前端·人工智能·spring boot·后端
2601_962071576 小时前
数据库系统架构与DBMS功能探微:现代信息时代数据管理的关键
java·开发语言·数据库
梦想的旅途26 小时前
如何高效调用企业微信通讯录API管理组织架构
java·开发语言·企业微信