快速入门:使用 Azure 门户创建服务总线队列Quickstart: Use Azure portal to create a Service Bus queue

本快速入门介绍如何使用 Azure 门户创建消息命名空间并在该命名空间中创建队列,以及如何获取该命名空间上的授权凭据,以便将消息发送到服务总线队列以及从中接收消息。This quickstart describes how to send and receive messages to and from a Service Bus queue, using the Azure portal to create a messaging namespace and a queue within that namespace, and to obtain the authorization credentials on that namespace. 然后该过程展示了如何使用 .NET Standard 库从此队列发送和接收消息。The procedure then shows how to send and receive messages from this queue using the .NET Standard library.

什么是 Service Bus 队列?What are Service Bus queues?

服务总线队列支持中转消息传送通信模型。Service Bus queues support a brokered messaging communication model. 在使用队列时,分布式应用程序的组件不会直接相互通信,而是通过充当中介(代理)的队列交换消息。When using queues, components of a distributed application do not communicate directly with each other; instead they exchange messages via a queue, which acts as an intermediary (broker). 消息创建方(发送方)将消息传送到队列,并继续对其进行处理。A message producer (sender) hands off a message to the queue and then continues its processing. 消息使用方(接收方)以异步方式从队列中提取消息并对其进行处理。Asynchronously, a message consumer (receiver) pulls the message from the queue and processes it. 创建方不必等待使用方的答复即可继续处理并发送更多消息。The producer does not have to wait for a reply from the consumer in order to continue to process and send further messages. 队列为一个或多个竞争使用方提供先入先出 (FIFO) 消息传递方式。Queues offer First In, First Out (FIFO) message delivery to one or more competing consumers. 也就是说,接收方通常会按照消息添加到队列中的顺序来接收并处理消息,并且每条消息仅由一个消息使用方接收并处理。That is, messages are typically received and processed by the receivers in the order in which they were added to the queue, and each message is received and processed by only one message consumer.

QueueConcepts

服务总线队列是一种可用于各种应用场景的通用技术:Service Bus queues are a general-purpose technology that can be used for a wide variety of scenarios:

  • 多层 Azure 应用程序中 Web 角色和辅助角色之间的通信。Communication between web and worker roles in a multi-tier Azure application.
  • 混合解决方案中本地应用程序和 Azure 托管应用程序之间的通信。Communication between on-premises apps and Azure-hosted apps in a hybrid solution.
  • 在不同组织或组织的各部门中本地运行的分布式应用程序组件之间的通信。Communication between components of a distributed application running on-premises in different organizations or departments of an organization.

利用队列,可以更轻松地缩放应用程序,并增强体系结构的弹性。Using queues enables you to scale your applications more easily, and enable more resiliency to your architecture.

先决条件Prerequisites

若要完成本教程,请确保已安装:To complete this tutorial, make sure you have installed:

  • Azure 订阅。An Azure subscription. 如果没有 Azure 订阅,可以在开始前创建一个[试用帐户][]。If you don't have an Azure subscription, you can create a trial account before you begin.
  • Visual Studio 2017 Update 3(版本 15.3 (26730.01))或更高版本。Visual Studio 2017 Update 3 (version 15.3, 26730.01) or later. 请使用 Visual Studio 生成一个向队列发送消息以及从队列接收消息的示例。You use Visual Studio to build a sample that sends messages to and receives message from a queue. 该示例用于测试使用 PowerShell 创建的队列。The sample is to test the queue you created using PowerShell.
  • NET Core SDK 2.0 或更高版本。NET Core SDK, version 2.0 or later.

若要开始在 Azure 中使用服务总线消息实体,必须先使用在 Azure 中唯一的名称创建一个命名空间。To begin using Service Bus messaging entities in Azure, you must first create a namespace with a name that is unique across Azure. 命名空间提供了用于对应用程序中的服务总线资源进行寻址的范围容器。A namespace provides a scoping container for addressing Service Bus resources within your application.

