Java 用 Azure Storage Queue クライアント ライブラリ - バージョン 12.19.1

Azure キュー ストレージは、HTTP または HTTPS を使用した認証された呼び出しを介して世界中のどこからでもアクセスできる大量のメッセージを格納するためのサービスです。 キューの 1 つのメッセージの最大サイズは 64 KB で、1 つのキューには、ストレージ アカウントの合計容量の上限に達するまで、数百万のメッセージを格納できます。

ソース コード | API リファレンス ドキュメント | 製品ドキュメント | サンプル

作業の開始

前提条件

パッケージを組み込む

BOM ファイルを含める

GA バージョンのライブラリに依存するには、azure-sdk-bom をプロジェクトに含めてください。 次のスニペットでは、{bom_version_to_target} プレースホルダーをバージョン番号に置き換えます。 BOM の詳細については、 AZURE SDK BOM README に関するページを参照してください。

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>com.azure</groupId>
            <artifactId>azure-sdk-bom</artifactId>
            <version>{bom_version_to_target}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

次に、バージョン タグのない依存関係セクションに直接依存関係を含めます。

<dependencies>
  <dependency>
    <groupId>com.azure</groupId>
    <artifactId>azure-storage-queue</artifactId>
  </dependency>
</dependencies>

直接依存関係を含める

BOM に存在しない特定のバージョンのライブラリに依存する場合は、次のように直接依存関係をプロジェクトに追加します。

<dependency>
  <groupId>com.azure</groupId>
  <artifactId>azure-storage-queue</artifactId>
  <version>12.19.1</version>
</dependency>

ストレージ アカウントを作成する

ストレージ アカウントを作成するには、Azure Portal または Azure CLI を使用できます。

az storage account create \
    --resource-group <resource-group-name> \
    --name <storage-account-name> \
    --location <location>

クライアントを認証する

ストレージ サービス (Blob、Queue、Message、MessageId、File) と対話するには、Service Client クラスのインスタンスを作成する必要があります。 これを可能にするには、ストレージ アカウントのアカウント SAS (共有アクセス署名) 文字列が必要です。 詳細については、SAS トークンに関するページを参照してください

資格情報の取得

  • SAS トークン

a. 次の Azure CLI スニペットを使用して、ストレージ アカウントから SAS トークンを取得します。

az storage queue generate-sas
    --name {queue name}
    --expiry {date/time to expire SAS token}
    --permission {permission to grant}
    --connection-string {connection string of the storage account}
CONNECTION_STRING=<connection-string>
az storage queue generate-sas
    --name javasdksas
    --expiry 2019-06-05
    --permission rpau
    --connection-string $CONNECTION_STRING

b. または、Azure Portal からアカウント SAS トークンを取得します。

Go to your storage account -> Shared access signature -> Click on Generate SAS and connection string (after setup)
  • 共有キーの資格情報

a. アカウント名とアカウント キーを使用します。 アカウント名は、ストレージ アカウント名です。

// Here is where we get the key
Go to your storage account -> Access keys -> Key 1/ Key 2 -> Key

b. 接続文字列を使用する

// Here is where we get the key
Go to your storage account -> Access Keys -> Keys 1/ Key 2 -> Connection string

主要な概念

URL 形式

キューは、次の URL 形式を使用してアドレス指定できます。次の URL は、図のキューをアドレス指定します。 https://myaccount.queue.core.windows.net/images-to-download

リソースの URI の構文

ストレージ アカウントの場合、キュー操作のベース URI にはアカウントの名前だけが含まれます。

https://myaccount.queue.core.windows.net

キューの場合、キュー操作のベース URI にはアカウントの名前とキューの名前が含まれます。

https://myaccount.queue.core.windows.net/myqueue

例外処理

以下の queueServiceClientQueue Service Client セクションから生成された を使用します。

String queueServiceURL = String.format("https://%s.queue.core.windows.net", ACCOUNT_NAME);
QueueServiceClient queueServiceClient = new QueueServiceClientBuilder().endpoint(queueServiceURL)
    .sasToken(SAS_TOKEN).buildClient();
