Azure Service Bus client library for JavaScript - version 7.10.0

Azure Service Bus は、Microsoft の信頼性の高いクラウド メッセージング サービスです。

アプリケーションでクライアント ライブラリ @azure/service-bus を使用して、次の操作を行います

  • Azure Service Bus キューまたはトピックへのメッセージの送信
  • Azure Service Bus キューまたはサブスクリプションからメッセージを受信する
  • Azure Service Bus 名前空間のキュー/トピック/サブスクリプション/ルールを作成/取得/削除/更新/一覧表示します。

@azure/service-busバージョン7のリソース:

主要なリンク:

注: バージョン 1.1.10 以前を使用していて、このパッケージの最新バージョンに移行する場合は、Service Bus V1 から Service Bus V7 への移行ガイドをご覧ください

作業の開始

パッケージをインストールする

npm を使用して、Azure Service Bus クライアント ライブラリの最新バージョンをインストールします。

npm install @azure/service-bus

現在サポートされている環境

Prerequisites

TypeScript の構成

TypeScript ユーザーには、Node 型の定義がインストールされている必要があります。

npm install @types/node

また、tsconfig.jsonで compilerOptions.allowSyntheticDefaultImports を有効にする必要があります。 compilerOptions.esModuleInteropを有効にした場合、allowSyntheticDefaultImports は既定で有効になっています。 詳細については、TypeScript のコンパイラ オプション ハンドブックの を参照してください。

JavaScript バンドル

ブラウザーでこのクライアント ライブラリを使用するには、まず、バンドルを使用する必要があります。 これを行う方法の詳細については、バンドルドキュメントを参照してください。

そこで説明されているものに加えて、このライブラリは、ブラウザーで適切に動作するために、次のNodeJSコア組み込みモジュール用の追加のポリフィルも必要です。

  • buffer
  • os
  • path
  • process

Webpackとのバンドル

Webpack v5を使用している場合は、次の開発依存関係をインストールできます

  • npm install --save-dev os-browserify path-browserify

次に、以下を webpack.config.js に追加します

 const path = require("path");
+const webpack = require("webpack");

 module.exports = {
   entry: "./src/index.ts",
@@ -12,8 +13,21 @@ module.exports = {
       },
     ],
   },
+  plugins: [
+    new webpack.ProvidePlugin({
+      process: "process/browser",
+    }),
+    new webpack.ProvidePlugin({
+      Buffer: ["buffer", "Buffer"],
+    }),
+  ],
   resolve: {
     extensions: [".ts", ".js"],
+    fallback: {
+      buffer: require.resolve("buffer/"),
+      os: require.resolve("os-browserify"),
+      path: require.resolve("path-browserify"),
+    },
   },

ロールアップによるバンドル

Rollup Bundler を使用している場合は、次の開発依存関係をインストールします

  • npm install --save-dev @rollup/plugin-commonjs @rollup/plugin-inject @rollup/plugin-node-resolve

次に、次のものを rollup.config.js に含めます

+import nodeResolve from "@rollup/plugin-node-resolve";
+import cjs from "@rollup/plugin-commonjs";
+import shim from "rollup-plugin-shim";
+import inject from "@rollup/plugin-inject";

export default {
  // other configs
  plugins: [
+    shim({
+      fs: `export default {}`,
+      net: `export default {}`,
+      tls: `export default {}`,
+      path: `export default {}`,
+      dns: `export function resolve() { }`,
+    }),
+    nodeResolve({
+      mainFields: ["module", "browser"],
+      preferBuiltins: false,
+    }),
+    cjs(),
+    inject({
+      modules: {
+        Buffer: ["buffer", "Buffer"],
+        process: "process",
+      },
+      exclude: ["./**/package.json"],
+    }),
  ]
};

ポリフィルの使用方法の詳細については、お気に入りのバンドラーのドキュメントを参照してください。

React Native のサポート

ブラウザと同様に、React Native はこの SDK ライブラリで使用される一部の JavaScript API をサポートしていないため、ポリフィルを提供する必要があります。 詳細については、 Expo を使用した Messaging React Native サンプル を参照してください。

クライアントを認証する

Service Bus との対話は、 ServiceBusClient クラスのインスタンスから始まります。 Service Bus への認証は、接続文字列または Azure Active Directory 資格情報を使用して行うことができます。

接続文字列の使用

