使用 Azure 服务总线队列创建 .NET 多层应用程序.NET multi-tier application using Azure Service Bus queues

使用 Visual Studio 和免费的 Azure SDK for .NET,可以轻松针对 Azure 进行开发。Developing for Azure is easy using Visual Studio and the free Azure SDK for .NET. 本教程指导完成创建使用在本地环境中运行的多个 Azure 资源的应用程序的步骤。This tutorial walks you through the steps to create an application that uses multiple Azure resources running in your local environment.

学习以下技能:You will learn the following:

  • 如何通过单个下载和安装来使计算机能够进行 Azure 开发。How to enable your computer for Azure development with a single download and install.
  • 如何使用 Visual Studio 针对 Azure 进行开发。How to use Visual Studio to develop for Azure.
  • 如何使用 Web 角色和辅助角色在 Azure 中创建多层应用程序。How to create a multi-tier application in Azure using web and worker roles.
  • 如何使用服务总线队列在各层之间进行通信。How to communicate between tiers using Service Bus queues.


若要完成本教程,需要一个 Azure 帐户。To complete this tutorial, you need an Azure account. 可以注册免费试用版You can sign up for a free trial.

在本教程中,将生成多层应用程序并在 Azure 云服务中运行它。In this tutorial you'll build and run the multi-tier application in an Azure cloud service. 前端为 ASP.NET MVC Web 角色,后端为使用服务总线队列的辅助角色。The front end is an ASP.NET MVC web role and the back end is a worker-role that uses a Service Bus queue. 可以创建与前端相同的多层应用程序,作为要部署到 Azure 网站而不是云服务的 Web 项目。You can create the same multi-tier application with the front end as a web project, that is deployed to an Azure website instead of a cloud service. 还可以试用 .NET 本地/云混合应用程序教程。You can also try out the .NET on-premises/cloud hybrid application tutorial.

以下屏幕截图显示已完成的应用程序。The following screenshot shows the completed application.


方案概述:角色间通信Scenario overview: inter-role communication

若要提交处理命令,以 Web 角色运行的前端 UI 组件必须与以辅助角色运行的中间层逻辑进行交互。To submit an order for processing, the front-end UI component, running in the web role, must interact with the middle tier logic running in the worker role. 此示例使用服务总线消息传送在各层之间进行通信。This example uses Service Bus messaging for the communication between the tiers.

在 Web 层和中间层之间使用服务总线消息传送将分离这两个组件。Using Service Bus messaging between the web and middle tiers decouples the two components. 与直接消息传送(即 TCP 或 HTTP)不同,Web 层不会直接连接到中间层,而是将工作单元作为消息推送到服务总线,服务总线以可靠方式保留这些工作单元,直到中间层准备好使用和处理它们。In contrast to direct messaging (that is, TCP or HTTP), the web tier does not connect to the middle tier directly; instead it pushes units of work, as messages, into Service Bus, which reliably retains them until the middle tier is ready to consume and process them.

服务总线提供了两个实体以支持中转消息传送:队列和主题。Service Bus provides two entities to support brokered messaging: queues and topics. 通过队列,发送到队列的每个消息均由一个接收方使用。With queues, each message sent to the queue is consumed by a single receiver. 主题支持发布/订阅模式,在该模式中,每个已发布消息都将提供给在该主题中注册的订阅。Topics support the publish/subscribe pattern in which each published message is made available to a subscription registered with the topic. 每个订阅都以逻辑方式保留自己的消息队列。Each subscription logically maintains its own queue of messages. 此外,还可以使用筛选规则配置订阅,这些规则可将传递给订阅队列的消息集限制为符合筛选条件的消息集。Subscriptions can also be configured with filter rules that restrict the set of messages passed to the subscription queue to those that match the filter. 以下示例使用服务总线队列。The following example uses Service Bus queues.

显示 Web 角色、服务总线和辅助角色之间通信的关系图。

