# @azure/amqp-common 中文文档

规范地址：https://npmcn.com/package/%40azure/amqp-common/

版本：1\.0\.0-preview\.17
npm 元数据更新时间：2026-03-19T20:32:16.058Z
中文译文更新时间：2026-11-07T14:42:12.499Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40azure/amqp-common
原文对照：https://npmcn.com/package/%40azure/amqp-common/?lang=original
项目主页：https://github.com/Azure/azure-sdk-for-js/tree/%40azure/amqp-common_1.0.0-preview.17/sdk/core/amqp-common
源码仓库：https://github.com/azure/azure-sdk-for-js

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：2.3 MB，125 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- 运行依赖：15 个
- 首次发布：2018-09-13T01:10:22.056Z
- 最新版本发布：2020-09-11T17:27:17.888Z
- 近 30 天下载量：17117（2026-10-08 至 2026-11-06，npm 官方下载统计）
- 已发布版本数：28（近 12 个月 0 个）

## 中文简介

基于amqp的 Azure sdks 如@azure/event-hubs 的常见库.

## 安装

```sh
npm install @azure/amqp-common
```

也可以使用：`pnpm add @azure/amqp-common`、`yarn add @azure/amqp-common`、`bun add @azure/amqp-common`

## README

# Azure Core AMQP 用于AMQP操作的客户端库

提供不同功能的库 **阿苏雷** 使用 amqp 协议的 Javascript 库 . 其中一些共同功能包括:

-   CBS 澳大利亚
-   通过AMQP发送请求和接收回复的请求-响应链接
-   不同的 AMQP 错误代码翻译出错 .
-   创建 `ConnectionConfig` 通过解析连接字符串
-   AMQP 信件头和信件属性转换
-   大多数AMQP基于Azure服务用于通信的AMQP消息数据转换(编码/解码)
-   重试不同操作的政策

## 开始

### 先决条件

