Administrator
发布于 2026-06-03 / 4 阅读
0
0

RabbitMQ消息队列详解

RabbitMQ消息队列详解

RabbitMQ是基于AMQP协议的企业级消息中间件,本文介绍其核心概念和实战用法。

一、核心概念

  • Exchange:交换机,接收消息并路由到队列

  • Queue:队列,存储消息

  • Binding:绑定,连接交换机和队列

  • Routing Key:路由键,决定消息路由

  • Virtual Host:虚拟主机,权限隔离

二、Exchange类型

  • Direct:精确匹配Routing Key

  • Topic:通配符匹配(*、#)

  • Fanout:广播到所有绑定队列

  • Headers:基于消息头匹配

三、Spring Boot整合

// 配置类
@Configuration
public class RabbitConfig {
    @Bean
    public Queue myQueue() {
        return new Queue("my-queue", true);
    }

    @Bean
    public DirectExchange myExchange() {
        return new DirectExchange("my-exchange");
    }
}

// 生产者
@Autowired
private RabbitTemplate rabbitTemplate;

rabbitTemplate.convertAndSend("my-exchange", "routing.key", message);

// 消费者
@RabbitListener(queues = "my-queue")
public void handleMessage(String message) {
    System.out.println("Received: " + message);
}

四、死信队列

用于处理消费失败的消息,配置步骤:

  1. 创建死信交换机和队列

  2. 在原队列上绑定死信交换机

  3. 设置消息TTL或拒绝消费

五、延迟队列

// 使用RabbitMQ延迟插件
@Bean
public Queue delayQueue() {
    Map<String, Object> args = new HashMap<>();
    args.put("x-delayed-type", "direct");
    return new Queue("delay-queue", true, false, false, args);
}


评论