1. 程式人生 > >.net 訊息佇列MSMQ

.net 訊息佇列MSMQ

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Messaging;
using System.Configuration;  


namespace Test
{
    /// <summary>
    /// 訊息佇列管理器
    /// </summary>
    public class MSMQManager<T>:IDisposable where T : class, new()
    {
        #region 欄位與屬性
        private MessageQueue _msmq = null;
        private string _path;


        private static MSMQManager<T> _instanceLocalComputer = new MSMQManager<T>(true);
        /// <summary>
        /// 本機訊息佇列例項
        /// </summary>
        public static MSMQManager<T> InstanceLocalComputer
        {
            get { return MSMQManager<T>._instanceLocalComputer; }
        }


        private static MSMQManager<T> _instance = new MSMQManager<T>(false);
        /// <summary>
        /// 遠端訊息佇列例項
        /// </summary>
        public static MSMQManager<T> Instance
        {
            get { return MSMQManager<T>._instance; }
        }
        #endregion


        /// <summary>
        /// 建立佇列
        /// </summary>
        /// <param name="transactional">是否啟用事務</param>
        /// <returns></returns>
        public bool Create(bool transactional)
        {
            if (MessageQueue.Exists(@".\private$\MessageQueuen" ))
            {
                return true;
            }
            else
            {
                if (MessageQueue.Create(@".\private$\MessageQueuen", transactional) != null)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }


        /// <summary>
        /// 例項化訊息佇列
        /// </summary>
        /// <param name="isLocalComputer">是否為本機</param>
        public MSMQManager(bool isLocalComputer)
        {
            if (isLocalComputer)
            {
                _path = @".\private$\MessageQueuen";
            }
            else
            {
                _path = @"FormatName:DIRECT=TCP:127.0.1.1\private$\MessageQueuen";
            }


            _msmq = new MessageQueue(_path);
        }




        /// <summary>
        /// 傳送訊息佇列
        /// </summary>
        /// <param name="msmqIndex">訊息佇列實體</param>
        /// <returns></returns>
        public void Send(T msg)
        {
            if (_msmq.Transactional)
            {
                MessageQueueTransaction myTransaction = new MessageQueueTransaction();
                try
                {
                    myTransaction.Begin();
                    _msmq.Send(new Message(msg, new BinaryMessageFormatter()), myTransaction);
                    myTransaction.Commit();
                }
                catch (Exception e)
                {
                    myTransaction.Abort();
                    //異常處理
                }
            }
            else
            {
                try
                {
                    _msmq.Send(new Message(msg, new BinaryMessageFormatter()));
                }
                catch (Exception e)
                {
                    //異常處理
                }
            }
        }


        /// <summary>
        /// 接收訊息佇列,刪除佇列
        /// </summary>
        /// <returns></returns>
        public T Receive()
        {
            T result = null;
            _msmq.Formatter = new BinaryMessageFormatter();
            Message msg = null;
            if (_msmq.Transactional)
            {
                MessageQueueTransaction myTransaction = new MessageQueueTransaction();
                try
                {
                    myTransaction.Begin();
                    msg = _msmq.Receive(new TimeSpan(0, 0, 3), myTransaction);
                    myTransaction.Commit();
                }
                catch (Exception e)
                {
                    myTransaction.Abort();
                    //異常處理
                }
            }
            else
            {
                try
                {
                    msg = _msmq.Receive(new TimeSpan(0, 0, 3));
                }
                catch (Exception ex)
                {
                    //異常處理
                }
            }
            if (msg != null)
            {
                result = msg.Body as T;
            }
            return result;
        }


        /// <summary>
        /// 接收訊息佇列,但不刪除
        /// </summary>
        /// <returns></returns>
        public T Peek()
        {
            T result = null;
            _msmq.Formatter = new BinaryMessageFormatter();
            Message msg = null;
            try
            {
                msg = _msmq.Peek(new TimeSpan(0, 0, 3));
            }
            catch (Exception ex)
            {
                //異常處理
            }
            if (msg != null)
            {
                result = msg.Body as T;
            }
            return result;
        }


        public List<T> GetAllMessage()
        {
            _msmq.Formatter = new BinaryMessageFormatter();


            List<T> msgList = new List<T>();
            T model = null;
            Message[] allMessage = null;
            try
            {
                allMessage = _msmq.GetAllMessages();


                if (allMessage != null)
                {
                    for (int i = 0; i < allMessage.Length; i++)
                    {
                        model = new T();
                        model = allMessage[i].Body as T;
                        msgList.Add(model);


                    }
                }
            }
            catch (Exception e)
            {
                //異常處理
            }
            return msgList;


        }


        /// <summary>
        /// 清空指定佇列的訊息
        /// </summary>


        public void ClearMessage()
        {
            _msmq.Purge();


        }


        #region IDisposable Members
        public void Dispose()
        {
            if (_msmq != null)
            {
                _msmq.Close();
                _msmq.Dispose();
                _msmq = null;
            }
        }




        #endregion
    }
}