快速入门:适用于 Java 的 Azure 队列存储客户端库 v12Quickstart: Azure Queue storage client library v12 for Java

适用于 Java 的 Azure 队列存储客户端库版本 12 入门。Get started with the Azure Queue storage client library version 12 for Java. Azure 队列存储服务可存储大量消息供稍后检索和处理。Azure Queue storage is a service for storing large numbers of messages for later retrieval and processing. 请按照以下步骤安装程序包并试用基本任务的示例代码。Follow these steps to install the package and try out example code for basic tasks.

使用适用于 Java 的 Azure 队列存储客户端库 v12:Use the Azure Queue storage client library v12 for Java to:

  • 创建队列Create a queue
  • 向队列添加消息Add messages to a queue
  • 查看队列中的消息Peek at messages in a queue
  • 更新队列中的消息Update a message in a queue
  • 接收和删除队列中的消息Receive and delete messages from a queue
  • 删除队列Delete a queue

其他资源:Additional resources:

先决条件Prerequisites

设置Setting up

本部分逐步指导如何准备一个项目,使其与适用于 Java 的 Azure 队列存储客户端库 v12 配合使用。This section walks you through preparing a project to work with the Azure Queue storage client library v12 for Java.

创建项目Create the project

创建名为 queues-quickstart-v12 的 Java 应用程序。Create a Java application named queues-quickstart-v12.

  1. 在控制台窗口(例如 cmd、PowerShell 或 Bash)中,使用 Maven 创建名为 queues-quickstart-v12 的新控制台应用。In a console window (such as cmd, PowerShell, or Bash), use Maven to create a new console app with the name queues-quickstart-v12. 键入以下“mvn”命令,创建“Hello World!”Type the following mvn command to create a "Hello world!" Java 项目。Java project.

    mvn archetype:generate -DgroupId=com.queues.quickstart \
                           -DartifactId=queues-quickstart-v12 \
                           -DarchetypeArtifactId=maven-archetype-quickstart \
                           -DarchetypeVersion=1.4 \
                           -DinteractiveMode=false
    
  2. 生成项目的输出应如下所示:The output from generating the project should look something like this:

    [INFO] Scanning for projects...
    [INFO]
    [INFO] ------------------< org.apache.maven:standalone-pom >-------------------
    [INFO] Building Maven Stub Project (No POM) 1
    [INFO] --------------------------------[ pom ]---------------------------------
    [INFO]
    [INFO] >>> maven-archetype-plugin:3.1.2:generate (default-cli) > generate-sources @ standalone-pom >>>
    [INFO]
    [INFO] <<< maven-archetype-plugin:3.1.2:generate (default-cli) < generate-sources @ standalone-pom <<<
    [INFO]
    [INFO]
    [INFO] --- maven-archetype-plugin:3.1.2:generate (default-cli) @ standalone-pom ---
    [INFO] Generating project in Batch mode
    [INFO] ----------------------------------------------------------------------------
    [INFO] Using following parameters for creating project from Archetype: maven-archetype-quickstart:1.4
    [INFO] ----------------------------------------------------------------------------
    [INFO] Parameter: groupId, Value: com.queues.quickstart
    [INFO] Parameter: artifactId, Value: queues-quickstart-v12
    [INFO] Parameter: version, Value: 1.0-SNAPSHOT
    [INFO] Parameter: package, Value: com.queues.quickstart
    [INFO] Parameter: packageInPathFormat, Value: com/queues/quickstart
    [INFO] Parameter: version, Value: 1.0-SNAPSHOT
    [INFO] Parameter: package, Value: com.queues.quickstart
    [INFO] Parameter: groupId, Value: com.queues.quickstart
    [INFO] Parameter: artifactId, Value: queues-quickstart-v12
    [INFO] Project created from Archetype in dir: C:\quickstarts\queues\queues-quickstart-v12
    [INFO] ------------------------------------------------------------------------
    [INFO] BUILD SUCCESS
    [INFO] ------------------------------------------------------------------------
    [INFO] Total time:  6.394 s
    [INFO] Finished at: 2019-12-03T09:58:35-08:00
    [INFO] ------------------------------------------------------------------------
    
  3. 切换到新创建的 queues-quickstart-v12 目录。Switch to the newly created queues-quickstart-v12 directory.

    cd queues-quickstart-v12
    

安装包Install the package

在文本编辑器中打开 pom.xml 文件。Open the pom.xml file in your text editor. 将以下依赖项元素添加到依赖项组。Add the following dependency element to the group of dependencies.

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

设置应用框架Set up the app framework