与直接消息传送相比,此通信机制具有多项优势:This communication mechanism has several advantages over direct messaging:

  • 暂时分离。Temporal decoupling. 使用异步消息传送模式,生产者和使用者不需要在同一时间联机。With the asynchronous messaging pattern, producers and consumers need not be online at the same time. 服务总线可靠地存储消息,直到使用方准备好接收它们。Service Bus reliably stores messages until the consuming party is ready to receive them. 这会允许分布式应用程序的组件断开连接,例如,为进行维护而自动断开,或因组件故障断开连接,而不会影响系统的整体性能。This enables the components of the distributed application to be disconnected, either voluntarily, for example, for maintenance, or due to a component crash, without impacting the system as a whole. 此外,使用方应用程序可能只需在一天的特定时段内联机。Furthermore, the consuming application might only need to come online during certain times of the day.

  • 负载量。Load leveling. 在许多应用程序中,系统负载随时间而变化,而每个工作单元所需的处理时间通常为常量。In many applications, system load varies over time, while the processing time required for each unit of work is typically constant. 使用队列在消息创建者与使用者之间中继意味着,只需将使用方应用程序(辅助)预配为适应平均负载而非最大负载。Intermediating message producers and consumers with a queue means that the consuming application (the worker) only needs to be provisioned to accommodate average load rather than peak load. 队列深度将随传入负载的变化而加大和减小。The depth of the queue grows and contracts as the incoming load varies. 这会直接根据为应用程序加载提供服务所需的基础结构的数目来节省成本。This directly saves money in terms of the amount of infrastructure required to service the application load.

  • 负载均衡。Load balancing. 随着负载增加,可添加更多的工作进程以从队列中读取。As load increases, more worker processes can be added to read from the queue. 每条消息仅由一个辅助进程处理。Each message is processed by only one of the worker processes. 另外,可通过此基于拉取的负载均衡来以最合理的方式使用辅助计算机,即使这些辅助计算机具有不同的处理能力(因为它们以其最大速率拉取消息)也是如此。Furthermore, this pull-based load balancing enables optimal use of the worker machines even if the worker machines differ in terms of processing power, as they will pull messages at their own maximum rate. 此模式通常称为 使用者竞争 模式。This pattern is often termed the competing consumer pattern.

显示 Web 角色、服务总线和两个辅助角色之间通信的关系图。

以下各节讨论了实现此体系结构的代码。The following sections discuss the code that implements this architecture.

创建命名空间Create a namespace

第一步是创建命名空间 并获取该命名空间的共享访问签名 (SAS) 密钥The first step is to create a namespace, and obtain a Shared Access Signature (SAS) key for that namespace. 命名空间为每个通过服务总线公开的应用程序提供应用程序边界。A namespace provides an application boundary for each application exposed through Service Bus. 创建命名空间后,系统将生成一个 SAS 密钥。A SAS key is generated by the system when a namespace is created. 命名空间名称与 SAS 密钥的组合为服务总线提供了用于验证应用程序访问权限的凭据。The combination of namespace name and SAS key provides the credentials for Service Bus to authenticate access to an application.

在 Azure 门户中创建命名空间Create a namespace in the Azure portal