创建命名空间:To create a namespace:

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

  2. 在门户的左侧导航窗格中,依次单击“+ 创建资源”、“集成”和“服务总线”。In the left navigation pane of the portal, click + Create a resource, then click Integration, and then click Service Bus.

  3. 在“创建命名空间” 对话框中,输入命名空间名称。In the Create namespace dialog, enter a namespace name. 系统会立即检查该名称是否可用。The system immediately checks to see if the name is available.

  4. 在确保命名空间名称可用后,选择定价层(基本版或标准版)。After making sure the namespace name is available, choose the pricing tier (Basic or Standard). 如果要使用主题和订阅,请务必选择“标准”。If you want to use topics and subscriptions, make sure to choose Standard. 基本定价层中不支持主题/订阅。Topics/subscriptions are not supported in the Basic pricing tier.

  5. 在“订阅” 字段中,选择要创建命名空间的 Azure 订阅。In the Subscription field, choose an Azure subscription in which to create the namespace.

  6. 在“资源组” 字段中,选择用于放置该命名空间的现有资源组,或者创建一个新资源组。In the Resource group field, choose an existing resource group in which the namespace will live, or create a new one.

  7. 在“位置” 中,选择应在其中托管该命名空间的国家或地区。In Location, choose the country or region in which your namespace should be hosted.

    创建命名空间

  8. 单击“创建” 。Click Create. 系统现已创建命名空间并已将其启用。The system now creates your namespace and enables it. 可能需要等待几分钟,因为系统会为你的帐户配置资源。You might have to wait several minutes as the system provisions resources for your account.

获取管理凭据Obtain the management credentials

创建新的命名空间时,会自动生成一项初始的共享访问签名 (SAS) 规则,将一对主密钥和辅助密钥关联到一起,向每个密钥授予对命名空间的所有资产的完全控制权限。Creating a new namespace automatically generates an initial Shared Access Signature (SAS) rule with an associated pair of primary and secondary keys that each grant full control over all aspects of the namespace. 请参阅服务总线身份验证和授权,了解如何创建更多的规则,对常规的发送者和接收者的权限进行更多限制。See Service Bus authentication and authorization for information about how to create further rules with more constrained rights for regular senders and receivers. 若要复制初始规则,请执行以下步骤:To copy the initial rule, follow these steps:

  1. 单击“所有资源”,然后单击新创建的命名空间名称。Click All resources, then click the newly created namespace name.

  2. 在命名空间窗口中,单击“共享访问策略”。In the namespace window, click Shared access policies.

  3. 在“共享访问策略”屏幕中,单击“RootManageSharedAccessKey”。In the Shared access policies screen, click RootManageSharedAccessKey.

    connection-info

  4. 在“策略: RootManageSharedAccessKey”窗口中,单击“主连接字符串”旁边的“复制”按钮,将连接字符串复制到剪贴板供以后使用。In the Policy: RootManageSharedAccessKey window, click the copy button next to Primary Connection String, to copy the connection string to your clipboard for later use. 将此值粘贴到记事本或其他某个临时位置。Paste this value into Notepad or some other temporary location.

    connection-string

  5. 重复上述步骤,将主键的值复制和粘贴到临时位置,以供稍后使用。Repeat the previous step, copying and pasting the value of Primary key to a temporary location for later use.