try {
    queueServiceClient.createQueue("myQueue");
} catch (QueueStorageException e) {
    logger.error("Failed to create a queue with error code: " + e.getErrorCode());
}

キュー名

アカウント内のすべてのキューには一意の名前を付ける必要があります。 キュー名は有効な DNS 名である必要があり、1 度作成したら変更することはできません。 キュー名は、次の規則に従う必要があります。

  1. キュー名は、文字または数字で始まり、文字、数字、またはダッシュ (-) 文字だけを使用できます。
  2. キュー名の最初と最後の文字は、英数字にする必要があります。 ダッシュ (-) 文字は最初の文字にすることも最後の文字にすることもできません。 キュー名で、ダッシュ文字を連続して使用することはできません。
  3. キュー名のすべての文字は、小文字にする必要があります。
  4. キュー名の長さは 3 ~ 63 文字にする必要があります。

キュー サービス

キュー サービスは、ストレージ アカウント内のキューに対して操作を実行し、キューのプロパティを管理します。

キュー サービス クライアント

クライアントは、キュー サービスとの対話、キューの作成または削除、Queue プロパティの取得と設定、アカウント内のキューの一覧表示、キュー統計の取得を実行します。 非同期、、 QueueServiceAsyncClientおよび同期の クライアントが SDK に存在し、 QueueClientアプリケーションのユース ケースに基づいてクライアントを選択できます。 SASToken の値を取得したら、 を${SASToken}使用してキュー サービス クライアントを${accountName}作成できます。

String queueServiceURL = String.format("https://%s.queue.core.windows.net", ACCOUNT_NAME);
QueueServiceClient queueServiceClient = new QueueServiceClientBuilder().endpoint(queueServiceURL)
    .sasToken(SAS_TOKEN).buildClient();

QueueClient newQueueClient = queueServiceClient.createQueue("myQueue");

または

String queueServiceAsyncURL = String.format("https://%s.queue.core.windows.net/", ACCOUNT_NAME);
QueueServiceAsyncClient queueServiceAsyncClient = new QueueServiceClientBuilder().endpoint(queueServiceAsyncURL)
    .sasToken(SAS_TOKEN).buildAsyncClient();
queueServiceAsyncClient.createQueue("newAsyncQueue").subscribe(result -> {
    // do something when new queue created
}, error -> {
    // do something if something wrong happened
}, () -> {
    // completed, do something
});

キュー

Azure キュー ストレージは、HTTP または HTTPS を使用した認証された呼び出しを介して世界中のどこからでもアクセスできる大量のメッセージを格納するためのサービスです。 キューの 1 つのメッセージの最大サイズは 64 KB で、1 つのキューには、ストレージ アカウントの合計容量の上限に達するまで、数百万のメッセージを格納できます。

QueueClient

SASToken の値を取得したら、 を使用してキュー サービス クライアントを${accountName}${queueName}${SASToken}作成できます。

String queueURL = String.format("https://%s.queue.core.windows.net/%s", ACCOUNT_NAME, queueName);
QueueClient queueClient = new QueueClientBuilder().endpoint(queueURL).sasToken(SAS_TOKEN).buildClient();

// metadata is map of key-value pair
queueClient.createWithResponse(metadata, Duration.ofSeconds(30), Context.NONE);

または

// Only one "?" is needed here. If the sastoken starts with "?", please removing one "?".
String queueAsyncURL = String.format("https://%s.queue.core.windows.net/%s?%s", ACCOUNT_NAME, queueAsyncName,
    SAS_TOKEN);
QueueAsyncClient queueAsyncClient = new QueueClientBuilder().endpoint(queueAsyncURL).buildAsyncClient();
queueAsyncClient.createWithResponse(metadata).subscribe(result -> {
    // do something when new queue created
}, error -> {
    // do something if something wrong happened
}, () -> {
    // completed, do something
});

