利用Ajax+MSMQ(訊息佇列)+WebService實現伺服器端向用戶端的資訊推送

來源:互聯網
上載者:User

標籤:

需求:

每當資料庫有資料更新時,推送到用戶端

軟需求:

1、伺服器資源有限,要求資源佔用儘可能小;

2、項目可控,不許調用第三方不可信不穩定的方法。

已有案例:

1、58到家採用的方法是TCP的長串連,對伺服器壓力較大;

2、redis等提供了訂閱推送服務,開源,但是定製化對開發人員其開發語言水平要求較高,筆者水平達不到

最終方案:

解釋:

①②頁面載入時第一次請求資料,返回資料,載入,調用ajax2

③頁面載入即發出請求,但是此時沒有資料,於是就block,等待其他組件insert msg

④收取新msg後,傳回值給ajax2

⑤ajax2調用ajax1

⑥ajax1重新整理資料

block後ajax2隻在伺服器佔用一個線程,資源消耗很小。

===================下面是代碼=======================

1、檔案結構

2、receive.cs//MSMQ的接收類

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Messaging;namespace WebApplication1{    public class receive    {        public String receives()        {            var queue = new MessageQueue(@".\private$\MsgQueue");            queue.Formatter = new XmlMessageFormatter(                new string[] { "System.String" }                );            Message m = queue.Receive();            return m.Body.ToString();        }    }}

2、send.cs//MSMQ的發送類

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Messaging;namespace WebApplication1{    public class send    {        public string create(String msg)        {            try            {                if (!MessageQueue.Exists(@".\private$\MsgQueue"))                {                    MessageQueue.Create(@".\private$\MsgQueue");                }                var queue = new MessageQueue(@".\private$\MsgQueue");                queue.Send(msg, "Label");                return "ok";            }            catch (Exception ex)            {                return "error";            }        }    }}

3、MQGiver.asmx//核心WebService

using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.Services;using WebApplication1;namespace 伺服器接收mq{    /// <summary>    /// MQGiver 的摘要說明    /// </summary>    [WebService(Namespace = "http://tempuri.org/")]    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]    [System.ComponentModel.ToolboxItem(false)]    // 若要允許使用 ASP.NET AJAX 從指令碼中調用此 Web 服務,請取消對下行的注釋。    // [System.Web.Script.Services.ScriptService]    [Serializable]    public class MQGiver : System.Web.Services.WebService    {        [WebMethod]        public string HelloWorld()        {            return "Hello World";        }        [WebMethod]        public void GiveMsg()        {            receive r = new receive();            String msg = r.receives();            String Json = "{\"msg\":\"" + msg + "\"}";            string callback = HttpContext.Current.Request["jsoncallback"];            HttpContext.Current.Response.Write(callback + "(" + Json + ")");        }        [WebMethod]        public void GiveData()        {            String Json = "{\"msg\":\"ok\"}";            string callback = HttpContext.Current.Request["jsoncallback"];            HttpContext.Current.Response.Write(callback + "(" + Json + ")");        }    }}

4、MSGadd.aspx//類比向MSMQ添加資料

前台代碼<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="MSGadd.aspx.cs" Inherits="伺服器接收mq.MSGadd" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server">    <title></title></head><body>    <form id="form1" runat="server">    <div>        </div>    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>    </form></body></html>//================================================後台代碼using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using WebApplication1;namespace 伺服器接收mq{    public partial class MSGadd : System.Web.UI.Page    {        protected void Page_Load(object sender, EventArgs e)        {        }        protected void Button1_Click(object sender, EventArgs e)        {            send s = new send();            Label1.Text = s.create(TextBox1.Text);        }    }}

5、調用介面

<html><head>    <!--自己注意jq包的引用-->    <script src="jq.js"></script></head><body>    <script type="text/javascript">    function getdata(){        $.ajax({            url: "http://localhost:55843/MQGiver.asmx/GiveData?jsoncallback=?",            dataType: "jsonp",            success: OnSuccess,        });        function OnSuccess(json) {            $("#la").text(json.msg)            getmsg();        }    }            function getmsg(){    $.ajax({            url: "http://localhost:55843/MQGiver.asmx/GiveMsg?jsoncallback=?",            dataType: "jsonp",            success: OnSuccess1,            });        function OnSuccess1(json1) {            getdata();        }    }        getdata();    </script>    <label id="la">    </label></body></html>

整個項目就是這樣的,已通,有好的建議和問題歡迎留言!

利用Ajax+MSMQ(訊息佇列)+WebService實現伺服器端向用戶端的資訊推送

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.