请确保已创建服务总线命名空间,如此处所示。Make sure that you have already created a Service Bus namespace, as shown here.

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

  2. 在门户左侧的导航窗格中,单击“服务总线”(如果未看到“服务总线”,请单击“所有服务”)。In the left navigation pane of the portal, click Service Bus (if you don't see Service Bus, click All services).

  3. 单击要在其中创建队列的命名空间。Click the namespace in which you would like to create the queue. 在此示例中,它是“sbnstest1”。In this case, it is sbnstest1.

    创建队列

  4. 在命名空间窗口中单击“队列”,然后在“队列”窗口中单击“+ 队列”。In the namespace window, click Queues, then in the Queues window, click + Queue.

    选择“队列”

  5. 输入队列名称,其他值则保留默认值。Enter the queue Name and leave the other values with their defaults.

    选择“新建”

  6. 在窗口底部,单击“创建”。At the bottom of the window, click Create.

发送和接收消息Send and receive messages

Note

此部分中用于发送和接收消息的示例是 .NET 示例。The sample used in this section to send and receive messages is a .NET sample. 有关使用其他编程语言发送/接收消息的示例,请参阅服务总线示例For samples to send/receive messages using other programming languages, see Service Bus samples.

有关使用各种编程语言发送/接收消息的分步说明,请参阅以下快速入门:For step-by-step instructions for sending/receiving messages using various programming languages, see the following quick starts:

预配命名空间和队列并且拥有所需的凭据后,便可以发送和接收消息。After the namespace and queue are provisioned, and you have the necessary credentials, you are ready to send and receive messages. 可以在此 GitHub 示例文件夹中检查代码。You can examine the code in this GitHub sample folder.

若要运行此代码,请执行以下操作:To run the code, do the following:

  1. 通过发出以下命令克隆服务总线 GitHub 存储库Clone the Service Bus GitHub repository by issuing the following command:

    git clone https://github.com/Azure/azure-service-bus.git
    
  2. 导航到示例文件夹 azure-service-bus\samples\DotNet\GettingStarted\BasicSendReceiveQuickStart\BasicSendReceiveQuickStartNavigate to the sample folder azure-service-bus\samples\DotNet\GettingStarted\BasicSendReceiveQuickStart\BasicSendReceiveQuickStart.

  3. 复制在“获取管理凭据”部分获得的连接字符串和队列名称。Copy the connection string and queue name you obtained in the Obtain the management credentials section.

  4. 在命令提示符窗口中键入以下命令:At a command prompt, type the following command:

    dotnet build
    
  5. 导航到 bin\Debug\netcoreapp2.0 文件夹。Navigate to the bin\Debug\netcoreapp2.0 folder.

  6. 键入以下命令以运行程序。Type the following command to run the program. 请务必将 myConnectionString 替换为先前获取的值,将 myQueueName 替换为所创建队列的名称:Be sure to replace myConnectionString with the value you previously obtained, and myQueueName with the name of the queue you created:

    dotnet BasicSendReceiveQuickStart.dll -ConnectionString "myConnectionString" -QueueName "myQueueName"
    
  7. 观察发送到队列并随后从队列中接收的 10 条消息:Observe 10 messages being sent to the queue, and subsequently received from the queue:

    程序输出

清理资源Clean up resources

可以通过门户删除资源组、命名空间和队列。You can use the portal to remove the resource group, namespace, and queue.

了解示例代码Understand the sample code

此部分包含有关示例代码功能的更多详细信息。This section contains more details about what the sample code does.

获取连接字符串和队列Get connection string and queue

连接字符串和队列名称作为命令行参数传递给 Main() 方法。The connection string and queue name are passed to the Main() method as command line arguments. Main() 声明了两个字符串变量来保存这些值:Main() declares two string variables to hold these values:

static void Main(string[] args)
{
    string ServiceBusConnectionString = "";
    string QueueName = "";

    for (int i = 0; i < args.Length; i++)
    {
        var p = new Program();
        if (args[i] == "-ConnectionString")
        {
            Console.WriteLine($"ConnectionString: {args[i+1]}");
            ServiceBusConnectionString = args[i + 1]; 
        }
        else if(args[i] == "-QueueName")
        {
            Console.WriteLine($"QueueName: {args[i+1]}");
            QueueName = args[i + 1];
        }                
    }

    if (ServiceBusConnectionString != "" && QueueName != "")
        MainAsync(ServiceBusConnectionString, QueueName).GetAwaiter().GetResult();
    else
    {
        Console.WriteLine("Specify -Connectionstring and -QueueName to execute the example.");
        Console.ReadKey();
    }                            
}

然后,Main() 方法启动异步消息循环 MainAsync()The Main() method then starts the asynchronous message loop, MainAsync().

消息循环Message loop

MainAsync() 方法使用命令行参数创建队列客户端,调用名为 RegisterOnMessageHandlerAndReceiveMessages() 的接收消息处理程序,并发送消息集:The MainAsync() method creates a queue client with the command line arguments, calls a receiving message handler named RegisterOnMessageHandlerAndReceiveMessages(), and sends the set of messages:

static async Task MainAsync(string ServiceBusConnectionString, string QueueName)
{
    const int numberOfMessages = 10;
    queueClient = new QueueClient(ServiceBusConnectionString, QueueName);

    Console.WriteLine("======================================================");
    Console.WriteLine("Press any key to exit after receiving all the messages.");
    Console.WriteLine("======================================================");

    // Register QueueClient's MessageHandler and receive messages in a loop
    RegisterOnMessageHandlerAndReceiveMessages();

    // Send Messages
    await SendMessagesAsync(numberOfMessages);

    Console.ReadKey();

    await queueClient.CloseAsync();
}

RegisterOnMessageHandlerAndReceiveMessages() 方法只是设置一些消息处理程序选项,然后调用队列客户端的 RegisterMessageHandler() 方法,该方法开始接收消息:The RegisterOnMessageHandlerAndReceiveMessages() method simply sets a few message handler options, then calls the queue client's RegisterMessageHandler() method, which starts the receiving:

static void RegisterOnMessageHandlerAndReceiveMessages()
{
    // Configure the MessageHandler Options in terms of exception handling, number of concurrent messages to deliver etc.
    var messageHandlerOptions = new MessageHandlerOptions(ExceptionReceivedHandler)
    {
        // Maximum number of Concurrent calls to the callback `ProcessMessagesAsync`, set to 1 for simplicity.
        // Set it according to how many messages the application wants to process in parallel.
        MaxConcurrentCalls = 1,

        // Indicates whether MessagePump should automatically complete the messages after returning from User Callback.
        // False below indicates the Complete will be handled by the User Callback as in `ProcessMessagesAsync` below.
        AutoComplete = false
    };

    // Register the function that will process messages
    queueClient.RegisterMessageHandler(ProcessMessagesAsync, messageHandlerOptions);
} 

发送消息Send messages

消息创建和发送操作发生在 SendMessagesAsync() 方法中:The message creation and send operations occur in the SendMessagesAsync() method:

static async Task SendMessagesAsync(int numberOfMessagesToSend)
{
    try
    {
        for (var i = 0; i < numberOfMessagesToSend; i++)
        {
            // Create a new message to send to the queue
            string messageBody = $"Message {i}";
            var message = new Message(Encoding.UTF8.GetBytes(messageBody));

            // Write the body of the message to the console
            Console.WriteLine($"Sending message: {messageBody}");

            // Send the message to the queue
            await queueClient.SendAsync(message);
        }
    }
    catch (Exception exception)
    {
        Console.WriteLine($"{DateTime.Now} :: Exception: {exception.Message}");
    }
}

处理消息Process messages

ProcessMessagesAsync() 方法确认、处理并完成消息的接收:The ProcessMessagesAsync() method acknowledges, processes, and completes the receipt of the messages:

static async Task ProcessMessagesAsync(Message message, CancellationToken token)
{
    // Process the message
    Console.WriteLine($"Received message: SequenceNumber:{message.SystemProperties.SequenceNumber} Body:{Encoding.UTF8.GetString(message.Body)}");

    // Complete the message so that it is not received again.
    await queueClient.CompleteAsync(message.SystemProperties.LockToken);
}

后续步骤Next steps

本文介绍了如何创建一个服务总线命名空间并从队列发送和接收消息所需的其他资源。In this article, you created a Service Bus namespace and other resources required to send and receive messages from a queue. 若要详细了解如何编写收发消息的代码,请继续阅读教程的“发送和接收消息”部分。To learn more about writing code to send and receive messages, continue to the tutorials in the Send and receive messages section.