次のセクションでは、次のような最も一般的な Configuration Service タスクの一部をカバーするいくつかのコード スニペットを示します。

クライアントを構築する

QueueService または Queue Client を構築する方法は 2 つあります。 ここでは、queueServiceClient を例として示します。 queueClient にも同じことが当てはまります。

最初に、完全な URL/エンドポイントからクライアントをビルドします (例: queueName、SASToken など)

// Only one "?" is needed here. If the sastoken starts with "?", please removing one "?".
String queueServiceURL = String.format("https://%s.queue.core.windows.net/?%s", ACCOUNT_NAME, SAS_TOKEN);
QueueServiceClient queueServiceClient = new QueueServiceClientBuilder().endpoint(queueServiceURL).buildClient();

または

資格情報として を使用して ${SASToken} 、ビルダーから queueServiceClient をビルドできます。

String queueServiceURL = String.format("https://%s.queue.core.windows.net", ACCOUNT_NAME);
QueueServiceClient queueServiceClient = new QueueServiceClientBuilder().endpoint(queueServiceURL)
        .sasToken(SAS_TOKEN).buildClient();

キューを作成する

資格情報として を使用して、ストレージ アカウントにキューを ${SASToken} 作成します。 キューの作成に失敗した場合、StorageException をスローします。

String queueServiceURL = String.format("https://%s.queue.core.windows.net", ACCOUNT_NAME);
QueueServiceClient queueServiceClient = new QueueServiceClientBuilder().endpoint(queueServiceURL)
    .sasToken(SAS_TOKEN).buildClient();

QueueClient newQueueClient = queueServiceClient.createQueue("myQueue");

キューを削除する

資格情報として を使用して、ストレージ アカウント内のキューを ${SASToken} 削除します。 キューの削除に失敗した場合、StorageException をスローします。

String queueServiceURL = String.format("https://%s.queue.core.windows.net", ACCOUNT_NAME);
QueueServiceClient queueServiceClient = new QueueServiceClientBuilder().endpoint(queueServiceURL)
        .sasToken(SAS_TOKEN).buildClient();

queueServiceClient.deleteQueue("myqueue");

アカウント内のキューを一覧表示する

資格情報として を使用して、アカウント内のすべてのキューを ${SASToken} 一覧表示します。

String queueServiceURL = String.format("https://%s.queue.core.windows.net", ACCOUNT_NAME);
QueueServiceClient queueServiceClient = new QueueServiceClientBuilder().endpoint(queueServiceURL)
        .sasToken(SAS_TOKEN).buildClient();
// @param marker: Starting point to list the queues
// @param options: Filter for queue selection
// @param timeout: An optional timeout applied to the operation.
// @param context: Additional context that is passed through the Http pipeline during the service call.
queueServiceClient.listQueues(options, timeout, context).stream().forEach(queueItem ->
    System.out.printf("Queue %s exists in the account.", queueItem.getName()));

キュー アカウントのプロパティを取得する

Storage Analyticsおよび CORS (クロスオリジン リソース共有) ルールのプロパティを含む、アカウント内のキュー プロパティを取得します。

資格情報として を使用 ${SASToken} します。

String queueServiceURL = String.format("https://%s.queue.core.windows.net", ACCOUNT_NAME);
QueueServiceClient queueServiceClient = new QueueServiceClientBuilder().endpoint(queueServiceURL)
        .sasToken(SAS_TOKEN).buildClient();

QueueServiceProperties properties = queueServiceClient.getProperties();

キュー アカウントでプロパティを設定する

Storage Analyticsルールと CORS (クロスオリジン リソース共有) ルールのプロパティを含む、アカウントでキュー のプロパティを設定します。

資格情報として を使用 ${SASToken} します。

String queueServiceURL = String.format("https://%s.queue.core.windows.net", ACCOUNT_NAME);
QueueServiceClient queueServiceClient = new QueueServiceClientBuilder().endpoint(queueServiceURL)
        .sasToken(SAS_TOKEN).buildClient();

