@cloudamqp/amqp-client

中文文档
4.1.2发布于 2026/10/19Apache-2.0TypeScriptESM + CJS零依赖构建来源已验证近 30 天下载 37.2万

AMQP 0-9-1 client for RabbitMQ, LavinMQ and other AMQP brokers, both for browsers (WebSocket) and node (TCP Socket)

原始使用文档
文档目录12 节
  1. Support
  2. Install
  3. Example usage
  4. High-level API (recommended)
  5. Low-level API
  6. WebSockets
  7. Performance
  8. Release
  9. Release Commands
  10. What happens during a release
  11. Prerequisites
  12. Automated npm Publishing

amqp-client.js

AMQP 0-9-1 TypeScript client both for Node.js and browsers (using WebSocket). This library is intended to replace all other Node.js AMQP libraries.

It works with any AMQP 0-9-1 broker: RabbitMQ, LavinMQ and Apache Qpid, whether self-hosted or managed by a provider such as CloudAMQP or Amazon MQ — they all speak the same protocol, so the same code runs against all of them.

API documentation.

This library is Promise-based and hence works very well with async/await. It's secure by default, for instance, publishes aren't fulfilled until either the data has been sent on the wire (so that back propagation is respected), or if the channel has Publish Confirms enabled, it isn't fulfilled until the server has acknowledged that the message has been enqueued.

The library was developed so to make it easy for developers who already are familiar with AMQP to write browser apps that communicates directly with an AMQP server over WebSocket.

Support

The library is developed and supported by CloudAMQP, the largest hosted RabbitMQ provider in the world.

Install

npm install @cloudamqp/amqp-client --save

Start node with --enable-source-maps to get proper stacktraces as the library is transpiled from TypeScript.

Example usage

This library provides two APIs:

  • High-level (AMQPSession): automatic reconnection, consumer recovery — use queue() / exchange() handles for reconnect-safe operations
  • Low-level (AMQPClient / AMQPWebSocketClient): direct channel access with queueDeclare, basicPublish, basicConsume, etc.

