Skip to content

Node.js RabbitMQ(消息队列)

RabbitMQ 是基于 AMQP 协议的开源消息队列中间件,用于微服务间异步解耦通信。

核心概念

概念说明
Producer生产者,发送消息
Consumer消费者,接收并处理消息
Exchange交换机,接收消息按规则路由到队列
Queue队列,存储消息
Binding绑定,Exchange 和 Queue 的关联规则

三种 Exchange 模式

模式路由规则
direct按 routingKey 精确匹配
topic*# 通配符匹配
fanout广播,忽略 routingKey

安装

bash
npm install amqplib

生产者

js
import amqp from 'amqplib'

const conn = await amqp.connect('amqp://localhost')
const channel = await conn.createChannel()
const queue = 'task_queue'

await channel.assertQueue(queue, { durable: true })  // 持久化队列

channel.sendToQueue(queue, Buffer.from('hello'), { persistent: true })  // 持久化消息

消费者

js
const conn = await amqp.connect('amqp://localhost')
const channel = await conn.createChannel()

channel.assertQueue('task_queue', { durable: true })
channel.prefetch(1)  // 每次只取一条(公平分发)

channel.consume('task_queue', (msg) => {
  console.log('收到:', msg.content.toString())
  channel.ack(msg)   // 确认消费
})

应用场景

场景说明
异步任务耗时操作(发邮件/生成报表)异步处理
流量削峰大促时先入队列,逐步消费
服务解耦微服务间通过消息通信,不直接调用
日志收集各服务日志统一发到 MQ,消费端集中处理