-   **节点.js版本: 6.x或更高.**
-   我们会 **还是鼓励你** 以在任何特定时间安装最新的 LTS 版本 [https://nodejs.org (英语)](https://nodejs.org/)。 。 。 . **总是安装最新可用的LTS版本节点.js是一个好的做法.**
-   正在安装节点.js on **窗口或macOS** 使用可用的安装器 [节点.js网站](https://nodejs.org/)。如果您正在使用 **基于 linux 的操作系统**,然后可以发现容易遵循,一步安装指令 [这里](https://nodejs.org/en/download/package-manager/)。 。 。 .

### 安装

-   安装此库

```bash
npm install @azure/amqp-common
```

-   [`rhea-promise`](https://github.com/amqp/rhea-promise) 是同级依赖。 您需要明确安装此库作为依赖 在您的申请.

### IDE 开发环境

这个 sdk 是在 [类型脚本](https://typescriptlang.org/) 并且有很好的源代码文档. 强烈建议使用 [vscode 密码](https://code.visualstudio.com/) 或任何能提供更好的内涵并暴露源代码文件的全部功率的IDE.

## 关键概念

这个 SDK 包含核心 AMQP 在使用 bu Azure SDKs 使用协议中的共同相关功能.

## 实例

请看一下 [样本](https://github.com/Azure/azure-sdk-for-js/tree/%40azure/amqp-common_1.0.0-preview.16/sdk/core/amqp-common/samples) 详细样本目录. 您可以在样本.js文件中复制复制以下样本.

```bash
- git clone https://github.com/Azure/azure-sdk-for-js.git
- cd azure-sdk-for-js/sdk/core/amqp-common
- npm i
- npm i -g typescript  #This is optional. However it is useful to have typescript installed globally on your box
- npm i -g ts-node     #This is optional. However it is useful to have ts-node installed globally on your box
# Make sure to set the environment variables and then run
- ts-node ./samples/cbsAuth.ts
```

以下样本为EventHubs和Servicebus通用. 您可以找到事件Hub的具体样本, 输入 [样本](https://github.com/Azure/azure-sdk-for-js/tree/%40azure/amqp-common_1.0.0-preview.16/sdk/core/amqp-common/samples) 目录.

## 例1 - CBS(基于请求的授权规格)

有关CBs授权的更多信息,请查看 [这里](https://docs.microsoft.com/en-us/azure/service-bus-messaging/service-bus-amqp-protocol-guide#claims-based-authorization)。 。 。 .

注:下面的代码块后来被称作"./cbsAuth".

```js
const { ConnectionContextBase, ConnectionConfig, CbsResponse } = require("@azure/amqp-common");
const dotenv = require("dotenv");
dotenv.config(); // Optional for loading environment configuration from a .env (config) file

export const str = process.env.CONNECTION_STRING || "";
export const path = process.env.ENTITY_PATH;
export const connectionConfig = ConnectionConfig.create(str, path);
const parameters = {
  config: connectionConfig,
  connectionProperties: {
    product: "MSJSClient",
    userAgent: "/js-amqp-common",
    version: "0.1.0"
  }
};
export const connectionContext = ConnectionContextBase.create(parameters);

/**
 * audience The entity token audience in one of the following forms:
 *
 * - **ServiceBus**
 *    - **Sender**
 *        - `"sb://<yournamespace>.servicebus.windows.net/<queue-name>"`
 *        - `"sb://<yournamespace>.servicebus.windows.net/<topic-name>"`
 *
 *    - **Receiver**
 *         - `"sb://<yournamespace>.servicebus.windows.net/<queue-name>"`
 *         - `"sb://<yournamespace>.servicebus.windows.net/<topic-name>"`
 *
 *    - **ManagementClient**
 *         - `"sb://<your-namespace>.servicebus.windows.net/<queue-name>/$management"`.
 *         - `"sb://<your-namespace>.servicebus.windows.net/<topic-name>/$management"`.
 *
 * - **EventHubs**
 *     - **Sender**
 *          - `"sb://<yournamespace>.servicebus.windows.net/<hubName>"`
 *          - `"sb://<yournamespace>.servicebus.windows.net/<hubName>/Partitions/<partitionId>"`.
 *
 *     - **Receiver**
 *         - `"sb://<your-namespace>.servicebus.windows.net/<event-hub-name>/ConsumerGroups/<consumer-group-name>/Partitions/<partition-id>"`.
 *
 *     - **ManagementClient**
 *         - `"sb://<your-namespace>.servicebus.windows.net/<event-hub-name>/$management"`.
 */
export async function authenticate(audience, closeConnection = false) {
  await connectionContext.cbsSession.init();
  const tokenObject = await connectionContext.tokenProvider.getToken(audience);
  const result = await connectionContext.cbsSession.negotiateClaim(audience, tokenObject);
  console.log(`Result is: ${result}`);
  if (closeConnection) {
    await connectionContext.connection.close();
    console.log("Successfully closed the connection.");
  }
  return result;
}

//Audience is for an EventHub or ServiceBus sender.
// You can uncomment the following line and just run this sample, if required.
// authenticate(`${config.endpoint}${path}`).catch((err) => console.log(err));
```

## 例2 - 发送信息

在上述cbs auth样本的基础上,在认证后,我们可以向EventHub或ServiceBus发送消息.

```js
const dotenv = require("dotenv");
dotenv.config(); // Optional for loading environment configuration from a .env (config) file
const { Sender, SenderOptions, EventContext, Message, Delivery } = require("rhea-promise");
const { authenticate, connectionContext, connectionConfig, path } = require("./cbsAuth");

async function main() {
  await authenticate(`${connectionConfig.endpoint}${path}`);
  const senderName = "sender-1";
  const senderOptions = {
    name: senderName,
    target: {
      // Address for EventHub Sender, it can be "<EventHubName>" or "<EventHubName>/Partitions/<PartitionId>"
      // For ServiceBus Queue, it will be "<QueueName>"
      address: `${path}`
    },
    onError: (context) => {
      const senderError = context.sender && context.sender.error;
      if (senderError) {
        console.log(
          ">>>>> [%s] An error occurred for sender '%s': %O.",
          connectionContext.connection.id,
          senderName,
          senderError
        );
      }
    },
    onSessionError: (context) => {
      const sessionError = context.session && context.session.error;
      if (sessionError) {
        console.log(
          ">>>>> [%s] An error occurred for session of sender '%s': %O.",
          connectionContext.connection.id,
          senderName,
          sessionError
        );
      }
    }
  };

  const sender = await connectionContext.connection.createSender(senderOptions);
  const message = {
    body: "Hello World!!",
    message_id: "12343434343434"
  };

  const delivery = await sender.send(message);
  console.log(">>>>>[%s] Delivery id: ", connectionContext.connection.id, delivery.id);

  await sender.close();
  await connectionContext.connection.close();
}

main().catch((err) => console.log(err));
```

## 例3 - 接收信息

在认证样本的基础上,后认证可以接收来自事件Hub或ServiceBus的信息.

```js
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

const dotenv = require("dotenv");
dotenv.config(); // Optional for loading environment configuration from a .env (config) file
const {
  Receiver,
  ReceiverOptions,
  EventContext,
  ReceiverEvents,
  delay,
  types
} = require("rhea-promise");
const { authenticate, connectionContext, connectionConfig, path } = require("./cbsAuth");

async function main() {
  await authenticate(`${connectionConfig.endpoint}${path}`);
  const receiverName = "receiver-1";
  const filterClause = `amqp.annotation.x-opt-enqueued-time > '${Date.now() - 3600 * 1000}'`; // Get messages from the past hour
  const receiverAddress = `${path}/ConsumerGroups/$default/Partitions/0`; // For ServiceBus "<QueueName>"
  const receiverOptions = {
    name: receiverName,
    source: {
      address: receiverAddress,
      filter: {
        // May not be required for ServiceBus. The current example is for EventHubs.
        "apache.org:selector-filter:string": types.wrap_described(filterClause, 0x468c00000004)
      }
    },
    onSessionError: (context) => {
      const sessionError = context.session && context.session.error;
      if (sessionError) {
        console.log(
          ">>>>> [%s] An error occurred for session of receiver '%s': %O.",
          connectionContext.connection.id,
          receiverName,
          sessionError
        );
      }
    }
  };

  const receiver = await connectionContext.connection.createReceiver(receiverOptions);
  receiver.on(ReceiverEvents.message, (context) => {
    console.log("Received message: %O", context.message);
  });
  receiver.on(ReceiverEvents.receiverError, (context) => {
    const receiverError = context.receiver && context.receiver.error;
    if (receiverError) {
      console.log(
        ">>>>> [%s] An error occurred for receiver '%s': %O.",
        connectionContext.connection.id,
        receiverName,
        receiverError
      );
    }
  });
  // sleeping for 2 mins to let the receiver receive messages and then closing it.
  await delay(120000);
  await receiver.close();
  await connectionContext.connection.close();
}

main().catch((err) => console.log(err));
```

## 解决问题

您可以设置以下环境变量以获取调试日志 .

-   从事件中心SDK获取调试日志

```bash
export DEBUG=azure:amqp-common*
```

-   从事件中心SDK和协议级别库获取调试日志 .

```bash
export DEBUG=azure:amqp-common*,rhea*
```

-   如果你是的话 **不感兴趣查看信件转换** (它消耗了很多控制台/磁盘空间) 然后你可以设置 `DEBUG` 环境变量如下:

```bash
export DEBUG=azure:amqp-common*,rhea*,-rhea:raw,-rhea:message,-azure:amqp-common:datatransformer
```

-   如果你只对 **错误**,然后可以设置 `DEBUG` 环境变量如下:

```bash
export DEBUG=azure-amqp-common:error,rhea-promise:error,rhea:events,rhea:frames,rhea:io,rhea:flow
```

#### 登录到文件

-   设定 `DEBUG` 环境变量,如上所示,然后将测试脚本运行如下:
    -   测试脚本的日志语句到 `out.log` sdk 的日志语句 `debug.log`。 。 。 .
        
        ```bash
        node your-test-script.js > out.log 2>debug.log
        ```
        
    -   从测试脚本记录语句, sdk 转到同一文件 `out.log` 将 stderr 重定向为 stdout( & 1), 然后将 stdout 重定向为文件 :
        
        ```bash
        node your-test-script.js >out.log 2>&1
        ```
        
    -   从测试脚本记录语句, sdk 转到同一文件 `out.log`。 。 。 .
        
        ```bash
          node your-test-script.js &> out.log
        ```
        

# 今后的步骤

请查看上面的例子部分来使用软件包 .

# 捐款

该项目欢迎各方的贡献和建议。 大多数捐款要求您同意 撰稿人许可协议(CLA)宣布,你有权并且实际上确实给了我们 有权使用您的贡献。 详情请访问 [https://cla.microsoft.com (中文(简体) )](https://cla.microsoft.com/)。 。 。 .

当您提交拉动请求时, CLA 机器人会自动确定您是否需要提供 a CLA并适当装饰公关(例如标签、评论)。 只要听从指示 由机器人提供。 你只需要用我们的CLA 一次就能完成.

该项目通过了 [Microsoft 开源行为守则](https://opensource.microsoft.com/codeofconduct/)。 。 。 . 更多信息见 [《行为守则》](https://opensource.microsoft.com/codeofconduct/faq/) 或者说 联系人 [打开码@ microsoft.com](mailto:opencode@microsoft.com) 并附上任何其他问题或评论.

## 常见问题

### @azure/amqp-common 是什么？

基于amqp的 Azure sdks 如@azure/event-hubs 的常见库\.

### 如何安装 @azure/amqp-common？

在项目目录运行 npm install @azure/amqp-common，或使用 pnpm add / yarn add / bun add。

### @azure/amqp-common 支持 TypeScript 吗？

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

### @azure/amqp-common 支持 ESM 还是 CommonJS？

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

### @azure/amqp-common 可以商用吗？

@azure/amqp-common 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @azure/amqp-common 的下载量有多少？

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

### @azure/amqp-common 还在维护吗？

最新版本 1\.0\.0-preview\.17 发布于 2020/09/12（6 年前）；至今共发布 28 个版本，其中过去 12 个月发布了 0 个；首次发布于 2018/09/13。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