若要开始在 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. 命名空间提供了用于对应用程序中的 Service Bus 资源进行寻址的范围容器。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, select + Create a resource, select Integration, and then select Service Bus.


  3. 在“创建命名空间”对话框中执行以下步骤 :In the Create namespace dialog, do the following steps:

    1. 输入命名空间的名称Enter a name for the namespace. 系统会立即检查该名称是否可用。The system immediately checks to see if the name is available. 若需用于对命名空间进行命名的规则的列表,请参阅创建命名空间 REST APIFor a list of rules for naming namespaces, see Create Namespace REST API.

    2. 选择命名空间的定价层(“基本”、“标准”或“高级”)。Select the pricing tier (Basic, Standard, or Premium) for the namespace. 若要使用主题和订阅,请选择“标准”或“高级”。If you want to use topics and subscriptions, choose either Standard or Premium. 基本定价层中不支持主题/订阅。Topics/subscriptions are not supported in the Basic pricing tier.

    3. 如果选择了“高级”定价层,请执行以下步骤: If you selected the Premium pricing tier, follow these steps:

      1. 指定消息传送单元的数目。Specify the number of messaging units. 高级层在 CPU 和内存级别提供资源隔离,使每个工作负荷在隔离的环境中运行。The premium tier provides resource isolation at the CPU and memory level so that each workload runs in isolation. 此资源容器称为消息传送单元。This resource container is called a messaging unit. 高级命名空间至少具有一个消息传送单元。A premium namespace has at least one messaging unit. 可为每个服务总线高级命名空间选择 1、2 或 4 个消息传送单元。You can select 1, 2, or 4 messaging units for each Service Bus Premium namespace. 有关详细信息,请参阅服务总线高级消息传送For more information, see Service Bus Premium Messaging.

      2. 指定是否要将命名空间设为区域冗余Specify whether you want to make the namespace zone redundant. 区域冗余通过在一个区域中的所有可用性区域之间分散副本来提供增强的可用性。The zone redundancy provides enhanced availability by spreading replicas across availability zones within one region at no additional cost.

    4. 对于“订阅”,请选择要在其中创建命名空间的 Azure 订阅。 For Subscription, choose an Azure subscription in which to create the namespace.

    5. 对于“资源组”,请选择该命名空间驻留到的现有资源组,或创建一个新资源组。 For Resource group, choose an existing resource group in which the namespace will live, or create a new one.

    6. 对于“位置”,请选择托管该命名空间的区域。 For Location, choose the region in which your namespace should be hosted.

    7. 选择“创建” 。Select 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.


  4. 确认是否已成功部署服务总线命名空间。Confirm that the service bus namespace is deployed successfully. 若要查看通知,请在工具栏上选择钟形图标(警报)To see the notifications, select the bell icon (Alerts) on the toolbar. 如下图所示,在通知中选择资源组的名称Select the name of the resource group in the notification as shown in the image. 将会看到包含服务总线命名空间的资源组。You see the resource group that contains the service bus namespace.


  5. 在资源组的“资源组”页上,选择你的服务总线命名空间On the Resource group page for your resource group, select your service bus namespace.

    “资源组”页 - 选择服务总线命名空间

  6. 将会看到服务总线命名空间的主页。You see the home page for your service bus namespace.


获取连接字符串Get the connection string