このメソッドは、接続文字列を Service Bus インスタンスに取得します。 接続文字列は、Azure portal から取得できます。

import { ServiceBusClient } from "@azure/service-bus";

const serviceBusClient = new ServiceBusClient("<connectionString>");

このコンストラクターの詳細については、 API ドキュメントを参照してください。

Azure Active Directory 資格情報の使用

Azure Active Directory での認証では、 Azure ID ライブラリが使用されます。

次の例では、 ライブラリから利用可能な多くの資格情報プロバイダーの 1 つである @azure/identity を使用しています。

import { DefaultAzureCredential } from "@azure/identity";
import { ServiceBusClient } from "@azure/service-bus";

const fullyQualifiedNamespace = "<name-of-service-bus-namespace>.servicebus.windows.net";
const credential = new DefaultAzureCredential();
const serviceBusClient = new ServiceBusClient(fullyQualifiedNamespace, credential);

注: AAD に対して TokenCredential インターフェイスの独自の実装を使用している場合は、service-bus の "スコープ" を次のように設定して、適切なトークンを取得します。

["https://servicebus.azure.net//user_impersonation"];

このコンストラクターの詳細については、API ドキュメントを参照してください

重要な概念

ServiceBusClientを初期化したら、Service Bus 名前空間内で次のリソースを操作できます。

  • キュー: メッセージの送受信を許可します。 ポイントツーポイント通信によく使用されます。
  • トピック: キューとは対照的に、トピックはパブリッシュ/サブスクライブのシナリオに適しています。 トピックは送信できますが、消費するにはサブスクリプションが必要であり、サブスクリプションは並行して複数存在できます。
  • サブスクリプション: トピックから消費するメカニズム。 各サブスクリプションは独立しており、トピックに送信された各メッセージのコピーを受け取ります。 ルールとフィルターを使用すると、特定のサブスクリプションで受信するメッセージを調整できます。

これらのリソースの詳細については、「 Azure Service Bus とは」を参照してください。

これらのリソースを操作するには、次の SDK の概念に精通している必要があります。

キュー、トピック、およびサブスクリプションは、このライブラリを使用する前に作成する必要があることに注意してください。

例示

次のセクションでは、Azure Service Bus を使用した一般的なタスクの一部をカバーするコード スニペットを提供します

メッセージを送信する

ServiceBusClientクラスのインスタンスを作成したら、メッセージServiceBusSenderに使用できるcreateSenderメソッドを使用してを取得できます。

import { DefaultAzureCredential } from "@azure/identity";
import { ServiceBusClient } from "@azure/service-bus";

const fullyQualifiedNamespace = "<name-of-service-bus-namespace>.servicebus.windows.net";
const credential = new DefaultAzureCredential();
const serviceBusClient = new ServiceBusClient(fullyQualifiedNamespace, credential);

const sender = serviceBusClient.createSender("my-queue");

const messages = [
  { body: "Albert Einstein" },
  { body: "Werner Heisenberg" },
  { body: "Marie Curie" },
  { body: "Steven Hawking" },
  { body: "Isaac Newton" },
  { body: "Niels Bohr" },
  { body: "Michael Faraday" },
  { body: "Galileo Galilei" },
  { body: "Johannes Kepler" },
  { body: "Nikolaus Kopernikus" },
];

// sending a single message
await sender.sendMessages(messages[0]);

// sending multiple messages in a single call
// this will fail if the messages cannot fit in a batch
await sender.sendMessages(messages);

// Sends multiple messages using one or more ServiceBusMessageBatch objects as required
let batch = await sender.createMessageBatch();

for (let i = 0; i < messages.length; i++) {
  const message = messages[i];
  if (!batch.tryAddMessage(message)) {
    // Send the current batch as it is full and create a new one
    await sender.sendMessages(batch);
    batch = await sender.createMessageBatch();

    if (!batch.tryAddMessage(messages[i])) {
      throw new Error("Message too big to fit in a batch");
    }
  }
}
// Send the batch
await sender.sendMessages(batch);

メッセージを受信する

ServiceBusClientクラスのインスタンスを作成したら、ServiceBusReceiver メソッドを使用してを取得できます。

import { DefaultAzureCredential } from "@azure/identity";
import { ServiceBusClient } from "@azure/service-bus";

