使用 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 screen shot 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.

与直接消息传送相比,此通信机制具有多项优势: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.

以下各节讨论了实现此体系结构的代码。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 中使用服务总线消息实体,必须先使用在 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.

创建 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.

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

  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".)

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

    请注意,现已引用所需的客户端程序集并已添加部分新代码文件。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.
            [HttpPost]
            // Attribute to help prevent cross-site scripting attacks and
            // cross-site request forgery.  
            [ValidateAntiForgeryToken]
            public ActionResult Submit(OnlineOrder order)
            {
                if (ModelState.IsValid)
                {
                    // Will put code for submitting to queue here.
    
                    return RedirectToAction("Submit");
                }
                else
                {
                    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.

  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 ProductsReplace 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:

  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.

编写用于将项提交到服务总线队列的代码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 =
                    ConnectivityMode.Http;
    
                // 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))
                {
                    namespaceManager.CreateQueue(QueueName);
                }
    
                // Get a client to the queue.
                var messagingFactory = MessagingFactory.Create(
                    namespaceManager.Address,
                    namespaceManager.Settings.TokenProvider);
                OrdersQueueClient = messagingFactory.CreateQueueClient(
                    "OrdersQueue");
            }
        }
    }
    
  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.

    FrontendWebRole.QueueConnector.Initialize();
    
  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.
            QueueConnector.OrdersQueueClient.Send(message);
            return RedirectToAction("Submit");
        }
        else
        {
            return View(order);
        }
    }
    
  9. 现在,可以重新运行应用程序。You can now run the application again. 每提交订单时,消息计数都会增大。Each time you submit an order, the message count increases.

创建辅助角色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");
    receivedMessage.Complete();
    
  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.

后续步骤Next steps

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

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