Asp.netSignalR实现服务端消息推送到Web端之前的文章介绍过Asp.netSignalR,ASP.NETSignalR是一个ASP.NET下的类库,可以在ASP.NET的Web项目中实现实时通信.今天我们来实现服务端消息推送到Web端,首先回顾一下它抽象层次图是这样的:实际上Asp.netSignalR2实现服务端消息推送到Web端,更加简单.为了获取更好的可伸缩性,我们引入消息队列,看如下基本流程图:消息队列MQ监听,在Website服务端一收到消息,马上通过Signalr推送广播到客户端.创建ASP.NETMVCWEBAPP,从NuGet安装SignalR2.12Install-PackageMicrosoft.AspNet.SignalR具体实现代码,是这样的,我们增加一个空的Hub:publicclassFeedHub:Hub{publicvoidInit(){}}是简单的消息模型,标题与正文属性:[Serializable]publicclassPushMessageModel{publicintId{get;set;}publicstringMSG_TITLE{get;set;}publicstringMSG_CONTENT{get;set;}}服务端推送具体类,记录日志,创建消息队列实例,监听,等待收取消息.这里我们使用的是AcitveMQ的.net客户端.ActiveMQListenAdapter是一个封装过的对象.publicclassMQHubsConfig{privatestaticILoggerlog=newLogger("MQHubsConfig");///
///Registersthemqlistenandhubs.///publicstaticvoidRegisterMQListenAndHubs(){varactivemq=Megadotnet.MessageMQ.Adapter.ActiveMQListenAdapter
.Instance(MQConfig.MQIpAddress,MQConfig.QueueDestination);activemq.MQListener+=m=>{log.InfoFormat("从MQ收到消息{0}",m.MSG_CONTENT);GlobalHost.ConnectionManager.GetHubContext().Clients.All.receive(m);};activemq.ReceviceListener();}}上面有一句关键代码GlobalHost.ConnectionManager.GetHubContext().Clients.All.receive(m);这里使用了GetHubContext方法后,直接来广播消息.需要在MVCApplication下加载:publicclassMvcApplication:System.Web.HttpApplication{protectedvoidApplication_Start(){AreaRegistration.RegisterAllAreas();FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);RouteConfig.RegisterRoutes(RouteTable.Routes);BundleConfig.RegisterBundles(BundleTable.Bundles);MQHubsConfig.RegisterMQListenAndHubs();}}同时需要增加一个Starup.cs,用于Owin[assembly:OwinStartup(typeof(RealTimeApp.Startup))]namespaceRealTimeApp{publicclassStartup{publicvoidConfiguration(IAppBuilderapp){//Anyconnectionorhubwireupandconfigurationshouldgohereapp.MapSignalR();}}}接下来是客户端App.js:functionApp(){varinit=function(){Feed();$.connection.hub.logging=true;$.connection.hub.start().done(function(){console.log("Connected!");$(document).trigger("Connected");}).fail(function(){console.log("CouldnotConnect!");});};init();};Feed.js具体与SignalR.js通信,创建名为receive的function,与服务端对应functionFeed(){varchat=undefined;varinit=function(){//Referencetheauto-generatedproxyforthehub.chat=$.connection.feedHub;//Createafunctionthatthehubcancallbacktodisplaymessages.chat.client.receive=function(item){varselector="ul.feed-listli[data-id="+item.Id+"]";if(!($(selector).length>0)){$("ul.feed-list").prepend($(".feed-template").render(item));$("ul.feed-listli:gt(3)").remove();}$.messager.show({title:'Tips',msg:item.MSG_CONTENT,showType:'show'});};//Starttheconnection.$.connection.hub.start().done(function(){chat.server.init();});};init();};上面的javascript代码与服务端有通信,具体看如下图:在Index.cshtml,我们需要引用SignalR客户端JS,放置hubs,这里我们使用了jsrender,easyui.js来呈现推送的消息.@modeldynamic@sectionScripts{