从项目目录中执行以下操作:From the project directory:

  1. 导航到 /src/main/java/com/queues/quickstart 目录Navigate to the /src/main/java/com/queues/quickstart directory
  2. 在编辑器中打开 App.java 文件Open the App.java file in your editor
  3. 删除 System.out.println("Hello world!"); 语句Delete the System.out.println("Hello world!"); statement
  4. 添加 import 指令Add import directives

代码如下:Here's the code:

package com.queues.quickstart;

/**
 * Azure queue storage v12 SDK quickstart
 */
import com.azure.storage.queue.*;
import com.azure.storage.queue.models.*;
import java.io.*;
import java.time.*;

public class App
{
    public static void main( String[] args ) throws IOException
    {
    }
}

从 Azure 门户复制凭据Copy your credentials from the Azure portal

当示例应用程序向 Azure 存储发出请求时,必须对其进行授权。When the sample application makes a request to Azure Storage, it must be authorized. 若要对请求进行授权,请将存储帐户凭据以连接字符串形式添加到应用程序中。To authorize a request, add your storage account credentials to the application as a connection string. 按照以下步骤查看存储帐户凭据:View your storage account credentials by following these steps:

  1. 登录 Azure 门户Sign in to the Azure portal.

  2. 找到自己的存储帐户。Locate your storage account.

  3. 在存储帐户概述的“设置”部分,选择“访问密钥”。 In the Settings section of the storage account overview, select Access keys. 在这里,可以查看你的帐户访问密钥以及每个密钥的完整连接字符串。Here, you can view your account access keys and the complete connection string for each key.

  4. 找到“密钥 1”下面的“连接字符串”值,选择“复制”按钮复制该连接字符串。 Find the Connection string value under key1, and select the Copy button to copy the connection string. 下一步需将此连接字符串值添加到某个环境变量。You will add the connection string value to an environment variable in the next step.

    显示如何从 Azure 门户复制连接字符串的屏幕截图

配置存储连接字符串Configure your storage connection string

复制连接字符串以后,请将其写入运行应用程序的本地计算机的新环境变量中。After you have copied your connection string, write it to a new environment variable on the local machine running the application. 若要设置环境变量,请打开控制台窗口,并遵照适用于操作系统的说明。To set the environment variable, open a console window, and follow the instructions for your operating system. <yourconnectionstring> 替换为实际的连接字符串。Replace <yourconnectionstring> with your actual connection string.

WindowsWindows

setx AZURE_STORAGE_CONNECTION_STRING "<yourconnectionstring>"

在 Windows 中添加环境变量后,必须启动命令窗口的新实例。After you add the environment variable in Windows, you must start a new instance of the command window.

LinuxLinux

export AZURE_STORAGE_CONNECTION_STRING="<yourconnectionstring>"

macOSmacOS

export AZURE_STORAGE_CONNECTION_STRING="<yourconnectionstring>"

重新启动程序Restart programs

添加环境变量后,重启需要读取环境变量的任何正在运行的程序。After you add the environment variable, restart any running programs that will need to read the environment variable. 例如,重启开发环境或编辑器,然后再继续。For example, restart your development environment or editor before continuing.

对象模型Object model

Azure 队列存储是一个可存储大量消息的服务。Azure Queue storage is a service for storing large numbers of messages. 队列消息大小最大可为 64 KB。A queue message can be up to 64 KB in size. 一个队列可以包含数百万条消息,直至达到存储帐户的总容量限值。A queue may contain millions of messages, up to the total capacity limit of a storage account. 队列通常用于创建要异步处理的积压工作 (backlog)。Queues are commonly used to create a backlog of work to process asynchronously. 队列存储提供三种类型的资源:Queue storage offers three types of resources:

  • 存储帐户The storage account
  • 存储帐户中的队列A queue in the storage account
  • 队列中的消息Messages within the queue

以下图示显示了这些资源之间的关系。The following diagram shows the relationship between these resources.

队列存储体系结构的图示

使用以下 Java 类与这些资源进行交互:Use the following Java classes to interact with these resources:

  • QueueClientBuilderQueueClientBuilder 类配置并实例化一个 QueueClient 对象。QueueClientBuilder: The QueueClientBuilder class configures and instantiates a QueueClient object.
  • QueueServiceClient:通过 QueueServiceClient 可管理存储帐户中的所有队列。QueueServiceClient: The QueueServiceClient allows you to manage the all queues in your storage account.
  • QueueClient:通过 QueueClient 类可管理和操纵单个队列及其消息。QueueClient: The QueueClient class allows you to manage and manipulate an individual queue and its messages.
  • QueueMessageItemQueueMessageItem 类表示在队列中调用 receiveMessages 时返回的各个对象。QueueMessageItem: The QueueMessageItem class represents the individual objects returned when calling receiveMessages on a queue.