const fullyQualifiedNamespace = "<name-of-service-bus-namespace>.servicebus.windows.net";
const credential = new DefaultAzureCredential();
const serviceBusClient = new ServiceBusClient(fullyQualifiedNamespace, credential);

const receiver = serviceBusClient.createReceiver("my-queue");

2つの receiveModeが利用可能です。

  • "peekLock" - peekLock モードでは、キューで指定された期間、受信者はメッセージをロックします。
  • "receiveAndDelete" - receiveAndDelete モードでは、メッセージは受信時に Service Bus から削除されます。

オプションで receiveMode が指定されていない場合、デフォルトは "peekLock" モードになります。 「peekLock」モードで受信した メッセージを決済 することもできます。

このレシーバーは、次の 3 つの方法のいずれかでメッセージを受信できます。

メッセージの配列を取得する

メッセージの配列に解決される promise を返す receiveMessages 関数を使用します。

import { DefaultAzureCredential } from "@azure/identity";
import { ServiceBusClient } from "@azure/service-bus";

const fullyQualifiedNamespace = "<name-of-service-bus-namespace>.servicebus.windows.net";
const credential = new DefaultAzureCredential();
const serviceBusClient = new ServiceBusClient(fullyQualifiedNamespace, credential);

const receiver = serviceBusClient.createReceiver("my-queue");

const myMessages = await receiver.receiveMessages(10);

メッセージハンドラを使用したサブスクライブ

subscribe メソッドを使用してメッセージハンドラを設定し、必要なだけ実行できるようにします。

完了したら、 receiver.close() に電話して、これ以上メッセージの受信を停止します。

import { DefaultAzureCredential } from "@azure/identity";
import { ServiceBusClient } from "@azure/service-bus";

const fullyQualifiedNamespace = "<name-of-service-bus-namespace>.servicebus.windows.net";
const credential = new DefaultAzureCredential();
const serviceBusClient = new ServiceBusClient(fullyQualifiedNamespace, credential);

const receiver = serviceBusClient.createReceiver("my-queue");

const myMessageHandler = async (message) => {
  // your code here
  console.log(`message.body: ${message.body}`);
};
const myErrorHandler = async (args) => {
  console.log(
    `Error occurred with ${args.entityPath} within ${args.fullyQualifiedNamespace}: `,
    args.error,
  );
};
receiver.subscribe({
  processMessage: myMessageHandler,
  processError: myErrorHandler,
});

非同期イテレータを使用する

getMessageIterator を使用して、メッセージに対する非同期イテレータを取得します

import { DefaultAzureCredential } from "@azure/identity";
import { ServiceBusClient } from "@azure/service-bus";

const fullyQualifiedNamespace = "<name-of-service-bus-namespace>.servicebus.windows.net";
const credential = new DefaultAzureCredential();
const serviceBusClient = new ServiceBusClient(fullyQualifiedNamespace, credential);

const receiver = serviceBusClient.createReceiver("my-queue");

for await (const message of receiver.getMessageIterator()) {
  // your code here
}

メッセージを解決する

メッセージを受信したら、メッセージの決済方法に基づいて、受信者に completeMessage()、 abandonMessage()、 deferMessage() 、または deadLetterMessage() を呼び出すことができます。

詳細については、「受信メッセージのセトリング」を参照してください

配信不能キュー

配信不能キューは サブキューです。 各キューまたはサブスクリプションには、独自の配信不能キューがあります。 デッドレターキューには、( receiver.deadLetterMessage() によって) 明示的にデッドレター化されたメッセージ、または最大配信数を超えたメッセージが格納されます。

配信不能サブキューの受信側を作成することは、サブスクリプションまたはキューの受信側を作成することと似ています。

import { DefaultAzureCredential } from "@azure/identity";
import { ServiceBusClient } from "@azure/service-bus";

const fullyQualifiedNamespace = "<name-of-service-bus-namespace>.servicebus.windows.net";
const credential = new DefaultAzureCredential();
const serviceBusClient = new ServiceBusClient(fullyQualifiedNamespace, credential);

// To receive from a queue's dead letter sub-queue
const deadLetterReceiverForQueue = serviceBusClient.createReceiver("queue", {
  subQueueType: "deadLetter",
});

// To receive from a subscription's dead letter sub-queue
const deadLetterReceiverForSubscription = serviceBusClient.createReceiver("topic", "subscription", {
  subQueueType: "deadLetter",
});

