Windows Azure Service Bus (3) 队列(Queue) 使用VS2013开发Service Bus Queue
《Windows Azure Platform 系列文章目錄》
在之前的Azure Service Bus中,我們已經介紹了Service Bus 隊列(Queue)的基本概念。
在本章中,筆者將介紹如何使用Visual Studio 2013,開發一個Service Bus Queue的Demo Project。
?
場景:
1.在前端有一個ASP.NET頁面,客戶從輸入框輸入數據,并且通過按鈕進行提交
2.輸入框輸入的數據,會被后端的WorkerRoleWithSBQueue接受處理,并在后端顯示
主要步驟有:
1.使用Azure Management Portal,創建Service Bus
2.修改Web Role邏輯
3.創建Cloud Project,添加Web Role和Service Bus Worker Role
4.配置WebRole和ServiceBusWorkerRole
3.DEMO
?
?
一.筆者已經在之前的文章中,介紹如何創建Service Bus了。不熟悉的讀者,可以參考Windows Azure Service Bus (2) 隊列(Queue)入門
二.創建Cloud Project
1.首先我們以管理員身份,運行VS2013
2.創建一個新的Cloud Service,命名為LeiServiceBusQueue,如下圖:
3.增加ASP.NET Web Role和Worker Role with Service Bus Queue。如下圖
?
?
?
二.設置WorkerRoleWithSBQueue1
1.在WorkerRoleWithSBQueue1項目中,修改WorkerRole.cs代碼,如下:
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net; using System.Threading; using Microsoft.ServiceBus; using Microsoft.ServiceBus.Messaging; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.ServiceRuntime;namespace WorkerRoleWithSBQueue1 {public class WorkerRole : RoleEntryPoint{// The name of your queueconst string QueueName = "ProcessingQueue";// QueueClient is thread-safe. Recommended that you cache // rather than recreating it on every request QueueClient Client;ManualResetEvent CompletedEvent = new ManualResetEvent(false);public override void Run(){Trace.WriteLine("Starting processing of messages");// Initiates the message pump and callback is invoked for each message that is received, calling close on the client will stop the pump.Client.OnMessage((receivedMessage) =>{try{// Process the messageTrace.WriteLine("Processing Service Bus message: " + receivedMessage.SequenceNumber.ToString());string received = receivedMessage.GetBody<string>();Trace.WriteLine("You input is" + received);}catch{// Handle any message processing specific exceptions here }});CompletedEvent.WaitOne();}public override bool OnStart(){// Set the maximum number of concurrent connections ServicePointManager.DefaultConnectionLimit = 12;// Create the queue if it does not exist alreadystring connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);if (!namespaceManager.QueueExists(QueueName)){namespaceManager.CreateQueue(QueueName);}// Initialize the connection to Service Bus QueueClient = QueueClient.CreateFromConnectionString(connectionString, QueueName);return base.OnStart();}public override void OnStop(){// Close the connection to Service Bus Queue Client.Close();CompletedEvent.Set();base.OnStop();}} }
?
在上面的WokerRole.cs類代碼中,分為兩個邏輯:
(1)OnStart函數,表示WorkerRole在啟動的時候,初始化了ProcessingQueue對象
(2)Run函數,表示在WorkerRole在執行的時候,將ProcessingQueue的內容輸出
?
?
?
三.設置Web Role
1.在Web Role的根目錄下,創建一個新的ASPX頁面,重命名為ServiceBusQueue.aspx
在ServiceBusQueue.aspx頁面中,
- 增加一個TextBox控件,重命名為txbInput
- 增加一個Button控件,重命名為BtnSend
2.在WebRole1項目中,增加NuGet,添加ServiceBus引用。如下圖:
3.在ServiceBusQueue.aspx.cs中,增加如下代碼
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls;using Microsoft.WindowsAzure; using Microsoft.ServiceBus; using Microsoft.ServiceBus.Messaging;namespace WebRole1 {public partial class ServiceBusQueue : System.Web.UI.Page{const string QueueName = "ProcessingQueue";protected void Page_Load(object sender, EventArgs e){}protected void BtnSend_Click(object sender, EventArgs e){string strinput = txbInput.Text.ToString();Send(strinput);txbInput.Text = string.Empty;}private void Send(string text){string connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");MessagingFactory factory = MessagingFactory.CreateFromConnectionString(connectionString);// Initialize the connection to Service Bus QueueMessageSender sender = factory.CreateMessageSender(QueueName);BrokeredMessage message1 = new BrokeredMessage(text);sender.Send(message1);}} }
上面的代碼中,會將用戶從界面的輸入值,插入到ProcessingQueue對象中
?
?
?
四.配置WebRole和ServiceBusWorkerRole
我們修改WebRole的配置文件,如下圖:
在WebRole1的Settings中,點擊Add Setting增加Microsoft.ServiceBus.ConnectionString對象,如下圖:
上圖中,需要將Value值修改為我們在Azure Management Portal中創建的ServiceBus連接字符串,如下圖:
?
修改完畢后,我們需要修改ServiceBusWorkerRole的配置文件
將Microsoft.ServiceBus.ConnectionString的Value屬性,修改為我們在Azure Management Portal中創建的ServiceBus連接字符串。如下圖:
?
?
五.然后我們用Visual Studio的Azure模擬器運行。
我們依次在ServiceBusQueue.aspx中,輸入不同的值。如下圖:
? ? ? ? ? ? ? ? ? ??
我們可以在Azure Compute模擬器中,查看到2次輸入的結果。如下圖:
?
可以觀察到,首先輸入的值,最先被處理。這也說明了Service Bus Queue 先進先出的特性。
?
最后我們還可以在Management Portal中,查看到由代碼生成的processingqueue對象
?
?
=====================================分隔符=======================================================
?
看到最后,如果有讀者覺得,從Azure Compute Emulator查看到aspx頁面的輸入,這也太不智能啦。
放心,其實我們可以將aspx頁面的輸入,返回到另外的ReturnQueue對象中去,并在前端aspx進行顯示:
(1)ProcessingQueue:插入(Send)數據
(2)ProcessingQueue:返回(Receive)數據
?
別問我為什么不能保存到代碼中申明的ProcessingQueue中,筆者試驗過,不能對ProcessingQueue同時執行Send和Receive操作
?
ServiceBusQueue.aspx.cs代碼如下
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls;using Microsoft.WindowsAzure; using Microsoft.ServiceBus; using Microsoft.ServiceBus.Messaging;namespace WebRole1 {public partial class ServiceBusQueue : System.Web.UI.Page{const string QueueName = "ProcessingQueue";const string ReturnQueueName = "ReturnQueue";protected void Page_Load(object sender, EventArgs e){}protected void BtnSend_Click(object sender, EventArgs e){string strinput = txbInput.Text.ToString();Send(strinput);txbInput.Text = string.Empty;}private void Send(string text){string connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");MessagingFactory factory = MessagingFactory.CreateFromConnectionString(connectionString);// Initialize the connection to Service Bus QueueMessageSender sender = factory.CreateMessageSender(QueueName);BrokeredMessage message1 = new BrokeredMessage(text);sender.Send(message1);}protected void btnReceiveMessage_Click(object sender, EventArgs e){string connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");QueueClient Client = QueueClient.CreateFromConnectionString(connectionString, ReturnQueueName);var message = Client.Receive(TimeSpan.FromSeconds(3));if (message != null){var ret = message.GetBody<string>();message.Complete();}}} }?
WorkerRole.cs代碼如下:
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net; using System.Threading; using Microsoft.ServiceBus; using Microsoft.ServiceBus.Messaging; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.ServiceRuntime;namespace WorkerRoleWithSBQueue1 {public class WorkerRole : RoleEntryPoint{// The name of your queueconst string QueueName = "ProcessingQueue";const string ReturnQueueName = "ReturnQueue";// QueueClient is thread-safe. Recommended that you cache // rather than recreating it on every request QueueClient Client;ManualResetEvent CompletedEvent = new ManualResetEvent(false);public override void Run(){Trace.WriteLine("Starting processing of messages");// Initiates the message pump and callback is invoked for each message that is received, calling close on the client will stop the pump.Client.OnMessage((receivedMessage) =>{try{// Process the messageTrace.WriteLine("Processing Service Bus message: " + receivedMessage.SequenceNumber.ToString());string received = receivedMessage.GetBody<string>();Trace.WriteLine("You input is" + received);SendToReturnQueue(ReturnQueueName, received);}catch{// Handle any message processing specific exceptions here }});CompletedEvent.WaitOne();}private void SendToReturnQueue(string queueName, string inputString){ string connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");MessagingFactory factory = MessagingFactory.CreateFromConnectionString(connectionString);// Initialize the connection to Service Bus QueueMessageSender sender = factory.CreateMessageSender(queueName);BrokeredMessage message1 = new BrokeredMessage(inputString);sender.Send(message1);}public override bool OnStart(){// Set the maximum number of concurrent connections ServicePointManager.DefaultConnectionLimit = 12;// Create the queue if it does not exist alreadystring connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);if (!namespaceManager.QueueExists(QueueName)){namespaceManager.CreateQueue(QueueName);}if (!namespaceManager.QueueExists(ReturnQueueName)){namespaceManager.CreateQueue(ReturnQueueName);}// Initialize the connection to Service Bus QueueClient = QueueClient.CreateFromConnectionString(connectionString, QueueName);return base.OnStart();}public override void OnStop(){// Close the connection to Service Bus Queue Client.Close();CompletedEvent.Set();base.OnStop();}} }?
?
?
本博-三石Blog(下文簡稱本博),在本博客文章結尾處右下腳未注明轉載、來源、出處的作品(內容)均為本博原創,本站對于原創作品內容對其保留版權,請勿隨意轉載,如若真有需要的朋友可以發Mail聯系我;轉載本博原創作品(內容)也必須遵循“署名-非商業用途-保持一致”的創作共用協議,請務必以文字鏈接的形式標明或保留文章原始出處和博客作者(Lei Zhang)的信息,關于本博攝影作品請務必注意保留(www.cnblog.com/threestone)等相關水印版權信息,否則視為侵犯原創版權行為;本博謝絕商業網站轉載。版權所有,禁止一切有違中華人民共和國著作權保護法及相關法律和本博(法律)聲明的非法及惡意抄襲。
?
總結
以上是生活随笔為你收集整理的Windows Azure Service Bus (3) 队列(Queue) 使用VS2013开发Service Bus Queue的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LINQ之路 2:C# 3.0的语言功能
- 下一篇: java信息管理系统总结_java实现科