创建新的命名空间时,会自动生成一项初始的共享访问签名 (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 rules with more constrained rights for regular senders and receivers. 若要复制命名空间的主要密钥和辅助密钥,请执行以下步骤:To copy the primary and secondary keys for your namespace, 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.


  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.


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

创建 Web 角色Create a web role

在本部分中,会生成应用程序的前端。In this section, you build the front end of your application. 首先,将创建应用程序显示的各种页面。First, you create the pages that your application displays. 之后,将添加代码,以便将项目提交到服务总线队列并显示有关队列的状态信息。After that, add code that submits items to a Service Bus queue and displays status information about the queue.

创建项目Create the project

  1. 使用管理员特权启动 Visual Studio:右键单击“Visual Studio” 程序图标,并单击“以管理员身份运行” 。Using administrator privileges, start Visual Studio: right-click the Visual Studio program icon, and then click Run as administrator. Azure 计算模拟器(本文后面会讨论)要求使用管理员权限启动 Visual Studio。The Azure compute emulator, discussed later in this article, requires that Visual Studio be started with administrator privileges.

    在 Visual Studio 的“文件”菜单中,单击“新建”,再单击“项目” 。In Visual Studio, on the File menu, click New, and then click Project.

  2. 从“Visual C#”下的“已安装模板”中,单击“云”,并单击“Azure 云服务”。From Installed Templates, under Visual C#, click Cloud and then click Azure Cloud Service. MultiTierAppName the project MultiTierApp. 然后单击“确定” 。Then click OK.

    “新建项目”对话框的屏幕截图,其中选择了“云”,并突出显示了“Azure 云服务 Visual C#”并添加了红色边框。

  3. 在“角色”窗格中,双击“ASP.NET Web 角色” 。From the Roles pane, double-click ASP.NET Web Role.

    “新建 Azure 云服务”对话框的屏幕截图,其中选择了“ASP.NET Web 角色”,同时还选择了“WebRole1”。

  4. 将鼠标指针停留在“Azure 云服务解决方案” 下的“WebRole1” 上,单击铅笔图标,并将 Web 角色重命名为“FrontendWebRole” 。Hover over WebRole1 under Azure Cloud Service solution, click the pencil icon, and rename the web role to FrontendWebRole. 然后单击“确定” 。Then click OK. (请确保输入“Frontend”而不是“FrontEnd”,此处为小写“e”。)(Make sure you enter "Frontend" with a lower-case 'e,' not "FrontEnd".)

    “新建 Azure 云服务”对话框的屏幕截图,其中解决方案已重命名为“FrontendWebRole”。

  5. 从“新建 ASP.NET 项目” 对话框的“选择模板” 列表中,单击“MVC” 。From the New ASP.NET Project dialog box, in the Select a template list, click MVC.

    “新建 ASP.NET 项目”对话框的屏幕截图,其中突出显示了“MVC”并添加了红色边框,还对“更改身份验证”选项添加了红色边框。

  6. 仍然在“新建 ASP.NET 项目” 对话框中,单击“更改身份验证” 按钮。Still in the New ASP.NET Project dialog box, click the Change Authentication button. 在“更改身份验证”对话框中,确保已选择“无身份验证”,然后单击“确定” 。In the Change Authentication dialog box, ensure that No Authentication is selected, and then click OK. 在本教程中,将部署无需用户登录名的应用。For this tutorial, you're deploying an app that doesn't need a user login.


  7. 返回到“新建 ASP.NET 项目” 对话框,单击“确定” 以创建项目。Back in the New ASP.NET Project dialog box, click OK to create the project.

  8. 在“解决方案资源管理器”的 FrontendWebRole 项目中,右键单击“引用”,再单击“管理 NuGet 包” 。In Solution Explorer, in the FrontendWebRole project, right-click References, then click Manage NuGet Packages.

  9. 单击“浏览” 选项卡,然后搜索“WindowsAzure.ServiceBus” 。Click the Browse tab, then search for WindowsAzure.ServiceBus. 搜索 WindowsAzure.ServiceBus 包,单击“安装”,并接受使用条款。Select the WindowsAzure.ServiceBus package, click Install, and accept the terms of use.

    “管理 NuGet 包”对话框的屏幕快照,其中突出显示了“WindowsAzure.ServiceBus”,并对“安装”选项添加了红色边框。

    请注意,现已引用所需的客户端程序集并已添加部分新代码文件。Note that the required client assemblies are now referenced and some new code files have been added.

  10. 在“解决方案资源管理器” 中,右键单击“模型” ,并依次单击“添加” 和“类” 。In Solution Explorer, right-click Models and click Add, then click Class. 在“名称” 框中,键入名称“OnlineOrder.cs” 。In the Name box, type the name OnlineOrder.cs. 然后单击“添加” 。Then click Add.

为 Web 角色编写代码Write the code for your web role

在本部分,将创建应用程序显示的各种页面。In this section, you create the various pages that your application displays.

  1. 在 Visual Studio 的 OnlineOrder.cs 文件中,将现有命名空间定义替换为以下代码:In the OnlineOrder.cs file in Visual Studio, replace the existing namespace definition with the following code:

    namespace FrontendWebRole.Models
        public class OnlineOrder
            public string Customer { get; set; }
            public string Product { get; set; }
  2. 在“解决方案资源管理器” 中,双击“Controllers\HomeController.cs” 。In Solution Explorer, double-click Controllers\HomeController.cs. 在文件顶部添加以下 using 语句以包括针对你刚创建的模型以及服务总线的命名空间。Add the following using statements at the top of the file to include the namespaces for the model you just created, as well as Service Bus.

    using FrontendWebRole.Models;
    using Microsoft.ServiceBus.Messaging;
    using Microsoft.ServiceBus;
  3. 仍在 Visual Studio 的 HomeController.cs 文件中,将现有命名空间定义替换为以下代码。Also in the HomeController.cs file in Visual Studio, replace the existing namespace definition with the following code. 此代码包含用于处理将项提交到队列这一任务的方法。This code contains methods for handling the submission of items to the queue.

    namespace FrontendWebRole.Controllers
        public class HomeController : Controller
            public ActionResult Index()
                // Simply redirect to Submit, since Submit will serve as the
                // front page of this application.
                return RedirectToAction("Submit");
            public ActionResult About()
                return View();
            // GET: /Home/Submit.
            // Controller method for a view you will create for the submission
            // form.
            public ActionResult Submit()
                // Will put code for displaying queue message count here.
                return View();
            // POST: /Home/Submit.
            // Controller method for handling submissions from the submission
            // form.
            // Attribute to help prevent cross-site scripting attacks and
            // cross-site request forgery.  
            public ActionResult Submit(OnlineOrder order)
                if (ModelState.IsValid)
                    // Will put code for submitting to queue here.
                    return RedirectToAction("Submit");
                    return View(order);
  4. 在“生成” 菜单中,单击“生成解决方案” 以测试工作的准确性。From the Build menu, click Build Solution to test the accuracy of your work so far.

  5. 现在,为前面创建的 Submit() 方法创建视图。Now, create the view for the Submit() method you created earlier. Submit() 方法(不带任何参数的 Submit() 的重载函数)中右键单击,并选择“添加视图” 。Right-click within the Submit() method (the overload of Submit() that takes no parameters), and then choose Add View.

    代码的屏幕截图,焦点位于 Submit 方法和一个下拉列表,其中突出显示了“添加视图”选项。

  6. 此时会显示一个用于创建视图的对话框。A dialog box appears for creating the view. 在“模板” 列表中,选择“创建” 。In the Template list, choose Create. 在“模型类” 列表中,选择“OnlineOrder” 类。In the Model class list, select the OnlineOrder class.


  7. 单击“添加” 。Click Add.

  8. 现在,请更改应用程序的显示名称。Now, change the displayed name of your application. 在“解决方案资源管理器”中,双击“views/shared\_Layout.cshtml”文件以在 Visual Studio 编辑器中将其打开。In Solution Explorer, double-click the Views\Shared\_Layout.cshtml file to open it in the Visual Studio editor.

  9. 将每一处“My ASP.NET Application”替换为“Northwind Traders Products” 。Replace all occurrences of My ASP.NET Application with Northwind Traders Products.

  10. 删除“Home” 、“About” 和“Contact” 链接。Remove the Home, About, and Contact links. 删除突出显示的代码:Delete the highlighted code:

    代码的截图,其中突出显示了三行 HTML 操作链接代码。

  11. 最后,修改提交页以包含有关队列的一些信息。Finally, modify the submission page to include some information about the queue. 在“解决方案资源管理器” 中,双击“Views\Home\Submit.cshtml” 文件以在 Visual Studio 编辑器中将其打开。In Solution Explorer, double-click the Views\Home\Submit.cshtml file to open it in the Visual Studio editor. <h2>Submit</h2>后面添加以下行。Add the following line after <h2>Submit</h2>. ViewBag.MessageCount 当前为空。For now, the ViewBag.MessageCount is empty. 稍后将填充它。You will populate it later.

    <p>Current number of orders in queue waiting to be processed: @ViewBag.MessageCount</p>
  12. 现在,已实现 UI。You now have implemented your UI. 可以按 F5 运行应用程序并确认其按预期方式运行。You can press F5 to run your application and confirm that it looks as expected.


编写用于将项提交到 Service Bus 队列的代码Write the code for submitting items to a Service Bus queue

现在,将添加用于将项提交到队列的代码。Now, add code for submitting items to a queue. 首先,将创建一个包含服务总线队列连接信息的类。First, you create a class that contains your Service Bus queue connection information. 然后,将从 Global.aspx.cs 初始化连接。Then, initialize your connection from Global.aspx.cs. 最后,将更新你之前在 HomeController.cs 中创建的提交代码以便实际将项提交到服务总线队列。Finally, update the submission code you created earlier in HomeController.cs to actually submit items to a Service Bus queue.

  1. 在“解决方案资源管理器” 中,右键单击“FrontendWebRole” (右键单击项目而不是角色)。In Solution Explorer, right-click FrontendWebRole (right-click the project, not the role). 单击“添加” ,并单击“类” 。Click Add, and then click Class.

  2. 将类命名为 QueueConnector.csName the class QueueConnector.cs. 单击“添加” 以创建类。Click Add to create the class.

  3. 现在,将添加可封装连接信息并初始化服务总线队列连接的代码。Now, add code that encapsulates the connection information and initializes the connection to a Service Bus queue. 将 QueueConnector.cs 的全部内容替换为下面的代码,并输入 your Service Bus namespace(命名空间名称)和 yourKey(之前从 Azure 门户中获取的主要密钥)的值。Replace the entire contents of QueueConnector.cs with the following code, and enter values for your Service Bus namespace (your namespace name) and yourKey, which is the primary key you previously obtained from the Azure portal.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using Microsoft.ServiceBus.Messaging;
    using Microsoft.ServiceBus;
    namespace FrontendWebRole
        public static class QueueConnector
            // Thread-safe. Recommended that you cache rather than recreating it
            // on every request.
            public static QueueClient OrdersQueueClient;
            // Obtain these values from the portal.
            public const string Namespace = "your Service Bus namespace";
            // The name of your queue.
            public const string QueueName = "OrdersQueue";
            public static NamespaceManager CreateNamespaceManager()
                // Create the namespace manager which gives you access to
                // management operations.
                var uri = ServiceBusEnvironment.CreateServiceUri(
                    "sb", Namespace, String.Empty);
                var tP = TokenProvider.CreateSharedAccessSignatureTokenProvider(
                    "RootManageSharedAccessKey", "yourKey");
                return new NamespaceManager(uri, tP);
            public static void Initialize()
                // Using Http to be friendly with outbound firewalls.
                ServiceBusEnvironment.SystemConnectivity.Mode =
                // Create the namespace manager which gives you access to
                // management operations.
                var namespaceManager = CreateNamespaceManager();
                // Create the queue if it does not exist already.
                if (!namespaceManager.QueueExists(QueueName))
                // Get a client to the queue.
                var messagingFactory = MessagingFactory.Create(
                OrdersQueueClient = messagingFactory.CreateQueueClient(
  4. 现在,请确保 Initialize 方法会被调用。Now, ensure that your Initialize method gets called. 在“解决方案资源管理器” 中,双击“Global.asax\Global.asax.cs” 。In Solution Explorer, double-click Global.asax\Global.asax.cs.

  5. Application_Start 方法的末尾添加以下代码行。Add the following line of code at the end of the Application_Start method.

  6. 最后,更新之前创建的 Web 代码以便将项提交到队列。Finally, update the web code you created earlier, to submit items to the queue. 在“解决方案资源管理器” 中,双击“Controllers\HomeController.cs” 。In Solution Explorer, double-click Controllers\HomeController.cs.

  7. 更新 Submit() 方法(不包含任何参数的重载),如下所示,获取队列的消息计数。Update the Submit() method (the overload that takes no parameters) as follows to get the message count for the queue.

    public ActionResult Submit()
        // Get a NamespaceManager which allows you to perform management and
        // diagnostic operations on your Service Bus queues.
        var namespaceManager = QueueConnector.CreateNamespaceManager();
        // Get the queue, and obtain the message count.
        var queue = namespaceManager.GetQueue(QueueConnector.QueueName);
        ViewBag.MessageCount = queue.MessageCount;
        return View();
  8. 更新 Submit(OnlineOrder order) 方法(包含一个参数的重载),如下所示,将订单信息提交到队列。Update the Submit(OnlineOrder order) method (the overload that takes one parameter) as follows to submit order information to the queue.

    public ActionResult Submit(OnlineOrder order)
        if (ModelState.IsValid)
            // Create a message from the order.
            var message = new BrokeredMessage(order);
            // Submit the order.
            return RedirectToAction("Submit");
            return View(order);
  9. 现在,可以重新运行应用程序。You can now run the application again. 每提交订单时,消息计数都会增大。Each time you submit an order, the message count increases.

    应用程序的“提交”页的屏幕截图,其中显示消息计数递增到 1。

创建辅助角色Create the worker role

现在,将创建用于处理订单提交的辅助角色。You will now create the worker role that processes the order submissions. 此示例使用“服务总线队列的辅助角色” Visual Studio 项目模板。This example uses the Worker Role with Service Bus Queue Visual Studio project template. 已从门户中获取所需的凭据。You already obtained the required credentials from the portal.

  1. 确保已将 Visual Studio 连接到 Azure 帐户。Make sure you have connected Visual Studio to your Azure account.

  2. 在 Visual Studio 的“解决方案资源管理器”中,右键单击 MultiTierApp 项目下的“角色”文件夹 。In Visual Studio, in Solution Explorer right-click the Roles folder under the MultiTierApp project.

  3. 单击“添加” ,并单击“新建辅助角色项目” 。Click Add, and then click New Worker Role Project. 此时会显示“添加新角色项目” 对话框。The Add New Role Project dialog box appears.


  4. 在“添加新角色项目” 对话框中,单击“服务总线队列的辅助角色” 。In the Add New Role Project dialog box, click Worker Role with Service Bus Queue.


  5. 在“名称” 框中,将项目命名为“OrderProcessingRole” 。In the Name box, name the project OrderProcessingRole. 然后单击“添加” 。Then click Add.

  6. 将在“创建服务总线命名空间”部分的步骤 9 中获取的连接字符串复制到剪贴板。Copy the connection string that you obtained in step 9 of the "Create a Service Bus namespace" section to the clipboard.

  7. 在“解决方案资源管理器”中,右键单击在步骤 5 中创建的“OrderProcessingRole”(确保右键单击“角色”下的“OrderProcessingRole”而不是类)。In Solution Explorer, right-click the OrderProcessingRole you created in step 5 (make sure that you right-click OrderProcessingRole under Roles, and not the class). 然后单击“属性” 。Then click Properties.

  8. 在“属性”对话框的“设置”选项卡中,在“Microsoft.ServiceBus.ConnectionString”的“值”框内单击,并粘贴在步骤 6 中复制的终结点值。On the Settings tab of the Properties dialog box, click inside the Value box for Microsoft.ServiceBus.ConnectionString, and then paste the endpoint value you copied in step 6.


  9. 从队列中处理订单时,创建一个 OnlineOrder 类来表示这些订单。Create an OnlineOrder class to represent the orders as you process them from the queue. 可以重用已创建的类。You can reuse a class you have already created. 在“解决方案资源管理器” 中,右键单击“OrderProcessingRole” 类(右键单击类图标,而不是角色)。In Solution Explorer, right-click the OrderProcessingRole class (right-click the class icon, not the role). 单击“添加” ,并单击“现有项” 。Click Add, then click Existing Item.

  10. 浏览到 FrontendWebRole\Models 的子文件夹,然后双击“OnlineOrder.cs” 以将其添加到此项目中。Browse to the subfolder for FrontendWebRole\Models, and then double-click OnlineOrder.cs to add it to this project.

  11. WorkerRole.cs 中,将 QueueName 变量的值 "ProcessingQueue" 更改为 "OrdersQueue",如以下代码所示。In WorkerRole.cs, change the value of the QueueName variable from "ProcessingQueue" to "OrdersQueue" as shown in the following code.

    // The name of your queue.
    const string QueueName = "OrdersQueue";
  12. 在 WorkerRole.cs 文件顶部添加以下 using 语句。Add the following using statement at the top of the WorkerRole.cs file.

    using FrontendWebRole.Models;
  13. Run() 函数中,在 OnMessage() 调用的内部,将 try 子句的内容替换为以下代码。In the Run() function, inside the OnMessage() call, replace the contents of the try clause with the following code.

    Trace.WriteLine("Processing", receivedMessage.SequenceNumber.ToString());
    // View the message as an OnlineOrder.
    OnlineOrder order = receivedMessage.GetBody<OnlineOrder>();
    Trace.WriteLine(order.Customer + ": " + order.Product, "ProcessingMessage");
  14. 已完成此应用程序。You have completed the application. 可以测试整个应用程序,方法是右键单击“解决方案资源管理器”中的 MultiTierApp 项目,选择“设置为启动项目” ,然后按 F5。You can test the full application by right-clicking the MultiTierApp project in Solution Explorer, selecting Set as Startup Project, and then pressing F5. 请注意,消息计数不会递增,因为辅助角色会处理队列中的项并将其标记为完成。Note that the message count does not increment, because the worker role processes items from the queue and marks them as complete. 可以通过查看 Azure 计算模拟器 UI 来查看辅助角色的跟踪输出。You can see the trace output of your worker role by viewing the Azure Compute Emulator UI. 可通过右击任务栏的通知区域中的模拟器图标并选择“显示计算模拟器 UI” 来执行此操作。You can do this by right-clicking the emulator icon in the notification area of your taskbar and selecting Show Compute Emulator UI.


    Azure 计算模拟器 (Express) 对话框的屏幕截图。

后续步骤Next steps

若要了解有关 Service Bus 的详细信息,请参阅以下资源:To learn more about Service Bus, see the following resources:

若要了解有关多层方案的详细信息,请参阅:To learn more about multi-tier scenarios, see: