《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 RoleWorker 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相关推荐

  1. Windows Azure Service Bus (5) 主题(Topic) 使用VS2013开发Service Bus Topic

    <Windows Azure Platform 系列文章目录> 项目文件,请在这里下载 在笔者之前的文章中Windows Azure Service Bus (1) 基础 介绍了Servi ...

  2. 微软云之路——Windows Azure 学习

    今天参与了灵通公司举办的微软云之路Windows Azure的培训,主要讲了Windows Azure提供的PaaS服务. 云端提供开发平台和服务器资源.具体先在云端建立host机,数据库账户.再在本 ...

  3. Windows Azure HandBook (5) Azure混合云解决方案

    <Windows Azure Platform 系列文章目录> 在很多情况下,我们都会遇到本地私有云和公有云做互通互联的混合云场景.对于这种混合云的场景,微软的Windows Azure会 ...

  4. Windows Azure实战pdf

    下载地址:网盘下载 内容简介  · · · · · · 本书应该是当下Windows Azure领域最具权威性.完整性和实用性,同时也是最与时俱进(结合最新技术)的书籍之一,由微软官方资深云计算专家撰 ...

  5. Windows Azure服务购买,收费,使用注意事项及学习资料推荐

    Windows Azure服务购买,收费,使用注意事项及学习资料推荐 近来,QQ群里不少朋友比较关注Windows Azure,然而又仿佛不知道怎么入手.怎么开始开发,部署这些是技术细节,相信难不倒大 ...

  6. Windows Azure Mobile Services增加了对 Android的支持并扩展其适用范围至东亚地区

    我们的Mobile Services使开发人员很容易地开发丰富多彩的移动应用程序.使用Mobile Services ,开发人员不仅能够连接其应用程序到 Windows Azure 上易扩展又安全的后 ...

  7. 在Windows Azure中使用自己的域名

    请参考:http://blog.smarx.com/posts/custom-domain-names-in-windows-azure 本文是对这篇文章部分解释和补充. 并请记住,此博客总是能给你在 ...

  8. 现实世界的 Windows Azure:HRG将应用程序扩展到移动设备,削减80 %的启动成本

    作为现实世界 Windows Azure 系列的一部分,我们联系了Hogg Robinson Group (HRG)的技术和产品开发主任Paul Saggar, 了解关于如何如何在Windows Az ...

  9. Windows Azure案例:迈阿密市政府使用“云”平台改善服务方案,降低运营成本

    公告   :本博客为微软云计算中文博客 的镜像博客. 部分文章因为博客兼容性问题 ,会影响阅读体验 .如遇此情况,请访问 原博客   . 市政府使用"云"改善服务方案,降低成本 迈 ...

最新文章

  1. jQuery 图片剪裁插件初探之 Jcrop
  2. react 合并数组_React快速上手
  3. CloudFoundry和BOSH的关系
  4. ffmpeg 转换flv压缩大小_ffmpeg转换参数和压缩输出大小的比率 参考 最新版本FFMPEG...
  5. ARC106E-Medals【hall定理,高维前缀和】
  6. 主要矛盾和次要矛盾_次要GC,主要GC与完整GC
  7. 怎么测试网络带宽_性能测试案例与经验分享
  8. charles 安装 ssl_「从零开始Python爬虫」1.7.1 Charles的安装与配置
  9. 计算机视觉基础-图像处理(图像分割/二值化)cpp+python
  10. 华为hs8545m如何复位_在华为东莞松山湖基地,见证一场始于AI质检的智能制造变革...
  11. lisp pline 加点_在cad中如何创建lisp程序?以及大神们所说的lisp解决重复性劳动问题是怎么回事?...
  12. Windows下使用platform.pk8 和platform.x509.pem生成jks签名文件
  13. 十分钟完成安卓 MediaCodec 视频解码
  14. Student‘s t分布
  15. Cookie跨域setDomain
  16. Jenkins常用插件之Publish Over SSH
  17. [php] thinkphp实现 163 qq 邮箱收发邮件(切实可用)
  18. c语言大小箱子,基于C语言箱子游戏.doc
  19. 520 送女朋友礼物大全 (推荐男生收藏)
  20. FormData对象用法

热门文章

  1. java习题8,Java经典练习题8
  2. 常见WEB漏洞描述及修复建议(可收藏写报告用)-句芒安全实验室
  3. MINIGUI常见错误集及解决方法
  4. php申请证书,用phpstudy来申请SSL证书
  5. linux中的vsprintf_Git29 年超 100 万次 commit,Linux 内核何以发展至今?
  6. activemq 控制台怎么看生产信息_Jmeter中间件处理-ActiveMQ
  7. nao机器人行走速度_震撼!寒冬腊月里惊现多台历途外墙清洗机器人
  8. java环境变量设置的作用_JDK环境变量的配置及作用
  9. 气温常年在25度的地方_最低调的海滨城市,物价便宜,常年25度,沙滩细白,不输三亚!...
  10. c语言for循环运行格式,关于for循环的格式