QueueServiceProperties properties = queueServiceClient.getProperties();
properties.setCors(Collections.emptyList());
queueServiceClient.setProperties(properties);

キュー サービスの統計情報を取得する

Get Queue Service Stats 操作は、キュー サービスのレプリケーションに関連する統計情報を取得します。

資格情報として を使用 ${SASToken} します。 読み取りアクセスの地理冗長レプリケーションがストレージ アカウントで有効なとき、これは 2 次拠点のエンドポイントでのみ使用できます。

String queueServiceURL = String.format("https://%s.queue.core.windows.net", ACCOUNT_NAME);
QueueServiceClient queueServiceClient = new QueueServiceClientBuilder().endpoint(queueServiceURL)
        .sasToken(SAS_TOKEN).buildClient();

QueueServiceStatistics queueStats = queueServiceClient.getStatistics();

キューにメッセージをエンキューする

この操作により、メッセージ キューの背面に新しいメッセージが追加されます。 表示タイムアウトを指定して、タイムアウトになるまでメッセージを非表示にすることもできます。

資格情報として を使用 ${SASToken} します。 メッセージは、UTF-8 エンコードされた XML 要求に含めることができる形式である必要があります。 エンコードされたメッセージのサイズは、バージョン 2011-08-18 以降では最大 64 KB、以前のバージョンでは 8 KB です。

String queueURL = String.format("https://%s.queue.core.windows.net", ACCOUNT_NAME);
QueueClient queueClient = new QueueClientBuilder().endpoint(queueURL).sasToken(SAS_TOKEN).queueName("myqueue")
        .buildClient();

queueClient.sendMessage("myMessage");

キュー内のメッセージを更新する

この操作により、メッセージ キュー内のメッセージが更新されます。 資格情報として を使用 ${SASToken} します。

String queueURL = String.format("https://%s.queue.core.windows.net", ACCOUNT_NAME);
QueueClient queueClient = new QueueClientBuilder().endpoint(queueURL).sasToken(SAS_TOKEN).queueName("myqueue")
        .buildClient();
// @param messageId: Id of the message
// @param popReceipt: Unique identifier that must match the message for it to be updated
// @param visibilityTimeout: How long the message will be invisible in the queue in seconds
queueClient.updateMessage(messageId, popReceipt, "new message", visibilityTimeout);

キュー内のメッセージを表示する

この操作では、キューの前面から 1 つ以上のメッセージがピークされます。 資格情報として を使用 ${SASToken} します。

String queueURL = String.format("https://%s.queue.core.windows.net", ACCOUNT_NAME);
QueueClient queueClient = new QueueClientBuilder().endpoint(queueURL).sasToken(SAS_TOKEN).queueName("myqueue")
        .buildClient();
// @param key: The key with which the specified value should be associated.
// @param value: The value to be associated with the specified key.
queueClient.peekMessages(5, Duration.ofSeconds(1), new Context(key, value)).forEach(message ->
    System.out.println(message.getBody().toString()));

キューからメッセージを受信する

この操作は、キューの先頭から 1 つ以上のメッセージを取得します。 資格情報として を使用 ${SASToken} します。

String queueURL = String.format("https://%s.queue.core.windows.net", ACCOUNT_NAME);
QueueClient queueClient = new QueueClientBuilder().endpoint(queueURL).sasToken(SAS_TOKEN).queueName("myqueue")
        .buildClient();
// Try to receive 10 messages: Maximum number of messages to get
queueClient.receiveMessages(10).forEach(message ->
    System.out.println(message.getBody().toString()));

キューからメッセージを削除する

この操作により、キューからメッセージが削除されます。 資格情報として を使用 ${SASToken} します。

String queueURL = String.format("https://%s.queue.core.windows.net", ACCOUNT_NAME);
QueueClient queueClient = new QueueClientBuilder().endpoint(queueURL).sasToken(SAS_TOKEN).queueName("myqueue")
        .buildClient();

queueClient.deleteMessage(messageId, popReceipt);

キューのプロパティを取得する