// Dead letter receivers work like any other receiver connected to a queue
// ex:
const messages = await deadLetterReceiverForQueue.receiveMessages(5);

for (const message of messages) {
  console.log(`Dead lettered message: ${message.body}`);
}

デッドレターキューをより詳細に示す完全なサンプル:

セッションを使用したメッセージの送信

セッションを使用するには、セッションが有効なキューまたはサブスクリプションを作成する必要があります。 この機能をポータルで構成する方法の詳細については、 こちらを参照してください。

セッションにメッセージを送信するには、 ServiceBusClient を使用して 、createSender を使用して送信者を作成します。

メッセージを送信するときは、メッセージ内の sessionId プロパティを設定して、メッセージが適切なセッションに届くようにします。

import { DefaultAzureCredential } from "@azure/identity";
import { ServiceBusClient } from "@azure/service-bus";

const fullyQualifiedNamespace = "<name-of-service-bus-namespace>.servicebus.windows.net";
const credential = new DefaultAzureCredential();
const serviceBusClient = new ServiceBusClient(fullyQualifiedNamespace, credential);

const sender = serviceBusClient.createSender("my-session-queue");
await sender.sendMessages({
  body: "my-message-body",
  sessionId: "my-session",
});

セッションの仕組みについては、 こちらをご覧ください。

セッションからのメッセージの受信

セッションを使用するには、セッションが有効なキューまたはサブスクリプションを作成する必要があります。 この機能をポータルで構成する方法の詳細については、 こちらを参照してください。

セッションが有効になっていないキューやサブスクリプションとは異なり、セッションからいつでも読み取れるのは 1 つの受信者だけです。 これは、Service Bus によって処理されるセッションを ロック することによって強制されます。 概念的には、これは peekLock モードを使用する場合のメッセージロックの動作と似ています - メッセージ(またはセッション)がロックされているとき、受信者はそれに排他的にアクセスできます。

セッションを開いてロックするには、 ServiceBusClient のインスタンスを使用して SessionReceiver を作成します。

開くセッションを選択するには、次の 2 つの方法があります。

  1. 指定したセッションをロックする sessionIdを指定します。

    const receiver = await serviceBusClient.acceptSession("my-session-queue", "my-session");
    
  2. セッション ID は指定しないでください。この場合、Service Bus は、まだロックされていない次に使用可能なセッションを検索します。

    const receiver = await serviceBusClient.acceptNextSession("my-session-queue");
    

    セッションの名前は、sessionIdの SessionReceiver プロパティで確認できます。 オプションで receiveMode が指定されていない場合、デフォルトは "peekLock" モードになります。 「peekLock」モードで受信した メッセージを決済 することもできます。

受信者が作成されたら、次の 3 つの方法からメッセージを受信できます。

セッションの仕組みについては、 こちらをご覧ください。

メッセージセッションを一覧表示

どのセッションがキューやサブスクリプションでアクティブなメッセージやセッション状態を持っているかを知りたい場合は、 listMessageSessions()を使用します。

import { DefaultAzureCredential } from "@azure/identity";
import { ServiceBusClient } from "@azure/service-bus";

const fullyQualifiedNamespace = "<name-of-service-bus-namespace>.servicebus.windows.net";
const credential = new DefaultAzureCredential();
const serviceBusClient = new ServiceBusClient(fullyQualifiedNamespace, credential);

// List all sessions with active messages or session state in a queue
for await (const sessionId of serviceBusClient.listMessageSessions("my-session-queue")) {
  console.log("Session ID:", sessionId);
}

// List sessions in a subscription
for await (const sessionId of serviceBusClient.listMessageSessions("my-topic", "my-subscription")) {
  console.log("Session ID:", sessionId);
}

// List only sessions whose stored session state was set or updated in the last seven days
const sessionStateUpdatedAfter = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
for await (const sessionId of serviceBusClient.listMessageSessions("my-session-queue", {
  sessionStateUpdatedAfter,
})) {
  console.log("Recently updated session ID:", sessionId);
}

Service Bus 名前空間のリソースを管理する

ServiceBusAdministrationClient では、エンティティ (キュー、トピック、サブスクリプション) およびサブスクリプションのルールに対する CRUD 操作を使用して名前空間を管理できます。

  • Service Bus 接続文字列と、@azure/identity と同様に ServiceBusClient の AAD 資格情報を使用した認証をサポートします。

