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);
    }
相关推荐
乌暮1 分钟前
从 `println` 到生产级日志:Spring Boot 日志体系完全指南
java·开发语言·jvm·spring boot·后端·学习·面试
脉动数据行情12 分钟前
Java OkHttp 对接国际期货批量行情 SpringBoot 定时落库实践
java·spring boot·okhttp
Wang's Blog19 分钟前
Java 项目实战: 交友项目 - 百度人脸识别:介绍
java·开发语言·交友
一枕槐安4871 小时前
大模型应用后端设计:上下文管理、缓存、降级策略的工程方案总结
java·spring·缓存
T_Apollo1 小时前
2.9 Java 25 版本新增特性和类
java
步行cgn1 小时前
@RequestMapping 注解详解
java·后端·spring
鶴哥只手遮天1 小时前
Spring Boot 4.1.1 深度源码解析-第 15 章 · 条件注解体系:全部 `@ConditionalOnXxx` 的实现原理
java·后端·开源
鶴哥只手遮天1 小时前
Spring Boot 4.1.1 深度源码解析-第 30 章 · 基础设施能力:SSL Bundle、Task 与虚拟线程、Retry
java·后端·开源
IT研究室1 小时前
最新计算机毕业设计选题推荐-基于微信小程序的汉服交易系统-网站-文档指导-Java-springboot
java·微信小程序·课程设计
鶴哥只手遮天1 小时前
Spring Boot 4.1.1 深度源码解析-第 26 章 · 指标、观测与链路追踪:Micrometer 与 OpenTelemetry
java·后端·开源