永发信息网

c#中怎样创建消息队列

答案:2  悬赏:80  手机版
解决时间 2021-03-11 18:37
  • 提问者网友:焚苦与心
  • 2021-03-11 04:06
c#中怎样创建消息队列
最佳答案
  • 五星知识达人网友:一袍清酒付
  • 2021-03-11 04:59
1..Net使用消息队列,借助windows组件来存储要完成的一系列任务,不用程序使用同一个队列,方便不同程序之间的数据共享和协作……
2.这个在某个方面类似于session(当然还有很多方面不同),相同之处:session可以把信息存储在aspnet_state服务中,网站重新编译或者重新启动网站,session不会丢失(session超时是正常情况,这种情况除外)。
3.win7中安装消息队列组件,详情请百度搜索相关资料。
4.先创建队列,再使用队列,队列中的消息,发送一个多一个,接收一个少一个,先进先出。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Messaging;
//添加物理文件 System.Messaging 的引用
namespace testweb
{
    public partial class MSMQtest : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //CreateNewQueue("MsgQueue");//创建一个消息队列
            //sendSimpleMsg();//每一个队列最好只发送和接收同一种格式的信息,不然不好转换格式。
            //receiveSimpleMsg();//
            //receiveSimpleMsg();
            //sendComplexMsg();
            //receiveComplexMsg();
            MsgModel m = receiveComplexMsg<MsgModel>();
            Response.Write(m.ToString());

        }
        private void sendSimpleMsg()
        {
            //实例化MessageQueue,并指向现有的一个名称为VideoQueue队列
            MessageQueue MQ = new MessageQueue(@".\private$\MsgQueue");
            //MQ.Send("消息测试", "测试消息");
            System.Messaging.Message message = new System.Messaging.Message();
            message.Label = "消息lable";
            message.Body = "消息body";
            MQ.Send(message);
            Response.Write("成功发送消息," + DateTime.Now + "<br/>");
        }
        private void receiveSimpleMsg()
        {
            MessageQueue MQ = new MessageQueue(@".\private$\MsgQueue");
            //调用MessageQueue的Receive方法接收消息
            if (MQ.GetAllMessages().Length > 0)
            {
                System.Messaging.Message message = MQ.Receive(TimeSpan.FromSeconds(5));
                if (message != null)
                {
                    //message.Formatter = new System.Messaging.XmlMessageFormatter(new string[] { "Message.Bussiness.VideoPath,Message" });//消息类型转换
                    message.Formatter = new System.Messaging.XmlMessageFormatter(new Type[] { typeof(string) });
                    Response.Write(string.Format("接收消息成功,lable:{0},body:{1},{2}<br/>", message.Label, message.Body.ToString(), DateTime.Now));
                }
            }
            else
            {
                Response.Write("没有消息了!<br/>");
            }
        }
        private void sendComplexMsg()
        {
            //实例化MessageQueue,并指向现有的一个名称为VideoQueue队列
            MessageQueue MQ = new MessageQueue(@".\private$\MsgQueue");
            //MQ.Send("消息测试", "测试消息");
            System.Messaging.Message message = new System.Messaging.Message();
            message.Label = "复杂消息lable";
            message.Body = new MsgModel("1", "消息1");
            MQ.Send(message);
            Response.Write("成功发送消息,"+DateTime.Now+"<br/>");
        }
        private void receiveComplexMsg()
        {
            MessageQueue MQ = new MessageQueue(@".\private$\MsgQueue");
            //调用MessageQueue的Receive方法接收消息
            if (MQ.GetAllMessages().Length > 0)
            {
                System.Messaging.Message message = MQ.Receive(TimeSpan.FromSeconds(5));
                if (message != null)
                {
                    message.Formatter = new System.Messaging.XmlMessageFormatter(new Type[] { typeof(MsgModel) });//消息类型转换
                    MsgModel msg = (MsgModel)message.Body;
                    Response.Write(string.Format("接收消息成功,lable:{0},body:{1},{2}<br/>", message.Label, msg, DateTime.Now));
                }
            }
            else
            {
                Response.Write("没有消息了!<br/>");
            }
        }
        private T receiveComplexMsg<T>()
        {
            MessageQueue MQ = new MessageQueue(@".\private$\MsgQueue");
            //调用MessageQueue的Receive方法接收消息
            if (MQ.GetAllMessages().Length > 0)
            {
                System.Messaging.Message message = MQ.Receive(TimeSpan.FromSeconds(5));
                if (message != null)
                {
                    message.Formatter = new System.Messaging.XmlMessageFormatter(new Type[] { typeof(T) });//消息类型转换
                    T msg = (T)message.Body;
                    return msg;
                }
            }
            return default(T);
        }
        /// <summary>
        /// 创建消息队列
        /// </summary>
        /// <param name="name">消息队列名称</param>
        /// <returns></returns>
        public void CreateNewQueue(string name)
        {
            if (!System.Messaging.MessageQueue.Exists(".\\private$\\" + name))//检查是否已经存在同名的消息队列
            {

                System.Messaging.MessageQueue mq = System.Messaging.MessageQueue.Create(".\\private$\\" + name);
                mq.Label = "private$\\"+name;
                Response.Write("创建成功!<br/>");
            }
            else
            {
                //System.Messaging.MessageQueue.Delete(".\\private$\\" + name);//删除一个消息队列
                Response.Write("已经存在<br/>");
            }
        }
    }
    [Serializable]
    public class MsgModel
    {
        public string id { get; set; }
        public string Name { get; set; }
        public MsgModel() { }
        public MsgModel(string _id, string _Name)
        {
            id = _id;
            Name = _Name;
        }
        public override string ToString()
        {
            if (string.IsNullOrEmpty(id) || string.IsNullOrEmpty(Name)) return "";
            return string.Format("id--{0},Name--{1}",id,Name);
        }
    }
}
全部回答
  • 1楼网友:洎扰庸人
  • 2021-03-11 05:09