代码示例Code examples

这些示例代码片段演示如何使用适用于 Java 的 Azure 队列存储客户端库执行以下操作:These example code snippets show you how to do the following actions with the Azure Queue storage client library for Java:

获取连接字符串Get the connection string

以下代码检索存储帐户的连接字符串。The code below retrieves the connection string for the storage account. 连接字符串存储在配置存储连接字符串部分中创建的环境变量中。The connection string is stored the environment variable created in the Configure your storage connection string section.

main 方法内添加此代码:Add this code inside the main method:

System.out.println("Azure Queues storage v12 - Java quickstart sample\n");

// Retrieve the connection string for use with the application. The storage
// connection string is stored in an environment variable on the machine
// running the application called AZURE_STORAGE_CONNECTION_STRING. If the environment variable
// is created after the application is launched in a console or with
// Visual Studio, the shell or application needs to be closed and reloaded
// to take the environment variable into account.
String connectStr = System.getenv("AZURE_STORAGE_CONNECTION_STRING");

创建队列Create a queue

确定新队列的名称。Decide on a name for the new queue. 以下代码将 GUID 值追加到队列名称,从而确保其是唯一的。The code below appends a GUID value to the queue name to ensure that it's unique.

重要

队列名称只能包含小写字母、数字和连字符,并且必须以字母或数字开头。Queue names may only contain lowercase letters, numbers, and hyphens, and must begin with a letter or a number. 每个连字符的前后必须为非连字符字符。Each hyphen must be preceded and followed by a non-hyphen character. 名称的长度还必须介于 3 到 63 个字符之间。The name must also be between 3 and 63 characters long. 有关命名队列的详细信息,请参阅命名队列和元数据For more information about naming queues, see Naming Queues and Metadata.

创建 QueueClient 类的实例。Create an instance of the QueueClient class. 然后,调用 create 方法,以便在存储帐户中创建队列。Then, call the create method to create the queue in your storage account.

将此代码添加到 main 方法的末尾:Add this code to the end of the main method:

// Create a unique name for the queue
String queueName = "quickstartqueues-" + java.util.UUID.randomUUID();

System.out.println("Creating queue: " + queueName);

// Instantiate a QueueClient which will be
// used to create and manipulate the queue
QueueClient queueClient = new QueueClientBuilder()
                                .connectionString(connectStr)
                                .queueName(queueName)
                                .buildClient();

// Create the queue
queueClient.create();

向队列添加消息Add messages to a queue

下面的代码片段调用 sendMessage 方法将消息添加到队列中。The following code snippet adds messages to queue by calling the sendMessage method. 它还保存从 sendMessage 调用返回的 SendMessageResultIt also saves a SendMessageResult returned from a sendMessage call. 结果用于稍后在程序中更新消息。The result is used to update the message later in the program.

将此代码添加到 main 方法的末尾:Add this code to the end of the main method:

System.out.println("\nAdding messages to the queue...");

// Send several messages to the queue
queueClient.sendMessage("First message");
queueClient.sendMessage("Second message");

// Save the result so we can update this message later
SendMessageResult result = queueClient.sendMessage("Third message");

查看队列中的消息Peek at messages in a queue

调用 peekMessages 方法来查看队列中的消息。Peek at the messages in the queue by calling the peekMessages method. peelkMessages 方法从队列的前部检索一条或多条消息,但不会更改消息的可见性。The peelkMessages method retrieves one or more messages from the front of the queue but doesn't alter the visibility of the message.

将此代码添加到 main 方法的末尾:Add this code to the end of the main method:

System.out.println("\nPeek at the messages in the queue...");

// Peek at messages in the queue
queueClient.peekMessages(10, null, null).forEach(
    peekedMessage -> System.out.println("Message: " + peekedMessage.getMessageText()));

更新队列中的消息Update a message in a queue

调用 updateMessage 方法来更新消息的内容。Update the contents of a message by calling the updateMessage method. updateMessage 方法可以更改消息的可见性超时和内容。The updateMessage method can change a message's visibility timeout and contents. 消息内容必须是不超过 64 KB 的 UTF-8 编码字符串。The message content must be a UTF-8 encoded string that is up to 64 KB in size. 除消息的新内容外,还要使用 SendMessageResult 在代码中传入之前保存的消息 ID 和 pop 收据。Along with new content for the message, pass in the message ID and pop receipt by using the SendMessageResult that was saved earlier in the code. 消息 ID 和 pop 收据标识要更新的消息。The message ID and pop receipt identify which message to update.

