系统减轻数据峰值办法(MSMQ)

在做一个证券系统,服务器接收的数据量特别频繁,也是为了系统的可扩展性,系统设计如下:接收数据-->MSMQ队列-->处理业务-->MSMQ队列-->返回信息,通过接口把数据接收存放到MSMQ实现。


MSMQ可以应用到很多地方,现在把思路放出来,给各位朋友参考参考,或许已经过时了,但总希望能有人需要吧!

首先引用命名空间:  using System.Messaging;

        private static bool InsertData(string mqName, object obj)
        {
            bool flag = false;
            if (mqName == null || mqName.Length == 0)
            {
                throw new ArgumentNullException("mqName", "mqName is null");
            }
            if (!MessageQueue.Exists(@".\private$\" + mqName))
            {
  throw new ArgumentNullException("mqName", "mqName isn't exists");
            }
           
            try
            {
                MessageQueue meQu = new MessageQueue(@".\private$\" + mqName);

                Message mes = new Message();
                mes.Body = obj;
                mes.Formatter = new XmlMessageFormatter(new Type[] { typeof(clsSt) });  //clsSt为类名
                meQu.Send(mes);

                mes.Dispose();
                 meQu.Close();

                flag = true;

            }
            catch(Exception Ex)
            {
               throw Ex;
            }

            return flag;

        }
这样就完成了向MSMQ插入数据的操作,如果将来有需要修改接收数据模块,则是完成独立出来修改都没有问题的.方便日后系统扩展.下面处理业务模块就需要从MSMQ读取消息,当有MSMQ有消息时,则马上读取消息把内容读取出来进行处理,这里其实需要一个程序不停的监测MSMQ就可以了.下面就是读取MSMQ里面的消息代码:
       private static clsSt ReadMes(string mqName)
        {
            clsSt clsStRead = null;
            if (mqName == null || mqName.Length == 0)
            {
                throw new ArgumentNullException("mqName", "mqName is null");
            }
            try
            {
                MessageQueue meQu = new MessageQueue(@".\private$\" + mqName);
                myQueue.Formatter = new XmlMessageFormatter(new Type[] { typeof(clsSt) });
                Message mes = meQu.Receive();
                clsStRead = (clsSt)mes.Body;

            }
            catch(Exception Ex)
            {
                throw Ex;
            }

            return clsStRead;
        }

原文地址:https://www.cnblogs.com/whtydn/p/1518499.html