你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

适用于 Java 的 Azure 存储队列客户端库 - 版本 12.19.1

Azure 队列存储是一项可存储大量消息的服务,用户可以通过经验证的呼叫,使用 HTTP 或 HTTPS 从世界任何地方访问这些消息。 一条队列消息的大小最多可为 64 KB,一个队列中可以包含数百万条消息,直至达到存储帐户的总容量限值。

源代码 | API 参考文档 | 产品文档 | 示例

入门

先决条件

添加包

包括 BOM 文件

请将 azure-sdk-bom 包含在项目中,以依赖于库的 GA 版本。 在以下代码段中,将 {bom_version_to_target} 占位符替换为版本号。 若要详细了解 BOM,请参阅 AZURE SDK BOM 自述文件

<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 门户或 Azure CLI

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

验证客户端

若要与存储服务 (Blob、队列、消息、MessageId、File) 需要创建服务客户端类的实例。 为此,需要帐户 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 门户获取帐户 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

处理异常

queueServiceClient使用下面的队列服务客户端部分生成的 。

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. 队列名称必须以字母或数字开头且只能包含字母、数字和短划线 (-) 字符。
  2. 队列名称中的第一个字符和最后一个字符必须是字母数字。 短划线 (-) 字符不能是第一个或最后一个字符。 队列名称中不允许有连续的短划线字符。
  3. 队列名称中的所有字母必须为小写。
  4. 队列名称的长度必须为 3 到 63 个字符。

队列服务

队列服务对存储帐户中的队列执行操作,并管理队列属性。

队列服务客户端

客户端执行与队列服务的交互、创建或删除队列、获取和设置队列属性、列出帐户中的队列以及获取队列统计信息。 SDK 中存在异步 QueueServiceAsyncClient、 和同步客户端, QueueClient允许根据应用程序的用例选择客户端。 获得 SASToken 的值后,可以使用 创建队列服务客户端${accountName}${SASToken}

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 从世界任何地方访问这些消息。 一条队列消息的大小最多可为 64 KB,一个队列中可以包含数百万条消息,直至达到存储帐户的总容量限值。

QueueClient

获得 SASToken 的值后,可以使用 、、${queueName}${SASToken}创建队列服务客户端${accountName}

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
});

示例

以下部分提供了几个代码片段,涵盖了一些最常见的配置服务任务,包括:

生成客户端

我们有两种方法可以生成 QueueService 或 Queue Client。 此处以 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()));

获取队列帐户中的属性

获取帐户中的队列属性,包括 存储分析 和 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();

在队列帐户中设置属性

在帐户中设置队列属性,包括 存储分析 和 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} 凭据。 仅在为存储帐户启用了读访问的地域冗余复制时,才能在辅助位置的终结点上使用它。

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);

查看队列中的消息

该操作从队列前面扫视一个或多个消息。 用作 ${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()));

从队列接收消息

该操作从队列前面检索一个或多个消息。 用作 ${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 客户端 Wiki 中详述了如何配置或更改 HTTP 客户端。

默认 SSL 库

默认情况下,所有客户端库均使用 Tomcat 原生 Boring SSL 库来为 SSL 操作启用原生级别性能。 Boring SSL 库是一个 uber jar,其中包含适用于 Linux/macOS/Windows 的原生库。与 JDK 内的默认 SSL 实现相比,它提供更好的性能。 有关详细信息(包括如何减小依赖项大小),请参阅 Wiki 的性能优化部分。

后续步骤

SDK 的 GitHub 存储库中提供了多个存储队列 Java SDK 示例。 这些示例提供了使用 密钥保管库 时经常遇到的其他方案的示例代码:

后续步骤示例

此处详细介绍了示例。

贡献

本项目欢迎贡献和建议。 大多数贡献要求你同意贡献者许可协议 (CLA),并声明你有权(并且确实有权)授予我们使用你的贡献的权利。 有关详细信息,请访问 https://cla.microsoft.com

提交拉取请求时,CLA 机器人将自动确定你是否需要提供 CLA,并相应地修饰 PR(例如标签、注释)。 直接按机器人提供的说明操作。 只需使用 CLA 对所有存储库执行一次这样的操作。

此项目采用了 Microsoft 开放源代码行为准则。 有关详细信息,请参阅行为准则常见问题解答,或如果有任何其他问题或意见,请与 联系。

有关参与此存储库的详细信息,请参阅 参与指南

  1. 分叉它
  2. 创建功能分支 (git checkout -b my-new-feature)
  3. () git commit -am 'Add some feature' 提交更改
  4. 推送到分支 (git push origin my-new-feature)
  5. 创建新的拉取请求

曝光数