.NET消息隊列的使用


在項目中使用消息隊列,可以對消息提供方和消息消費方進行解耦,提高系統的靈活性和可拓展性。其中,企業級的消息隊列中間件有IBM WebSphere MQ、Tibco EMS、HornetQ等等。微軟的Windows系統也自帶了消息隊列的功能,可以在“啟動或關閉Windows功能”中開啟

開啟后在服務中查看消息隊列服務是否運行:

接下來是簡單的消息隊列操作:

using System;
using System.Messaging;

namespace MQ
{
    class MQHelper
    {
        /// <summary>
        /// 創建一個消息隊列
        /// </summary>
        /// <param name="name">消息隊列的名稱</param>
        /// <returns>是否創建成功</returns>
        public static bool CreateNewMQ(string name)
        {
            if (!MessageQueue.Exists(".\\private$\\" + name))
            {

                MessageQueue mq = MessageQueue.Create(".\\private$\\" + name);
                mq.Label = "private$\\" + name;
                return true;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 刪除一個消息隊列
        /// </summary>
        /// <param name="name">消息隊列的名稱</param>
        /// <returns>是否創建成功</returns>
        public static bool DeleteNewMQ(string name)
        {
            if (!MessageQueue.Exists(".\\private$\\" + name))
            {
                MessageQueue.Delete(".\\private$\\" + name);
                return true;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 發送消息到指定消息隊列
        /// </summary>
        /// <param name="mq_name">消息隊列名稱</param>
        /// <param name="msg_lable">消息頭</param>
        /// <param name="msg_body">消息體</param>
        public static void SendMessage(string mq_name, string msg_lable, string msg_body)
        {
            MessageQueue mq = new MessageQueue(@".\private$\" + mq_name);
            Message message = new Message();
            message.Label = msg_lable;
            message.Body = msg_body;
            mq.Send(message);
        }
        /// <summary>
        /// 從指定消息隊列獲取第一條消息
        /// </summary>
        /// <param name="mq_name">消息隊列名稱</param>
        /// <returns>Message</returns>
        public static Message ReceiveMessage(string mq_name)
        {
            MessageQueue mq = new MessageQueue(@".\private$\" + mq_name);
            if (mq.GetAllMessages().Length > 0)
            {
                Message message = mq.Receive();
                if (message != null)
                {
                    message.Formatter = new System.Messaging.XmlMessageFormatter(new Type[] { typeof(string) });
                }
                return message;
            }
            else
            {
                return null;
            }
        }
    }
}

在WPF中調用寫好的方法:

using System;
using System.Timers;
using System.Windows;

namespace MQ
{
    public partial class MainWindow : Window
    {
        private static readonly string mq_name = "textMQ";
        private Timer timer;

        public MainWindow()
        {
            InitializeComponent();
            MQHelper.CreateNewMQ(mq_name);
            timer = new Timer();
            timer.Interval = 1000;
            timer.Elapsed += new System.Timers.ElapsedEventHandler(flash);
            timer.Start();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            string mq_content = inputText.Text;
            //發送一條消息到消息隊列
            MQHelper.SendMessage(mq_name, "test", mq_content);
        }

        //循環獲取消息隊列中的消息,並展現到TextBox中
        private void flash(object sender, ElapsedEventArgs e)
        {
            var message = MQHelper.ReceiveMessage(mq_name);
            if (message != null)
            {
                Action hide = delegate()
                {
                    outputText.Text += message.Id + " " + message.Label + " " + message.Body + "\n";
                };
                this.Dispatcher.BeginInvoke(hide);
            }
        }
    }
}

運行結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM