• Net 消息队列的简单实现


    微软的消息队列已经在服务器版本的操作系统上好久了。这段时间研究如何面对大数据量的时候提高系统的访问性能,就想到了消息队列。

    原来在实现web聊天的时候我们就曾经使用过消息队列,因为消息队列天生的异步机制,读和写的分离使他适合处理大量消息读取但是不要求即时性很高的系统

    使用消息队列首先要在操作系统的添加组件中添加消息队列,

    在net平台下开发消息队列也比较简单,要专门添加引用system.messageing这个命名空间主要研究MessageQueue这个类

    消息队列分为好几种类型

    我们大部分使用的是私有队列,公共队列可能需要安装到工作组管理的机器应该和AD有关的

    创建私有队列是这样的 System.Messaging.MessageQueue.Create(".\\private$\\name");其中。标示机器名字,private标示是私有队列,name是这个队列的名字

    公共队列是机器名\\队列名,但是一般机器创建的时候会报错

    下面是一个简单的类文件,使用了创建,发送和读取的三个基本功能


    /// <summary>
    ///消息队列的简单实例
    ///2008-10-10
    ///author:张军营
    /// </summary>
    public class Msg
    {
        public static string CreateNewQueue(string name)
        {
            if (!System.Messaging.MessageQueue.Exists(".\\private$\\" + name))//检查是否已经存在同名的消息队列
            {
                System.Messaging.MessageQueue mq = System.Messaging.MessageQueue.Create(".\\private$\\" + name);
                mq.Label = "test";
                return "ok";
            }
            else
            {
                return "已经存在";
            }
        }

        /// <summary>
        /// 同步发送消息
        /// </summary>
        /// <param name="input">发送的内容</param>
        /// <param name="queueName">发送哪个消息队列中</param>
        public static void SendMsg(string input,string queueName)
        {
           // System.Messaging.MessageQueue.Create(".\\private$\\test2");
            System.Messaging.MessageQueue mq = new MessageQueue(".\\private$\\" + queueName);
            System.Messaging.Message message = new System.Messaging.Message();
            message.Body = input;
            message.Formatter = new System.Messaging.XmlMessageFormatter(new Type[] { typeof(string) });
            mq.Send(message);

        }

        /// <summary>
        /// 同步接收消息
        /// </summary>
        /// <param name="queueName">从哪个消息队列接受消息</param>
        /// <returns></returns>
        public static string  ReceiveMsg(string queueName)
        {
            System.Messaging.MessageQueue mq = new MessageQueue(".\\private$\\" + queueName);

            if (mq.GetAllMessages().Length == 0)//判断是否还有消息,如果没有消息的话Receive方法会一直独占进程直到有消息为止,所以必须判断
            {
                return "没有消息了";
            }
            else
            {
                Message m = mq.Receive();
                m.Formatter = new System.Messaging.XmlMessageFormatter(new Type[] { typeof(string) });
                return m.Body.ToString();
            }
        }
    }

    比较简单,代码也很少。更详细的异步读写数据,已经消息队列的更多属性可以查看msnd

    本文使用Blog_Backup未注册版本导出,请到soft.pt42.com注册。

  • 相关阅读:
    模板:高精度求积
    模板:求n累加和
    模板:求A/B高精度值
    模板:堆
    模板:素数筛
    模板:前缀和
    模板:单调队列(Sliding Window)
    模板:最长上升子序列(LIS)
    [转]Asp.net mvc 网站之速度优化 -- 页面缓存
    [转]ASP.NET MVC3 + EF 性能优化解决方案以及最优架构
  • 原文地址:https://www.cnblogs.com/zjypp/p/2319412.html
Copyright © 2020-2023  润新知