System.out.println("\nUpdating the third message in the queue...");

// Update a message using the result that
// was saved when sending the message
queueClient.updateMessage(result.getMessageId(),
                          result.getPopReceipt(), 
                          "Third message has been updated",
                          Duration.ofSeconds(1));

接收和删除队列中的消息Receive and delete messages from a queue

调用 receiveMessages 方法来下载以前添加的消息。Download previously added messages by calling the receiveMessages method. 接收并处理消息后,此示例代码还会从队列中删除消息。The example code also deletes messages from the queue after they're received and processed. 在本例中,“处理”即在控制台上显示消息。In this case, processing is just displaying the message on the console.

在接收和删除消息之前,应用会调用 System.console().readLine(); 以暂停并等待用户输入。The app pauses for user input by calling System.console().readLine(); before it receives and deletes the messages. 在删除资源之前,请先在 Azure 门户中验证资源已正确创建。Verify in your Azure portal that the resources were created correctly, before they're deleted. 未显式删除的任何消息都将在队列中再次变为可见,以方便再一次进行处理。Any messages not explicitly deleted will eventually become visible in the queue again for another chance to process them.

将此代码添加到 main 方法的末尾:Add this code to the end of the main method:

System.out.println("\nPress Enter key to receive messages and delete them from the queue...");
System.console().readLine();

// Get messages from the queue
queueClient.receiveMessages(10).forEach(
    // "Process" the message
    receivedMessage -> {
        System.out.println("Message: " + receivedMessage.getMessageText());

        // Let the service know we're finished with
        // the message and it can be safely deleted.
        queueClient.deleteMessage(receivedMessage.getMessageId(), receivedMessage.getPopReceipt());
    }
);

删除队列Delete a queue

以下代码使用 delete 方法删除队列,从而清除该应用所创建的资源。The following code cleans up the resources the app created by deleting the queue using the delete method.

将此代码添加到 main 方法的末尾:Add this code to the end of the main method:

System.out.println("\nPress Enter key to delete the queue...");
System.console().readLine();

// Clean up
System.out.println("Deleting queue: " + queueClient.getQueueName());
queueClient.delete();

System.out.println("Done");

运行代码Run the code

此应用创建三条消息并将其添加到 Azure 队列。This app creates and adds three messages to an Azure queue. 此代码列出队列中的消息,然后检索并删除它们,最后删除队列。The code lists the messages in the queue, then retrieves and deletes them, before finally deleting the queue.

在控制台窗口中,导航到应用程序目录,然后生成并运行应用程序。In your console window, navigate to your application directory, then build and run the application.

mvn compile

然后,生成包。Then, build the package.

mvn package

运行以下 mvn 命令以执行应用。Run the following mvn command to execute the app.

mvn exec:java -Dexec.mainClass="com.queues.quickstart.App" -Dexec.cleanupDaemonThreads=false

应用的输出类似于以下示例:The output of the app is similar to the following example:

Azure Queues storage v12 - Java quickstart sample

Adding messages to the queue...

Peek at the messages in the queue...
Message: First message
Message: Second message
Message: Third message

Updating the third message in the queue...

Press Enter key to receive messages and delete them from the queue...

Message: First message
Message: Second message
Message: Third message has been updated

Press Enter key to delete the queue...

Deleting queue: quickstartqueues-fbf58f33-4d5a-41ac-ac0e-1a05d01c7003
Done

当应用在接收到消息之前暂停时,请在 Azure 门户中检查存储帐户。When the app pauses before receiving messages, check your storage account in the Azure portal. 验证消息是否在队列中。Verify the messages are in the queue.

按“Enter”键接收和删除消息。Press the Enter key to receive and delete the messages. 出现提示时,请再次按“Enter”键,删除队列并完成演示。When prompted, press the Enter key again to delete the queue and finish the demo.

后续步骤Next steps

通过本快速入门,你了解了如何使用 Java 代码创建队列并向其添加消息。In this quickstart, you learned how to create a queue and add messages to it using Java code. 然后了解了如何查看、检索和删除消息。Then you learned to peek, retrieve, and delete messages. 最后,你还了解了如何删除消息队列。Finally, you learned how to delete a message queue.

有关教程、示例、快速入门和其他文档,请访问:For tutorials, samples, quick starts, and other documentation, visit: