.net msmq消息队列实例详解
程序员文章站
2022-05-26 10:57:40
本文为大家分享了.net msmq消息队列实例代码,供大家参考,具体内容如下
1.msmq消息队列windows环境安装
控制面板----》程序和功能----》启用或关...
本文为大家分享了.net msmq消息队列实例代码,供大家参考,具体内容如下
1.msmq消息队列windows环境安装
控制面板----》程序和功能----》启用或关闭windows程序----》microsoft message queue(msmq)服务器
选中如图所示功能点击“确认”进行安装,安装好后可在 “计算机管理”中进行查看
2.创建消息队列实体对象
/// <summary> /// 消息实体 /// </summary> [serializable] public class msmqdata { public int id { get; set; } public string name { get; set; } }
实体对象必须可序列化,即需添加[serializable]
3.创建消息队列管理对象
/// <summary> /// 消息队列管理对象 /// </summary> public class msmqmanager { /// <summary> /// 消息队列地址 /// </summary> public string _path; /// <summary> /// 消息队列对象 /// </summary> public messagequeue _msmq; /// <summary> /// 构造函数并初始化消息队列对象 /// </summary> /// <param name="path"></param> public msmqmanager(string path = null) { if (string.isnullorempty(path)) { _path = configurationmanager.appsettings["msmqpath"].tostring(); } else { _path = path; } if (messagequeue.exists(_path)) { _msmq = new messagequeue(_path); } else { _msmq = messagequeue.create(_path); } } /// <summary> /// 发送消息队列 /// </summary> /// <param name="body"></param> public void send(object body) { _msmq.send(new message(body, new xmlmessageformatter(new type[] { typeof(msmqdata) }))); } /// <summary> /// 接受队列中第一个消息后删除 /// </summary> /// <returns></returns> public object receivemessage() { var msg = _msmq.receive(); if (msg != null) { //msg.formatter = new binarymessageformatter(); msg.formatter = new xmlmessageformatter(new type[] { typeof(msmqdata) }); var body = (msmqdata)msg.body; console.writeline("消息内容:{0},{1}", body.id, body.name); return msg.body; } return null; } /// <summary> /// 遍历消息队列中的消息并删除 /// </summary> public void writeallmessage() { var enumerator = _msmq.getmessageenumerator2(); while (enumerator.movenext()) { message msg = (message)(enumerator.current); //msg.formatter = new binarymessageformatter(); msg.formatter = new xmlmessageformatter(new type[] { typeof(msmqdata) }); var body = (msmqdata)msg.body; console.writeline("消息内容:{0},{1}", body.id, body.name); //根据消息id查询并删除消息队列 _msmq.receivebyid(msg.id); } } }
此例中使用xml格式(xmlmessageformtter)对消息进行格式化
4.主程序添加调用消息队列
static void main(string[] args) { var msmqmanager = new msmqmanager(); for (int i = 1; i <= 10; i++) { msmqdata data = new msmqdata() { id = i, name = string.format("name{0}", i) }; //发送消息 msmqmanager.send(data); } var msg = msmqmanager.receivemessage(); msmqmanager.writeallmessage(); console.readline(); }
添加消息队列地址配置,本例使用私有队列
<appsettings> <add key="msmqpath" value=".\private$\myqueue"/> </appsettings>
5.运行程序查看结果
可以在发送完消息后打上断点查看消息队列消息正文
最后运行结果
6.常见消息队列类型路径的语法
队列类型
路径中使用的语法
公共队列
machinename\queuename
专用队列
machinename\private$\queuename
日志队列
machinename\queuename\journal$
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
上一篇: three.js实现圆柱体
下一篇: jQuery实现拖动效果的实例代码