注: Service Bus では、名前空間の CORS ルールの設定がまだサポートされていないため、Web セキュリティを無効にしないとブラウザーで ServiceBusAdministrationClient は機能しません。 詳細については、 こちらを参照してください。

import { ServiceBusAdministrationClient } from "@azure/service-bus";

const queueName = "my-session-queue";

// Get the connection string from the portal
// OR
// use the token credential overload, provide the host name of your Service Bus instance and the AAD credentials from the @azure/identity library
const serviceBusAdministrationClient = new ServiceBusAdministrationClient("<connectionString>");

// Similarly, you can create topics and subscriptions as well.
const createQueueResponse = await serviceBusAdministrationClient.createQueue(queueName);
console.log("Created queue with name - ", createQueueResponse.name);

const queueRuntimeProperties =
  await serviceBusAdministrationClient.getQueueRuntimeProperties(queueName);
console.log(`Number of messages in the queue = ${queueRuntimeProperties.totalMessageCount}`);

// Topic runtime properties additionally report the total number of SQL and correlation filters
// across all of the topic's subscriptions. These counts are served by the 2024-05 service API
// version and later; on an older version they are `undefined`.
const topicName = "my-topic";
const subscriptionName = "my-subscription";
await serviceBusAdministrationClient.createTopic(topicName);
// A new subscription carries a default rule with a SQL TrueFilter. Adding a correlation rule
// gives the topic one of each, so the counts below aggregate across the subscription's rules.
await serviceBusAdministrationClient.createSubscription(topicName, subscriptionName);
await serviceBusAdministrationClient.createRule(
  topicName,
  subscriptionName,
  "my-correlation-rule",
  { correlationId: "my-correlation-id" },
);
const topicRuntimeProperties =
  await serviceBusAdministrationClient.getTopicRuntimeProperties(topicName);
console.log(`SQL filter count = ${topicRuntimeProperties.sqlFilterCount}`);
console.log(`Correlation filter count = ${topicRuntimeProperties.correlationFilterCount}`);

await serviceBusAdministrationClient.deleteTopic(topicName);
await serviceBusAdministrationClient.deleteQueue(queueName);

Troubleshooting

問題の診断を開始するための最初のステップを次に示します。 詳細については、 Service Bus トラブルシューティング ガイドを参照してください。

AMQP の依存関係

Service Bus ライブラリは、接続の管理、AMQP プロトコルを介したメッセージの送受信を rhea-promise ライブラリに依存しています。

Logging

このライブラリを使用する場合は、次の環境変数を設定してデバッグ ログを取得できます。

  • Service Bus SDK からのデバッグ ログの取得
export DEBUG=azure*
  • Service Bus SDK とプロトコル レベル ライブラリからデバッグ ログを取得する。
export DEBUG=azure*,rhea*
  • メッセージ変換 (コンソール/ディスク・スペースを大量に消費する) を表示したくない場合は 、次のように DEBUG 環境変数を設定できます。
export DEBUG=azure*,rhea*,-rhea:raw,-rhea:message,-azure:core-amqp:datatransformer
  • エラーのみに関心がある場合は、次のようにDEBUG環境変数を設定できます。
export DEBUG=azure:service-bus:error,azure:core-amqp:error,rhea-promise:error,rhea:events,rhea:frames,rhea:io,rhea:flow

ファイルへのログ記録

  1. DEBUG環境変数を上記のように設定します
  2. 次のようにテストスクリプトを実行します。
  • テスト スクリプトからステートメントをログに記録すると、out.log に移動し、sdk からステートメントをログに記録すると、debug.logに移動します。
    node your-test-script.js > out.log 2>debug.log
    
  • テスト スクリプトと sdk からステートメントをログに記録すると、stderr を stdout (&1) にリダイレクトして同じファイル out.log に移動し、stdout をファイルにリダイレクトします。
    node your-test-script.js >out.log 2>&1
    
  • テスト スクリプトと SDK からステートメントをログに記録すると、同じファイル out.logに移動します。
      node your-test-script.js &> out.log
    

次のステップ

このライブラリを使用して Service Bus キュー、トピック、およびサブスクリプションとの間でメッセージを送受信する方法の詳細な例については、samples ディレクトリを参照してください。

Contributing

このライブラリに貢献したい場合は、コードのビルドやテスト方法について詳しく知るために、contributing guideをお読みください。