本文为大家分享了.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.常见消息队列类型路径的语法

队列类型
路径中使用的语法

公共队列
MachineNameQueueName

专用队列
MachineNamePrivate$QueueName

日志队列
MachineNameQueueNameJournal$

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持悠悠之家。

点赞(74)

评论列表共有 0 条评论

立即
投稿
返回
顶部