Azure Storage Queue は、アプリケーション コンポーネント間のクラウド メッセージングを提供します。 アプリケーションをスケール用に設計する場合、アプリケーション コンポーネントは個別にスケーリングできるように分離されることがよくあります。 Queue Storage は、アプリケーション コンポーネントがクラウド、デスクトップ、オンプレミス サーバー、モバイル デバイスのどちらで実行されているかに関係なく、アプリケーション コンポーネント間の通信に非同期メッセージングを提供します。 キュー ストレージでは、非同期タスクの管理とプロセスワーク フローの構築もサポートされています。
このプロジェクトは、Azure Storage Queue サービスを簡単に使用できる JavaScript のクライアント ライブラリを提供します。
このパッケージのクライアント ライブラリを使用して、次の操作を行います。
- キュー サービスのプロパティを取得/設定する
- キューの作成/一覧表示/削除
- キュー メッセージの送受信/ピーク/クリア/更新/削除
主要なリンク:
- ソースコード
- パッケージ (npm)
- API リファレンス ドキュメント
- 製品ドキュメント
- Samples
- Azure Storage Queue REST API を
する
作業の開始
現在サポートされている環境
- Node.js の LTS バージョンを
する - Safari、Chrome、Edge、Firefox の最新バージョン。
詳細については、 サポート ポリシー を参照してください。
Prerequisites
パッケージをインストールする
JavaScript 用の Azure Storage Queue クライアント ライブラリをインストールする推奨される方法は、npm パッケージ マネージャーを使用することです。 ターミナル ウィンドウに次のように入力します。
npm install @azure/storage-queue
クライアントを認証する
Azure Storage では、いくつかの認証方法がサポートされています。 Azure Queue Storage サービスと対話するには、ストレージ クライアントのインスタンス (QueueServiceClient や QueueClient など) を作成する必要があります。 認証の詳細については、
Azure Active Directory
Azure Queue Storage サービスでは、Azure Active Directory を使用して API への要求を認証できます。
@azure/identity パッケージには、アプリケーションでこれを行うために使用できるさまざまな資格情報の種類が用意されています。 作業を開始するための詳細とサンプルについては、
Compatibility
このライブラリは、Node.js とブラウザーと互換性があり、LTS Node.js バージョン (>=8.16.0) と Chrome、Firefox、Edge の最新バージョンに対して検証されます。
Web ワーカー
このライブラリでは、ブラウザーで使用する場合、特定の DOM オブジェクトをグローバルに使用できる必要があります。Web ワーカーは既定では使用できません。 Web ワーカーでこのライブラリを動作させるには、これらをポリフィルする必要があります。
詳細については、Web Worker で Azure SDK for JS を使用するための ドキュメントを参照してください
このライブラリは、Web ワーカーで使用するときに外部ポリフィルを読み込む必要がある次の DOM API に依存します。
Node.js とブラウザーの違い
Node.js とブラウザーのランタイムには違いがあります。 このライブラリの使用を開始するときは、
次の機能、インターフェイス、クラス、または関数は、Node.js でのみ使用できます
- アカウント名とアカウント キーに基づく共有キーの承認
StorageSharedKeyCredential
- Shared Access Signature (SAS) の生成
generateAccountSASQueryParameters()generateQueueSASQueryParameters()
JavaScript バンドル
ブラウザーでこのクライアント ライブラリを使用するには、まず、バンドルを使用する必要があります。 これを行う方法の詳細については、
CORS
ブラウザー用に開発する必要がある場合は、ストレージ アカウント クロスオリジン リソース共有 (CORS) 規則を設定する必要があります。 Azure portal と Azure Storage Explorer に移動し、ストレージ アカウントを見つけ、BLOB/キュー/ファイル/テーブル サービス用の新しい CORS ルールを作成します。
たとえば、デバッグ用に次の CORS 設定を作成できます。 ただし、運用環境の要件に合わせて設定を慎重にカスタマイズしてください。
- 許可される配信元: *
- 使用できる動詞: DELETE、GET、HEAD、MERGE、POST、OPTIONS、PUT
- 許可されるヘッダー: *
- 公開されたヘッダー: *
- 最長有効期間 (秒): 86400
重要な概念
キューは、接続されたクライアント間でメッセージを送受信するための Azure Storage Queue サービス アカウント内のデータ ストアです。
これらのサービスに関連するライブラリの主なデータ型は次のとおりです。
-
QueueServiceClientは、Azure Storage キュー サービス内の特定のストレージ アカウントへの接続 (URL 経由) を表し、そのキューを操作するための API を提供します。 これはサービスに対して認証され、QueueClientオブジェクトの作成や、サービスからのキューの作成、削除、一覧表示に使用できます。 -
QueueClientは、ストレージ アカウント内の 1 つのキューを表します。 キュー内のメッセージの送信、受信、ピークなど、キューのメッセージを操作するために使用できます。
Examples
パッケージをインポートする
クライアントを使用するには、パッケージをファイルにインポートします。
import * as AzureStorageQueue from "@azure/storage-queue";
または、必要な型のみを選択的にインポートします。
import { QueueServiceClient, StorageSharedKeyCredential } from "@azure/storage-queue";
キュー サービス クライアントを作成する
QueueServiceClient には、キュー サービスへの URL とアクセス資格情報が必要です。 また、必要に応じて、options パラメーターの一部の設定を受け入れます。
パッケージからの DefaultAzureCredential@azure/identity 使用
QueueServiceClient
をインスタンス化するための推奨される方法
セットアップ : リファレンス - クライアント アプリケーションから Azure Active Directory を使用して BLOB とキューへのアクセスを承認する - https://learn.microsoft.com/azure/storage/common/storage-auth-aad-app
新しい AAD アプリケーションを登録し、サインインしているユーザーの代わりに Azure Storage にアクセスするためのアクセス許可を付与する
- Azure Active Directory(azure-portal)に新しいアプリケーションを登録する - https://learn.microsoft.com/azure/active-directory/develop/quickstart-register-app
- [
API permissions] セクションで、[Add a permission] を選択し、[Microsoft APIs] を選択します。 -
Azure Storageを選択し、[user_impersonation] の横にあるチェックボックスをオンにして、[Add permissions] をクリックします。 これにより、アプリケーションはサインインしているユーザーの代わりに Azure Storage にアクセスできるようになります。
Azure Portal で RBAC を使用して Azure Storage Queue データへのアクセスを許可する
- BLOB とキューの RBAC ロール - https://learn.microsoft.com/azure/storage/common/storage-auth-aad-rbac-portal。
- Azure portal でストレージ アカウントに移動し、ストレージ キュー データ共同作成者の ロールを、(azure-portal のストレージ アカウントの左側のナビゲーション バーにある)
Access control (IAM)タブから登録済みの AAD アプリケーションに割り当てます。
サンプルの環境のセットアップ
- AAD アプリケーションの概要ページで、
CLIENT IDとTENANT IDをメモします。 [証明書 & シークレット] タブでシークレットを作成し、下にメモします。 - サンプルを正常に実行するために、環境変数として
AZURE_TENANT_ID、AZURE_CLIENT_ID、AZURE_CLIENT_SECRETしていることを確認します (process.env を活用できます)。
- AAD アプリケーションの概要ページで、
import { DefaultAzureCredential } from "@azure/identity";
import { QueueServiceClient } from "@azure/storage-queue";
const account = "<account>";
const credential = new DefaultAzureCredential();
const queueServiceClient = new QueueServiceClient(
`https://${account}.queue.core.windows.net`,
credential,
);
[注 - 上記の手順は Node.js専用です]
接続文字列の使用
または、完全な接続文字列を引数として使用して、QueueServiceClient 静的メソッドを使用して fromConnectionString() をインスタンス化することもできます。 (接続文字列は Azure portal から取得できます)。[NODE.JS ランタイムでのみ使用可能]
import { QueueServiceClient } from "@azure/storage-queue";
const connectionString = "<connection string>";
const queueServiceClient = QueueServiceClient.fromConnectionString(connectionString);
StorageSharedKeyCredential
または、QueueServiceClient と StorageSharedKeyCredential を引数として渡して、accountName を使用してaccountKeyをインスタンス化します。 (アカウント名とアカウント キーの値は、Azure ポータルから取得できます。[NODE.JSランタイムでのみ利用可能]
import { StorageSharedKeyCredential, QueueServiceClient } from "@azure/storage-queue";
// Enter your storage account name and shared key
const account = "<account>";
const accountKey = "<accountkey>";
// Use StorageSharedKeyCredential with storage account and account key
// StorageSharedKeyCredential is only available in Node.js runtime, not in browsers
const sharedKeyCredential = new StorageSharedKeyCredential(account, accountKey);
const queueServiceClient = new QueueServiceClient(
`https://${account}.queue.core.windows.net`,
sharedKeyCredential,
{
retryOptions: { maxTries: 4 }, // Retry options
userAgentOptions: {
userAgentPrefix: "BasicSample V10.0.0",
}, // Customized telemetry string
},
);
SAS トークンを使用する
また、共有アクセス署名 (SAS) を使用して QueueServiceClient をインスタンス化することもできます。 Azure Portal から SAS トークンを取得することも、generateAccountSASQueryParameters()を使用して SAS トークンを生成することもできます。
import { QueueServiceClient } from "@azure/storage-queue";
const account = "<account name>";
const sas = "<service Shared Access Signature Token>";
const queueServiceClient = new QueueServiceClient(
`https://${account}.queue.core.windows.net?${sas}`,
);
このアカウントのキューを一覧表示する
QueueServiceClient.listQueues() 関数を使用して、新しい for-await-of 構文でキューを反復処理します。
import { QueueServiceClient } from "@azure/storage-queue";
import { DefaultAzureCredential } from "@azure/identity";
const account = "<account>";
const queueServiceClient = new QueueServiceClient(
`https://${account}.queue.core.windows.net`,
new DefaultAzureCredential(),
);
let i = 1;
for await (const item of queueServiceClient.listQueues()) {
console.log(`Queue${i++}: ${item.name}`);
}
または、for-await-ofを使用しない場合:
import { QueueServiceClient } from "@azure/storage-queue";
import { DefaultAzureCredential } from "@azure/identity";
const account = "<account>";
const queueServiceClient = new QueueServiceClient(
`https://${account}.queue.core.windows.net`,
new DefaultAzureCredential(),
);
let i = 1;
const iterator = queueServiceClient.listQueues();
let { done, value } = await iterator.next();
while (!done) {
console.log(`Queue${i++}: ${value.name}`);
({ done, value } = await iterator.next());
}
キューの反復に関する完全なサンプルについては、 samples/v12/typescript/listQueues.tsを参照してください。
新しいキューを作成する
QueueServiceClient.getQueueClient() 関数を使用して新しいキューを作成します。
import { QueueServiceClient } from "@azure/storage-queue";
import { DefaultAzureCredential } from "@azure/identity";
const account = "<account>";
const queueServiceClient = new QueueServiceClient(
`https://${account}.queue.core.windows.net`,
new DefaultAzureCredential(),
);
const queueName = "<valid queue name>";
const queueClient = queueServiceClient.getQueueClient(queueName);
const createQueueResponse = await queueClient.create();
console.log(
`Created queue ${queueName} successfully, service assigned request Id: ${createQueueResponse.requestId}`,
);
キューにメッセージを送信する
sendMessage() を使用して、キューにメッセージを追加します。
import { QueueServiceClient } from "@azure/storage-queue";
import { DefaultAzureCredential } from "@azure/identity";
const account = "<account>";
const queueServiceClient = new QueueServiceClient(
`https://${account}.queue.core.windows.net`,
new DefaultAzureCredential(),
);
const queueName = "<valid queue name>";
const queueClient = queueServiceClient.getQueueClient(queueName);
// Send a message into the queue using the sendMessage method.
const sendMessageResponse = await queueClient.sendMessage("Hello World!");
console.log(
`Sent message successfully, service assigned message Id: ${sendMessageResponse.messageId}, service assigned request Id: ${sendMessageResponse.requestId}`,
);
メッセージをピークする
QueueClient.peekMessages() では、キューの前にある 1 つ以上のメッセージを確認できます。 この呼び出しでは、他のコードがピークされたメッセージにアクセスすることを防ぐことはありません。
import { QueueServiceClient } from "@azure/storage-queue";
import { DefaultAzureCredential } from "@azure/identity";
const account = "<account>";
const queueServiceClient = new QueueServiceClient(
`https://${account}.queue.core.windows.net`,
new DefaultAzureCredential(),
);
const queueName = "<valid queue name>";
const queueClient = queueServiceClient.getQueueClient(queueName);
const peekMessagesResponse = await queueClient.peekMessages();
console.log(`The peeked message is: ${peekMessagesResponse.peekedMessageItems[0].messageText}`);
メッセージの処理
メッセージは 2 つの手順で処理されます。
- 最初の呼び出し
queueClient.receiveMessages(). これにより、既定の 30 秒間、このキューからメッセージを読み取る他のコードからメッセージが非表示になります。 - メッセージの処理が完了したら、メッセージの
queueClient.deleteMessage()でpopReceiptを呼び出します。
ハードウェアまたはソフトウェアの障害が原因でコードがメッセージを処理できない場合、この 2 段階のプロセスにより、コードの別のインスタンスが同じメッセージを取得して再試行できるようになります。
import { QueueServiceClient } from "@azure/storage-queue";
import { DefaultAzureCredential } from "@azure/identity";
const account = "<account>";
const queueServiceClient = new QueueServiceClient(
`https://${account}.queue.core.windows.net`,
new DefaultAzureCredential(),
);
const queueName = "<valid queue name>";
const queueClient = queueServiceClient.getQueueClient(queueName);
const response = await queueClient.receiveMessages();
if (response.receivedMessageItems.length === 1) {
const receivedMessageItem = response.receivedMessageItems[0];
console.log(`Processing & deleting message with content: ${receivedMessageItem.messageText}`);
const deleteMessageResponse = await queueClient.deleteMessage(
receivedMessageItem.messageId,
receivedMessageItem.popReceipt,
);
console.log(
`Delete message successfully, service assigned request Id: ${deleteMessageResponse.requestId}`,
);
}
キューを削除する
import { QueueServiceClient } from "@azure/storage-queue";
import { DefaultAzureCredential } from "@azure/identity";
const account = "<account>";
const queueServiceClient = new QueueServiceClient(
`https://${account}.queue.core.windows.net`,
new DefaultAzureCredential(),
);
const queueName = "<valid queue name>";
const queueClient = queueServiceClient.getQueueClient(queueName);
const deleteQueueResponse = await queueClient.delete();
console.log(
`Deleted queue successfully, service assigned request Id: ${deleteQueueResponse.requestId}`,
);
単純な QueueServiceClient シナリオの完全な例は、 samples/v12/typescript/src/queueClient.tsにあります。
Troubleshooting
ログ記録を有効にすると、エラーに関する有用な情報を明らかにするのに役立つ場合があります。 HTTP 要求と応答のログを表示するには、AZURE_LOG_LEVEL 環境変数を infoに設定します。 または、setLogLevelで @azure/logger を呼び出すことによって、実行時にログを有効にすることもできます。
import { setLogLevel } from "@azure/logger";
setLogLevel("info");
次のステップ
その他のコード サンプル
Contributing
このライブラリに投稿する場合は、コードをビルドしてテストする方法の詳細については、 投稿ガイド をお読みください。
また、ストレージ ライブラリのテスト環境の設定に関する追加情報については、Storage 固有のガイドの を参照してください。
Azure SDK for JavaScript