Detailed explanation of. Net MSMQ message queue instance

Time:2020-1-15

This article shares the. Net MSMQ message queue instance code for your reference. The specific content is as follows

1. Installation of MSMQ message queuing Windows Environment

Control panel —– programs and functions —– enable or close windows programs —– Microsoft message queue (MSMQ) server

Select the function as shown in the figure and click “confirm” to install. After installation, you can view it in “computer management”

2. Create message queue entity object

/// <summary>
  ///Message entity
  /// </summary>
  [Serializable]
  public class MsmqData
  {
    public int Id { get; set; }
    public string Name { get; set; }
  }

The entity object must be serializable, that is to add [serializable]

3. Create message queue management object

/// <summary>
  ///Message queue management object
  /// </summary>
  public class MSMQManager
  {
    /// <summary>
    ///Message queue address
    /// </summary>
    public string _path;
    /// <summary>
    ///Message queue object
    /// </summary>
    public MessageQueue _msmq;

    /// <summary>
    ///Constructor and initialize the message queuing object
    /// </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>
    ///Send message queue
    /// </summary>
    /// <param name="body"></param>
    public void Send(object body)
    {
      _msmq.Send(new Message(body, new XmlMessageFormatter(new Type[] { typeof(MsmqData) })));
    }

    /// <summary>
    ///Delete after accepting the first message in the queue
    /// </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 ("message content: {0}, {1}", body. ID, body. Name);
        return msg.Body;
      }
      return null;
    }

    /// <summary>
    ///Traverse messages in message queue and delete
    /// </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 ("message content: {0}, {1}", body. ID, body. Name);
        //Query and delete message queue based on message ID
        _msmq.ReceiveById(msg.Id);

      }
    }
  }

In this example, the message is formatted using XML message formatter

4. Main program add call message queue

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) };
        //Send message
        msmqManager.Send(data);
      }
      var msg = msmqManager.ReceiveMessage();
      msmqManager.WriteAllMessage();
      Console.ReadLine();
    }

Add message queue address configuration. In this case, private queue is used


<appSettings>
 <add key="MsmqPath" value=".\private$\myQueue"/>
</appSettings>

5. Run the program to view the results

You can set a breakpoint to view the message queue message body after sending the message

Final run result

6. Syntax of common message queue type path

Queue type
Syntax used in path

Public queue
MachineName\QueueName

Private queue
MachineName\Private$\QueueName

Log queue
MachineName\QueueName\Journal$

The above is the whole content of this article. I hope it will help you in your study, and I hope you can support developepaer more.

Recommended Today

Using non root user to operate docker

This article is reproduced on the Internet: https://blog.csdn.net/lynnyq/ By default, the docker command uses UNIX socket to communicate with the docker engine. Only root and docker group users can access the UNIX socket of docker engine. For security reasons, root is not directly used on Linux systems. Therefore, it is better to add users who […]