Use AMQPSession.connect(url, options) to get a session with automatic reconnection and consumer recovery. The transport is chosen from the URL scheme (amqp:// / amqps:// → TCP; ws:// / wss:// → WebSocket):

import { AMQPSession } from "@cloudamqp/amqp-client"

const session = await AMQPSession.connect("amqp://localhost")

// Declare a queue and publish a message (waits for broker confirmation)
const q = await session.queue("my-queue")
await q.publish("Hello World", { deliveryMode: 2 })

// Subscribe with a callback — consumer recovers automatically on reconnect.
// Messages are acked after the callback returns. If it throws, the message is
// nacked and requeued. Call msg.ack() / msg.nack() yourself to override.
const sub = await q.subscribe(async (msg) => {
  console.log(msg.bodyString())
})

// Or subscribe with an async iterator — messages are acked when the loop advances.
// Call msg.ack() / msg.nack() before the next iteration to override.
const iterSub = await q.subscribe()
for await (const msg of iterSub) {
  console.log(msg.bodyString())
}

// Exchanges work the same way
const x = await session.topicExchange("events")
await x.publish("user signed up", { routingKey: "events.user.created" })

// When done
await session.stop()

Automatic encoding/decoding (codecs)

Opt in to a codec registry and the session serializes and deserializes message bodies for you based on content-type and content-encoding. Pass builtinParsers (JSON, text) and builtinCoders (gzip, deflate), and optionally set defaults so you don't repeat them on every publish:

import { AMQPSession, builtinParsers, builtinCoders } from "@cloudamqp/amqp-client"

const session = await AMQPSession.connect("amqp://localhost", {
  parsers: builtinParsers,
  coders: builtinCoders,
  defaultContentType: "application/json", // applied when publish() doesn't set one
  defaultContentEncoding: "gzip", // body is gzip-compressed on the wire
})

const q = await session.queue("jobs")

// Object is serialized to JSON and gzip-compressed automatically
await q.publish({ task: "resize", id: 42 })

// On consume, msg.body is the decoded value — no JSON.parse, no decompression
const sub = await q.subscribe(async (msg) => {
  console.log(msg.body.task) // "resize"
})

msg.body is Uint8Array when no codecs are configured and the decoded value when they are; the CodecMode generic infers this at compile time. Override per publish by passing contentType / contentEncoding in the options. Register your own codecs by merging with the built-ins:

const session = await AMQPSession.connect("amqp://localhost", {
  parsers: { ...builtinParsers, "text/csv": csvParser },
  coders: { ...builtinCoders, lz4: lz4Coder },
})

Decode failures surface as a plain Error (not AMQPError); in subscribe() they nack the message, honoring requeueOnNack.

Reconnection options

const session = await AMQPSession.connect("amqp://localhost", {
  reconnectInterval: 1000, // initial delay before reconnecting (ms)
  maxReconnectInterval: 30000, // maximum delay between attempts (ms)
  backoffMultiplier: 2, // exponential backoff multiplier
  maxRetries: 0, // 0 = infinite retries
  onconnect: () => console.log("Connected"), // fires on initial connect + each reconnect
  ondisconnect: (err) => console.warn("Disconnected:", err?.message),
  onfailed: (err) => console.error("Gave up:", err?.message),
})

Consumer recovery

Subscriptions created via queue.subscribe() are automatically re-established after reconnection. Include prefetch in the subscribe params to set QoS on each connection:

const q = await session.queue("my-queue", { durable: true })
const sub = await q.subscribe({ prefetch: 10 }, async (msg) => {
  // process msg — acked on return, nacked and requeued on throw
})

// sub.consumerTag and sub.channel reflect the current consumer (updated on reconnect)
// await sub.cancel()  // stops consuming and removes from auto-recovery

RPC (Remote Procedure Call)

The session provides built-in RPC support using the direct reply-to feature:

import { AMQPSession } from "@cloudamqp/amqp-client"

const session = await AMQPSession.connect("amqp://localhost")

// Start an RPC server that listens on a queue
const server = await session.rpcServer("my_rpc_queue", async (msg) => {
  return `processed:${msg.bodyString()}`
})

// Simple RPC call — creates a temporary client per call
const reply = await session.rpcCall("my_rpc_queue", "hello", { timeout: 5000 })
console.log(reply.bodyToString()) // "processed:hello"

// For high-throughput scenarios, reuse a client to avoid per-call channel overhead
const rpc = await session.rpcClient()
const r1 = await rpc.call("my_rpc_queue", "a")
const r2 = await rpc.call("my_rpc_queue", "b")
await rpc.close()

await session.stop() // closes all RPC clients, servers, and consumers

RPC servers and reusable clients created via session.rpcClient() are automatically recovered after a reconnection.

Low-level API

For full control over channels and resources, use the transport clients directly:

import { AMQPClient } from "@cloudamqp/amqp-client"

const amqp = new AMQPClient("amqp://localhost")
const conn = await amqp.connect()
const ch = await conn.channel()

// Declare a queue
const q = await ch.queueDeclare("my-queue")

// Publish
await ch.basicPublish("", q.name, "Hello World", { deliveryMode: 2 })

// Consume with a callback
const consumer = await ch.basicConsume(q.name, { noAck: false }, async (msg) => {
  console.log(msg.bodyToString())
  await msg.ack()
  await consumer.cancel()
})
await consumer.wait()

// Or consume with an async iterator
const consumer = await ch.basicConsume(q.name, { noAck: false })
for await (const msg of consumer.messages) {
  console.log(msg.bodyToString())
  await msg.ack()
  break // breaking automatically cancels the consumer
}

await conn.close()

WebSockets

This library can be used in the browser to access an AMQP server over WebSockets. For servers such as RabbitMQ that doesn't support WebSockets natively a WebSocket TCP relay have to be used as a proxy. All CloudAMQP servers has this proxy configured. More information can be found in this blog post.

For web browsers a compiled and rolled up version is available at https://github.com/cloudamqp/amqp-client.js/releases.

AMQPSession works with WebSocket URLs out of the box — pass a ws:// or wss:// URL and transport is chosen automatically:

import { AMQPSession } from "@cloudamqp/amqp-client"

const session = await AMQPSession.connect("wss://my.cloudamqp.com/ws/", {
  vhost: "my-vhost",
})
const q = await session.queue("my-queue")
const sub = await q.subscribe({ noAck: true }, (msg) => {
  console.log(msg.bodyString())
})

For lower-level control without reconnection, use AMQPWebSocketClient directly:

<!DOCTYPE html>
<html>
  <head>
    <script type="module">
      import { AMQPWebSocketClient } from "./js/amqp-websocket-client.mjs"

      const textarea = document.getElementById("textarea")
      const input = document.getElementById("message")

      const tls = window.location.protocol === "https:"
      const url = `${tls ? "wss" : "ws"}://${window.location.host}`
      const amqp = new AMQPWebSocketClient(url, "/", "guest", "guest")

      async function start() {
        try {
          const conn = await amqp.connect()
          const ch = await conn.channel()
          attachPublish(ch)
          const q = await ch.queueDeclare("")
          await ch.queueBind(q.name, "amq.fanout", "")
          const consumer = await ch.basicConsume(q.name, { noAck: false }, (msg) => {
            console.log(msg)
            textarea.value += msg.bodyToString() + "\n"
            msg.ack()
          })
        } catch (err) {
          console.error("Error", err, "reconnecting in 1s")
          disablePublish()
          setTimeout(start, 1000)
        }
      }

      function attachPublish(ch) {
        document.forms[0].onsubmit = async (e) => {
          e.preventDefault()
          try {
            await ch.basicPublish("amq.fanout", "", input.value, {
              contentType: "text/plain",
            })
          } catch (err) {
            console.error("Error", err, "reconnecting in 1s")
            disablePublish()
            setTimeout(start, 1000)
          }
          input.value = ""
        }
      }

      function disablePublish() {
        document.forms[0].onsubmit = (e) => {
          alert("Disconnected, waiting to be reconnected")
        }
      }

      start()
    </script>
  </head>
  <body>
    <form>
      <textarea id="textarea" rows="10"></textarea>
      <br />
      <input id="message" />
      <button type="submit">Send</button>
    </form>
  </body>
</html>

Performance

Messages with a 1-byte body, no properties:

ClientPublish rateConsume rate
amqp-client.js300.000 msgs/s512.000 msgs/s
amqplib172.000 msgs/s519.000 msgs/s

Messages with a 1-byte body, and all properties, except headers:

ClientPublish rateConsume rate
amqp-client.js144.000 msgs/s202.000 msgs/s
amqplib110.000 msgs/s251.000 msgs/s

Messages with a 1-byte body, and all properties, including headers:

ClientPublish rateConsume rate
amqp-client.js70.000 msgs/s89.000 msgs/s
amqplib60.000 msgs/s99.000 msgs/s

The reason amqp-client is somewhat slower to consume is that to maintain browser compatibility for the websocket client, DataView are used for parsing the binary protocol instead of Buffer.

Module comparison

ClientRuntime dependenciesLines of code
amqp-client.js01743
amqplib146720 (w/o dependencies)

Release

This project uses automated release scripts for version management.

Release Commands

The package.json includes several npm scripts for releasing:

  • npm run release - Performs a patch version bump (e.g., 3.2.1 → 3.2.2) and creates a release
  • npm run release:minor - Performs a minor version bump (e.g., 3.2.1 → 3.3.0) and creates a release
  • npm run release:major - Performs a major version bump (e.g., 3.2.1 → 4.0.0) and creates a release

What happens during a release

  1. Tests: All tests are run to ensure everything passes (preversion)
  2. Version bump: npm automatically updates the version in package.json
  3. File updates: The version is updated in src/amqp-base-client.ts, code is formatted, and changelog is updated (version)
  4. Staging: All changes are staged for commit (version)
  5. Git commit: npm automatically commits all staged changes with a version message
  6. Git tag: An annotated tag is created with the full changelog content as the tag message (postversion)
  7. Push: Both the commit and tags are pushed to the remote repository (postversion)
  8. CI deployment: The GitHub Actions workflow automatically publishes the new version to npm

Technical Note: This release process leverages npm's built-in version lifecycle hooks (preversion, version, postversion). The npm version command automatically handles the git commit after running our custom version script, which is why we stage changes with git add -A rather than committing manually.

Prerequisites

Before releasing:

  1. Add your changes to the ## [Unreleased] section in CHANGELOG.md
  2. All tests should pass (npm test)
  3. The working directory should be clean (no uncommitted changes)

Automated npm Publishing

When a new tag is pushed (e.g., v3.3.0), the GitHub Actions workflow (.github/workflows/release.yml) automatically:

  • Builds the project
  • Publishes the package to npm with public access and provenance
  • Creates a GitHub release with browser bundle artifacts

The git tag contains the complete changelog section for that version, including version header, all changes, and PR links. This makes it easy to see what changed in each release directly from the git tag.

版本与发布记录

@cloudamqp/amqp-client 共发布 41 个版本,首次发布于 2021/02/17;过去 12 个月发布了 6 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
4.1.2latest2026/10/1921 天前
4.1.12026/08/282 个月前
4.1.02026/08/192 个月前
4.0.02026/06/124 个月前
3.4.12025/11/2811 个月前
3.4.02025/11/1311 个月前

关于 @cloudamqp/amqp-client 的常见问题

@cloudamqp/amqp-client 是什么?

AMQP 0-9-1 client for RabbitMQ, LavinMQ and other AMQP brokers, both for browsers (WebSocket) and node (TCP Socket)

如何安装 @cloudamqp/amqp-client?

在项目目录运行 npm install @cloudamqp/amqp-client,或使用 pnpm add / yarn add / bun add。

@cloudamqp/amqp-client 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@cloudamqp/amqp-client 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@cloudamqp/amqp-client 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=18.0.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@cloudamqp/amqp-client 可以商用吗?

@cloudamqp/amqp-client 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@cloudamqp/amqp-client 的下载量有多少?

根据 npm 官方下载统计,@cloudamqp/amqp-client 在 2026/10/10 – 2026/11/08 这 30 天内被下载 372,202 次,日均约 12,407 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@cloudamqp/amqp-client 还在维护吗?

最新版本 4.1.2 发布于 2026/10/19(21 天前);至今共发布 41 个版本,其中过去 12 个月发布了 6 个;首次发布于 2021/02/17。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。