“消息”是在两台计算机间传送的数据单位。消息可以非常简单,例如只包含文本字符串;也可以更复杂,可能包含嵌入对象。 消息被发送到队列中。“消息队列”是在消息的传输过程中保存消息的容器。消息队列管理器在将消息从它的源中继到它的目标时充当中间人。 c#中发往消息队列中发送消息 public bool sendmessage(string title, string body) { messagequeue smsqueue = new messagequeue(); try { string mqpath = system.configuration.configurationsettings.appsettings["siteenvironmentmqpath"];//给基站告警用的(wz的程序) string mqpath = string.format(@"formatname:direct=tcp:{0}", mqpath); smsqueue.messagereadpropertyfilter.body = true; smsqueue.messagereadpropertyfilter.appspecific = true; smsqueue.messagereadpropertyfilter.priority = true; smsqueue.formatter = new system.messaging.xmlmessageformatter(new type[] { typeof(string) }); smsqueue.path = mqpath; message objmsg = new message(); objmsg.label = title; objmsg.body = body; smsqueue.send(objmsg); return true; } catch (exception ex) { return false; } finally { smsqueue.close(); } } c# 从消息队列中取消息 public string receivemessage(string mqpath) { string ret = ""; messagequeue smsqueue = new messagequeue(); try { string mqpath = string.format(@"formatname:direct=tcp:{0}", mqpath); //string mqpath = system.configuration.configurationsettings.appsettings["mqpath"]; smsqueue.messagereadpropertyfilter.body = true; smsqueue.messagereadpropertyfilter.appspecific = true; smsqueue.messagereadpropertyfilter.priority = true; smsqueue.formatter = new system.messaging.xmlmessageformatter(new type[] { typeof(string) }); smsqueue.path = mqpath; message objmsg = smsqueue.receive(); ret = objmsg.body.tostring(); } catch (exception ex) { //logclass.writelog("错误", datetime.now.tostring(), ex.message, "从消息队列读取告警数据"); //system.threading.thread.sleep(convert.toint16(system.configuration.configurationsettings.appsettings["sleeptime"])); } finally { smsqueue.close(); } return ret
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