# RabbitMQ 传输器

来源：https://docs.nestjs.com/microservices/rabbitmq

[RabbitMQ](https://www.rabbitmq.com/) 是一个开源、轻量的消息 broker，支持多种消息协议。它可以部署为分布式和联邦式配置，以满足大规模、高可用性的要求，并且是部署最广泛的消息 broker 之一，从小的初创公司到大型企业都在使用。

> info **提示** 若想了解两个通过 RabbitMQ 通信的完整服务——包含事件、请求-响应、重试、死信队列，以及崩溃后仍能存续的消息——请参阅[用 RabbitMQ 在 Node.js 中构建微服务](/tutorials/microservices-rabbitmq)。

#### 安装

要开始构建基于 RabbitMQ 的微服务，请先安装所需的包：

```bash
$ npm i --save amqplib amqp-connection-manager
```

#### 概览

要使用 RabbitMQ 传输器，请把下面的选项对象传给 `createMicroservice()` 方法：

```typescript
@@filename(main)
const app = await NestFactory.createMicroservice<MicroserviceOptions>(AppModule, {
  transport: Transport.RMQ,
  options: {
    urls: ['amqp://localhost:5672'],
    queue: 'cats_queue',
    queueOptions: {
      durable: false
    },
  },
});
```

> info **提示** `Transport` 枚举从 `@nestjs/microservices` 包导入。

#### 选项

`options` 属性是所选传输器专属的。<strong>RabbitMQ</strong> 传输器暴露以下属性。

<table>
  <tr>
    <td><code>urls</code></td>
    <td>按顺序尝试的连接 URL 数组</td>
  </tr>
  <tr>
    <td><code>queue</code></td>
    <td>服务器监听的队列名</td>
  </tr>
  <tr>
    <td><code>prefetchCount</code></td>
    <td>设置通道的预取数量</td>
  </tr>
  <tr>
    <td><code>isGlobalPrefetchCount</code></td>
    <td>若为 <code>true</code>，预取数量按通道生效，而不是按消费者生效</td>
  </tr>
  <tr>
    <td><code>noAck</code></td>
    <td>若为 <code>false</code>，启用手动确认模式。默认为 <code>true</code></td>
  </tr>
  <tr>
    <td><code>nackOnInternalError</code></td>
    <td>若为 <code>true</code>（且 <code>noAck</code> 为 <code>false</code>），当处理器因内部错误而失败时，对该消息做否定确认且不重新入队，从而由死信交换机接收（参见<a href="/microservices/rabbitmq#message-acknowledgement">消息确认</a>）。默认为 <code>false</code></td>
  </tr>
  <tr>
    <td><code>consumerTag</code></td>
    <td>服务器用于区分该消费者消息投递的名称；它不能是该通道上已在使用的名称。通常省略它更为简单，此时服务器会生成一个随机名称并在应答中提供（参见 amqplib 文档中的 <a href="https://amqp-node.github.io/amqplib/channel_api.html#channel_consume" rel="nofollow" target="_blank"><code>channel.consume()</code></a>）</td>
  </tr>
  <tr>
    <td><code>queueOptions</code></td>
    <td>额外的队列选项（参见 amqplib 文档中的 <a href="https://amqp-node.github.io/amqplib/channel_api.html#channel_assertQueue" rel="nofollow" target="_blank"><code>channel.assertQueue()</code></a>）</td>
  </tr>
  <tr>
    <td><code>socketOptions</code></td>
    <td>额外的 socket 选项（参见 amqplib 文档中的 <a href="https://amqp-node.github.io/amqplib/channel_api.html#connect" rel="nofollow" target="_blank"><code>connect()</code></a>）</td>
  </tr>
  <tr>
    <td><code>headers</code></td>
    <td>随每条消息发送的消息头。仅适用于生产者（客户端）配置</td>
  </tr>
  <tr>
    <td><code>replyQueue</code></td>
    <td>生产者的应答队列。默认为 <code>amq.rabbitmq.reply-to</code></td>
  </tr>
  <tr>
    <td><code>persistent</code></td>
    <td>若为真值，消息可在 broker 重启后存续，前提是它们所在的队列也能在重启后存续</td>
  </tr>
  <tr>
    <td><code>noAssert</code></td>
    <td>若为 <code>true</code>，在消费之前不声明队列。默认为 <code>false</code></td>
  </tr>
  <tr>
    <td><code>wildcards</code></td>
    <td>仅当你希望使用主题交换机把消息路由到队列时才设为 <code>true</code>。启用后可在消息模式和事件模式中使用通配符（<code>*</code>、<code>#</code>）</td>
  </tr>
  <tr>
    <td><code>exchange</code></td>
    <td>交换机名称。当 <code>wildcards</code> 设为 <code>true</code> 时默认为队列名</td>
  </tr>
  <tr>
    <td><code>exchangeType</code></td>
    <td>交换机类型。默认为 <code>topic</code>。接受标准 AMQP 类型 <code>direct</code>、<code>fanout</code>、<code>topic</code> 和 <code>headers</code>，也可接受自定义交换机类型的名称</td>
  </tr>
  <tr>
    <td><code>exchangeArguments</code></td>
    <td>声明交换机时传入的额外参数</td>
  </tr>
  <tr>
    <td><code>routingKey</code></td>
    <td>主题交换机的附加路由键</td>
  </tr>
  <tr>
    <td><code>maxConnectionAttempts</code></td>
    <td>最大连接尝试次数。仅适用于消费者配置。默认为 <code>-1</code>（无限）</td>
  </tr>
  <tr>
    <td><code>maxMessageSize</code></td>
    <td>消息体的最大大小，以字节计。更大的消息会被服务器记录日志并跳过，不做解码（当 <code>noAck</code> 为 <code>false</code> 时对其做不重新入队的否定确认，请求则会收到错误应答），而客户端会让应答超过该限制的请求失败。设为 <code>Infinity</code> 可取消限制。若取值不是数字（例如 <code>Number()</code> 把未设置的环境变量变成的 <code>NaN</code>），则采用默认值。默认为 <code>16777216</code>（16 MiB）</td>
  </tr>
  <tr>
    <td><code>gracefulShutdown</code></td>
    <td>启用优雅关闭。启用后，关闭服务器会先取消其消费者，然后等待正在处理的请求和事件完成，再关闭通道和连接。仅适用于消费者配置。默认为 <code>false</code></td>
  </tr>
  <tr>
    <td><code>gracePeriod</code></td>
    <td>启用 <code>gracefulShutdown</code> 时，等待正在处理的请求和事件的最长时间，以毫秒计。若这些处理在此之前完成，服务器会更早关闭。仅适用于消费者配置。默认为 <code>10000</code></td>
  </tr>
</table>

> info **提示** 返回一个永不结束的流的处理器仍被视为正在处理，因此此时关闭服务器会耗尽整个 `gracePeriod`。当 `noAck` 设为 `false` 时，broker 会在通道关闭时把仍未确认的消息重新入队，因此处理器超出 `gracePeriod` 的消息会被再次投递。

#### 客户端

与其他微服务传输器一样，你有[多种选择](/microservices/basics#client-producer-class)来创建 RabbitMQ 的 `ClientProxy` 实例。

创建实例的一种方式是使用 `ClientsModule`。导入它并调用其 `register()` 方法，传入一个选项对象，其属性与上面 `createMicroservice()` 方法中展示的相同，另加一个用作注入标记的 `name` 属性。关于 `ClientsModule` 的更多内容，请参阅[微服务概览](/microservices/basics#client-producer-class)。

```typescript
@Module({
  imports: [
    ClientsModule.register([
      {
        name: 'MATH_SERVICE',
        transport: Transport.RMQ,
        options: {
          urls: ['amqp://localhost:5672'],
          queue: 'cats_queue',
          queueOptions: {
            durable: false
          },
        },
      },
    ]),
  ]
  ...
})
```

你也可以用 `ClientProxyFactory` 或 `@Client()` 创建客户端，详见[微服务概览](/microservices/basics#client-producer-class)。

#### 上下文

在更复杂的场景中，你可能需要关于传入请求的额外信息。使用 RabbitMQ 传输器时，你可以访问 `RmqContext` 对象。

```typescript
@@filename()
@MessagePattern('notifications')
getNotifications(@Payload() data: number[], @Ctx() context: RmqContext) {
  console.log(`Pattern: ${context.getPattern()}`);
}
```

> info **提示** `@Payload()`、`@Ctx()` 和 `RmqContext` 从 `@nestjs/microservices` 包导入。

要访问原始的 RabbitMQ 消息（含其 `properties`、`fields` 和 `content`），请使用 `RmqContext` 对象的 `getMessage()` 方法：

```typescript
@@filename()
@MessagePattern('notifications')
getNotifications(@Payload() data: number[], @Ctx() context: RmqContext) {
  console.log(context.getMessage());
}
```

要取得 RabbitMQ [通道](https://www.rabbitmq.com/channels.html)的引用，请使用 `RmqContext` 对象的 `getChannelRef()` 方法：

```typescript
@@filename()
@MessagePattern('notifications')
getNotifications(@Payload() data: number[], @Ctx() context: RmqContext) {
  console.log(context.getChannelRef());
}
```

#### 消息确认

为确保消息永不丢失，RabbitMQ 支持[消息确认](https://www.rabbitmq.com/confirms.html)。消费者回送一个确认，告知 RabbitMQ 某条消息已被接收并处理完毕，RabbitMQ 可以自由删除它。如果消费者在未发送确认的情况下死亡（其通道被关闭、连接被关闭，或 TCP 连接丢失），RabbitMQ 会认为该消息未被完全处理，并把它重新入队。

默认情况下，RabbitMQ 传输器不要求确认（`noAck` 为 `true`）。要启用手动确认模式，请把 `noAck` 属性设为 `false`：

```typescript
options: {
  urls: ['amqp://localhost:5672'],
  queue: 'cats_queue',
  noAck: false,
  queueOptions: {
    durable: false
  },
},
```

开启手动消费者确认后，你必须从 worker 发出确认，以表明它已完成任务：

```typescript
@@filename()
@MessagePattern('notifications')
getNotifications(@Payload() data: number[], @Ctx() context: RmqContext) {
  const channel = context.getChannelRef();
  const originalMsg = context.getMessage();

  channel.ack(originalMsg);
}
```

当处理器失败时，服务器会让其消息保持未确认状态。该消息会一直占用一个 `prefetchCount` 名额，直到通道关闭，然后 broker 会再次投递它，因此一个永远无法处理的负载会在每次重连后回来，永远进不了[死信交换机](https://www.rabbitmq.com/docs/dlx)。要让这类消息进入死信，请把 `nackOnInternalError` 设为 `true`（`@nestjs/microservices` 12.6.1 及之后版本可用）：

```typescript
options: {
  urls: ['amqp://localhost:5672'],
  queue: 'orders',
  noAck: false,
  nackOnInternalError: true,
  queueOptions: {
    durable: true,
    arguments: { 'x-dead-letter-exchange': 'orders.dlx' },
  },
},
```

启用该选项后，当事件处理器或请求处理器因内部错误而失败时，服务器会调用 `nack(message, false, false)`。内部错误是指 `RpcException` 之外的异常，默认异常过滤器会以「Internal server error」应答这类异常。消息不会被重新入队，因此队列的死信交换机会收到它；若队列没有死信交换机，broker 会丢弃它。请求仍会收到其错误应答。该选项不影响其他任何行为：

- `RpcException` 属于业务错误，例如处理器抛出的「not found」或守卫抛出的「Forbidden resource」：消息保持未确认。
- 成功完成的处理器仍会自行确认其消息。
- 处理器（或拦截器）已经确认或拒绝的消息不会被再次结算，否则 RabbitMQ 会以关闭通道来回应。
- 使用自己的负载应答的自定义异常过滤器（即不调用 `BaseRpcExceptionFilter` 的 `super.catch()`）不算作内部错误。

> info **提示** 校验管道抛出的是 `BadRequestException`，它并非 `RpcException`，因此未通过校验的负载会进入死信：对毒消息而言这正是你想要的。若要把校验失败当作业务错误处理，请为该管道提供一个返回 `RpcException` 的 `exceptionFactory`。

#### 记录构建器

要配置消息选项，请使用 `RmqRecordBuilder` 类（它对基于事件的流程同样有效）。例如，要设置 `headers` 和 `priority` 属性，请使用 `setOptions()` 方法：

```typescript
const message = ':cat:';
const record = new RmqRecordBuilder(message)
  .setOptions({
    headers: {
      ['x-version']: '1.0.0',
    },
    priority: 3,
  })
  .build();

this.client.send('replace-emoji', record).subscribe(...);
```

> info **提示** `RmqRecordBuilder` 类从 `@nestjs/microservices` 包导出。

AMQP 把某些消息属性以短字符串携带，最长 255 字节：`contentType`、`contentEncoding`、`correlationId`、`replyTo`、`expiration`、`messageId`、`type`、`userId` 和 `appId`。若某个 `send()` 或 `emit()` 的选项把这些属性之一设得更长，或者（在使用 `wildcards` 或 `fanout` 交换机时）其模式（会成为路由键）超过 255 字节，客户端就会失败。对于 `replyTo` 或 `correlationId` 更长的请求，服务器不会应答，并记录一条错误日志。

你也可以在服务器端通过访问 `RmqContext` 读取这些值：

```typescript
@@filename()
@MessagePattern('replace-emoji')
replaceEmoji(@Payload() data: string, @Ctx() context: RmqContext): string {
  const { properties: { headers } } = context.getMessage();
  return headers['x-version'] === '1.0.0' ? '🐱' : '🐈';
}
```

从 NestJS v12.1.3 起，消息处理器也可以返回记录。Nest 会把记录中的数据作为应答发送，并把记录的选项（例如 `headers` 和 `priority` 属性）应用到应答消息上：

```typescript
@MessagePattern('replace-emoji')
replaceEmoji() {
  return new RmqRecordBuilder(':cat:')
    .setOptions({
      headers: {
        ['x-version']: '1.0.0',
      },
      priority: 3,
    })
    .build();
}
```

应答总会携带请求的关联 ID，因此客户端可以把它与请求匹配起来。

#### 实例状态更新

要实时获取连接以及底层驱动实例状态的变化，请订阅 `status` 流。该流提供所选驱动专属的状态更新。对于 RMQ 驱动，`status` 流会发出 `connected`、`disconnected`、`blocked` 和 `unblocked` 事件。

```typescript
this.client.status.subscribe((status: RmqStatus) => {
  console.log(status);
});
```

> info **提示** `RmqStatus` 类型从 `@nestjs/microservices` 包导入。

类似地，你可以订阅服务器的 `status` 流，以接收关于服务器状态的通告：

```typescript
const server = app.connectMicroservice<MicroserviceOptions>(...);
server.status.subscribe((status: RmqStatus) => {
  console.log(status);
});
```

#### 监听 RabbitMQ 事件

在某些情况下，你可能想监听微服务发出的内部事件。例如，你可以监听 `error` 事件，以便在发生错误时触发额外操作。为此，请使用 `on()` 方法：

```typescript
this.client.on('error', (err) => {
  console.error(err);
});
```

类似地，你可以监听服务器的内部事件：

```typescript
server.on<RmqEvents>('error', (err) => {
  console.error(err);
});
```

> info **提示** `RmqEvents` 类型从 `@nestjs/microservices` 包导入。

从 NestJS v12.1.2 起，通过客户端 `on()` 方法注册的监听器会一直保持注册状态，直到你调用 `close()`，因此它们也会挂到客户端在上一次连接尝试失败后、下一次 `send()` 或 `emit()` 调用时新建的连接上。注册不会被去重，所以每个监听器只注册一次，不要在它自己的回调里或每次连接尝试失败后再次注册。

#### 访问底层驱动

对于更高级的用例，你可能需要访问底层驱动实例，例如手动关闭连接或使用驱动专属方法。不过在大多数情况下，你 **不应该需要** 直接访问驱动。

要这样做，请使用 `unwrap()` 方法，它返回底层驱动实例。用泛型类型参数指定你期望的驱动实例类型。

```typescript
const managerRef =
  this.client.unwrap<import('amqp-connection-manager').AmqpConnectionManager>();
```

类似地，你可以访问服务器的底层驱动实例：

```typescript
const managerRef =
  server.unwrap<import('amqp-connection-manager').AmqpConnectionManager>();
```

#### 通配符

RabbitMQ 支持在路由键中使用通配符，以实现灵活的消息路由。`#` 通配符匹配零个或多个单词，`*` 通配符恰好匹配一个单词。

例如，路由键 `cats.#` 可匹配 `cats`、`cats.meow` 和 `cats.meow.purr`。路由键 `cats.*` 可匹配 `cats.meow`，但不匹配 `cats.meow.purr`。

要在你的 RabbitMQ 微服务中启用通配符支持，请在选项对象中把 `wildcards` 配置选项设为 `true`：

```typescript
const app = await NestFactory.createMicroservice<MicroserviceOptions>(
  AppModule,
  {
    transport: Transport.RMQ,
    options: {
      urls: ['amqp://localhost:5672'],
      queue: 'cats_queue',
      wildcards: true,
    },
  },
);
```

有了该配置，你在订阅事件和消息时就可以在路由键中使用通配符。例如，要监听路由键为 `cats.#` 的消息：

```typescript
@MessagePattern('cats.#')
getCats(@Payload() data: { message: string }, @Ctx() context: RmqContext) {
  console.log(`Received message with routing key: ${context.getPattern()}`);

  return {
    message: 'Hello from the cats service!',
  }
}
```

要发送带特定路由键的消息，请使用 `ClientProxy` 实例的 `send()` 方法：

```typescript
this.client.send('cats.meow', { message: 'Meow!' }).subscribe((response) => {
  console.log(response);
});
```

路由键最多容纳 255 字节，因此模式超过 255 个字符的消息匹配不到任何通配符模式。