操作は、指定されたキューのユーザー定義メタデータとキュー プロパティを取得します。 メタデータは、名前と値のペアとしてキューに関連付けられています。

資格情報として を使用 ${SASToken} します。

String queueURL = String.format("https://%s.queue.core.windows.net", ACCOUNT_NAME);
QueueClient queueClient = new QueueClientBuilder().endpoint(queueURL).sasToken(SAS_TOKEN).queueName("myqueue")
        .buildClient();

QueueProperties properties = queueClient.getProperties();

キューのメタデータを設定する

この操作により、指定したキューにユーザー定義メタデータが設定されます。 メタデータは、名前と値のペアとしてキューに関連付けられます。

資格情報として を使用 ${SASToken} します。

String queueURL = String.format("https://%s.queue.core.windows.net", ACCOUNT_NAME);
QueueClient queueClient = new QueueClientBuilder().endpoint(queueURL).sasToken(SAS_TOKEN).queueName("myqueue")
        .buildClient();

Map<String, String> metadata = new HashMap<>();
metadata.put("key1", "val1");
metadata.put("key2", "val2");
queueClient.setMetadata(metadata);

トラブルシューティング

全般

この Java クライアント ライブラリを使用してキューを操作すると、サービスによって返されるエラーは、 REST API 要求に対して返されるのと同じ HTTP 状態コードに対応します。 たとえば、ストレージ アカウントに存在しないキューを取得しようとすると、 404 を示す Not Foundエラーが返されます。

既定の HTTP クライアント

すべてのクライアント ライブラリでは、Netty HTTP クライアントが既定で使用されます。 前述の依存関係を追加すると、Netty HTTP クライアントを使用するようにクライアント ライブラリが自動的に構成されます。 HTTP クライアントの構成と変更については、HTTP クライアントの Wiki で詳しく説明されています。

既定の SSL ライブラリ

すべてのクライアント ライブラリは、Tomcat ネイティブの Boring SSL ライブラリを既定で使用して、SSL 操作にネイティブレベルのパフォーマンスを実現しています。 Boring SSL ライブラリは、Linux、macOS、Windows のネイティブ ライブラリを含んだ uber jar であり、JDK 内の既定の SSL 実装よりも優れたパフォーマンスを備えています。 依存関係のサイズを縮小する方法など、詳細については、Wiki の「パフォーマンス チューニング」セクションを参照してください。

次の手順

SDK の GitHub リポジトリでは、いくつかの Storage Queue Java SDK サンプルを使用できます。 これらのサンプルでは、Key Vaultの操作中に一般的に発生するその他のシナリオのコード例を示します。

次の手順のサンプル

サンプルについては、 こちらを参照してください

共同作成

このプロジェクトでは、共同作成と提案を歓迎しています。 ほとんどの共同作成では、共同作成者使用許諾契約書 (CLA) にご同意いただき、ご自身の共同作成内容を使用する権利を Microsoft に供与する権利をお持ちであり、かつ実際に供与することを宣言していただく必要があります。 詳細については、 https://cla.microsoft.com を参照してください。

pull request を送信すると、CLA を提供して PR (ラベル、コメントなど) を適宜装飾する必要があるかどうかを CLA ボットが自動的に決定します。 ボットによって提供される手順にそのまま従ってください。 この操作は、Microsoft の CLA を使用するすべてのリポジトリについて、1 回だけ行う必要があります。

このプロジェクトでは、Microsoft オープン ソースの倫理規定を採用しています。 詳しくは、「Code of Conduct FAQ (倫理規定についてよくある質問)」を参照するか、opencode@microsoft.com 宛てに質問またはコメントをお送りください。

このリポジトリへの投稿の詳細については、 投稿ガイドを参照してください。

  1. フォークする
  2. 機能ブランチを作成する (git checkout -b my-new-feature)
  3. 変更をコミットする (git commit -am 'Add some feature')
  4. ブランチにプッシュする (git push origin my-new-feature)
  5. 新しい Pull Request を作成する

インプレッション数