C# MQ操作

来源:互联网 发布:与朋友交而不信乎的与 编辑:程序博客网 时间:2024/06/08 11:00
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Messaging;
using System.Xml;


namespace MQService
{
    public static class MsgQueueHelperLocker
    {
        //MQ 发送锁
        public static object MQSendLocker = new object();
        //MQ 接收锁
        public static object MQReceiveLocker = new object();
        //MQ 清楚所有信息锁
        public static object MQClearAllMsgLocker = new object();
        //MQ 获取所有信息锁
        public static object MQGetAllMsgLocker = new object();
        //MQ 线程获取信息锁
        public static object TimerGetVIPMQLocker = new object();
        //MQ 线程获取信息锁
        public static object TimerGetCQVIPMQLocker = new object();
        //MQ 线程获取信息锁
        public static object TimerGetCDAMQLocker = new object();
        //MQ 线程获取信息锁
        public static object TimerGetZGMQLocker = new object();
        //MQ 线程获取信息锁
        public static object AddListViewItemLocker = new object();
    }


    public static class MsgQueueHelper
    {
        /// <summary>
        /// 
        /// </summary>
        public static string QPath { get; set; }


        /// <summary>
        /// 1.通过Create方法创建使用指定路径的新消息队列
        /// </summary>
        /// <param name="queuePath"></param>
        public static Tuple<bool, String> Createqueue(string queuePath)
        {
            try
            {
                if (!MessageQueue.Exists(queuePath))
                {
                    MessageQueue.Create(queuePath);
                }
                else
                {
                    return new Tuple<bool, string>(false, queuePath + "已经存在!");
                    //Console.WriteLine(queuePath + "已经存在!");
                    //MessageQueue.Delete(queuePath);
                    //MessageQueue.Create(queuePath);
                    //Console.WriteLine(queuePath + "删除重建");
                }
                QPath = queuePath;
                return new Tuple<bool, string>(true, "");
            }
            catch (MessageQueueException e)
            {
                //Console.WriteLine(e.Message);
                return new Tuple<bool, string>(false, e.Message);
            }
        }


        /// <summary>
        /// 2.连接消息队列并发送消息到队列
        /// 远程模式:MessageQueue rmQ = new MessageQueue("FormatName:Direct=OS:machinename//private$//queue");
        /// rmQ.Send("sent to regular queue - Atul");对于外网的MSMQ只能发不能收
        /// </summary>
        /// <param name="XMLStr">发送字符串</param>
        /// <param name="StrPath"></param>
        /// <param name="EncodingType"></param>
        /// <param name="LableStr"></param>
        /// <param name="MsgTracType"></param>
        /// <returns></returns>
        public static Tuple<bool, string> SendMessage(string XMLStr, string StrPath = "", string LableStr = "", System.Text.Encoding EncodingType = null, MessageQueueTransactionType MsgTracType = MessageQueueTransactionType.Single)
        {
            try
            {
                if (EncodingType == null)
                {
                    EncodingType = System.Text.Encoding.Unicode;
                }
                //lock (MsgQueueHelperLocker.MQSendLocker)
                //{
                    //连接到本地队列
                    MessageQueue myQueue = new MessageQueue(string.IsNullOrEmpty(StrPath) ? QPath : StrPath);//"FormatName:Direct=TCP:172.20.20.46\\private$\\in"
                    System.Messaging.Message myMessage = new System.Messaging.Message();
                    Byte[] StrBytes = EncodingType.GetBytes(XMLStr);
                    myMessage.BodyStream = new MemoryStream(StrBytes);
                    //MSMQ消息标签设置,格式:YJCHDECDSB2B_S_ECDS_企业十位海关编码_0000000000_业务编号__年月日时分秒毫秒_GUID。
                    //企业十位海关编码:报文B2B_BE_CHECK节点中的TRADE_CODE。
                    //业务编号:报文B2B_BE_CHECK节点中的ERP_NO。
                    if (!string.IsNullOrEmpty(LableStr))
                        myMessage.Label = LableStr;// "YJCHDECDSB2B_S_ECDS_" + objVal.B2B_BE_CHECK.TRADE_CODE + "_0000000000_" + objVal.B2B_BE_CHECK.ERP_NO + "__" + DateTime.Now.ToString("yyyyMMddHHmmss") + "_" + Guid.NewGuid().ToString();
                    //if (myQueue.Transactional)
                    //    MsgTracType = MessageQueueTransactionType.Single;
                    //发生消息到队列中
                    myQueue.Send(myMessage, MsgTracType);
                //}


                return new Tuple<bool, string>(true, "");


            }
            catch (MessageQueueException e)
            {
                return new Tuple<bool, string>(false, e.Message);
                //Console.WriteLine(e.Message);
            }
        }


        /// <summary>
        /// 3.连接消息队列并从队列中接收消息
        /// </summary>
        public static Tuple<bool, string, Message> ReceiveMessage(string StrPath = "",MessageQueueTransaction MQTrac = null, System.Text.Encoding EncodingType = null)
        {
            try
            {
                string context = "";
                Message myMessage = null;
                if (EncodingType == null)
                {
                    EncodingType = System.Text.Encoding.Unicode;
                }
                //lock (MsgQueueHelperLocker.MQReceiveLocker)
                //{
                    MessageQueue myQueue = new MessageQueue(string.IsNullOrEmpty(StrPath) ? QPath : StrPath);
                    if (MQTrac != null)
                    {
                        //从队列中接收消息
                        myMessage = myQueue.Receive(MQTrac);
                        //myMessage = myQueue.Peek();--接收后不消息从队列中移除
                    }
                    else
                    {
                        //从队列中接收消息
                        myMessage = myQueue.Receive();
                        //myMessage = myQueue.Peek();--接收后不消息从队列中移除
                    }


                    Stream st = myMessage.BodyStream;


                    //XmlDocument doc = new XmlDocument();
                    ////doc.Load(st);
                    //XmlReader xr = XmlReader.Create(st);
                    //doc.Load(xr);
                    //context = doc.OuterXml;


                    byte[] BodyBytes = new byte[st.Length];
                    st.Read(BodyBytes, 0, BodyBytes.Length);
                    int SeekNum = skipLength(BodyBytes);
                    if (SeekNum > 0)
                    {
                        BodyBytes = BodyBytes.Skip(SeekNum).ToArray();
                        SeekNum = 0;
                    }


                    //var ss = BodyBytes[0];
                    //if (ss == 255)
                    //{
                    //    BodyBytes = BodyBytes.Skip(1).ToArray();
                    //}
                    //设置当前流的位置为流的开始 
                    st.Seek(SeekNum, SeekOrigin.Begin);


                    //try
                    //{
                    //    XmlDocument doc = new XmlDocument();
                    //    doc.Load(st);
                    //}
                    //catch (Exception ex)
                    //{
                    //    EncodingType = Encoding.BigEndianUnicode;
                    //}


                    context = EncodingType.GetString(BodyBytes);
                //}
                return new Tuple<bool, string, Message>(true, context, myMessage);
            }
            catch (MessageQueueException e)
            {
                return new Tuple<bool, string, Message>(false, e.Message, null);
                //Console.WriteLine(e.Message);
            }
            catch (InvalidCastException e)
            {
                return new Tuple<bool, string, Message>(false, e.Message, null);
                //Console.WriteLine(e.Message);
            }
        }


        /// <summary>
        /// 取消息
        /// </summary>
        /// <param name="StrPath"></param>
        /// <param name="MsgID"></param>
        /// <returns></returns>
        public static Tuple<bool, string,System.Messaging.Message> ReceiveMessageByID(string StrPath,string MsgXML, System.Messaging.Message Msg)
        {
            Tuple<bool, string, System.Messaging.Message> ret = new Tuple<bool, string, System.Messaging.Message>(true, MsgXML, Msg);
            try
            {
                MessageQueue myQueue = new MessageQueue(string.IsNullOrEmpty(StrPath) ? QPath : StrPath);
                myQueue.ReceiveById(Msg.Id);
            }
            catch(Exception ex)
            {
                string ErrMsg = Common.GetExceptionMsg(ex);
                ret = new Tuple<bool, string, System.Messaging.Message>(false, ErrMsg, Msg);
            }


            return ret;
        }


        public static int skipLength(byte[] bom)
        {
            String encoding = "";
            int skipn = 0;
            try
            {
                if ((bom[0] == (byte)0x00) && (bom[1] == (byte)0x00) && (bom[2] == (byte)0xFE) && (bom[3] == (byte)0xFF))
                {
                    encoding = "UTF-32BE";
                    skipn = 4;
                }
                else if ((bom[0] == (byte)0xFF) && (bom[1] == (byte)0xFE) && (bom[2] == (byte)0x00) && (bom[3] == (byte)0x00))
                {
                    encoding = "UTF-32LE";
                    skipn = 4;
                }
                else if ((bom[0] == (byte)0xEF) && (bom[1] == (byte)0xBB) && (bom[2] == (byte)0xBF))
                {
                    encoding = "UTF-8";
                    skipn = 3;
                }
                else if ((bom[0] == (byte)0xFE) && (bom[1] == (byte)0xFF))
                {
                    encoding = "UTF-16BE";
                    skipn = 2;
                }
                else if ((bom[0] == (byte)0xFF) && (bom[1] == (byte)0xFE))
                {
                    encoding = "UTF-16LE";
                    skipn = 2;
                }
                else
                {
                    // Unicode BOM mark not found, unread all bytes
                    skipn = 0;
                }
            }
            catch (Exception ex) 
            {
                skipn = 0; 
            }
            return skipn;
        }


        /// <summary>
        /// 4.清空指定队列的消息
        /// </summary>
        public static Tuple<bool, string> ClearAllMessage(string StrPath = "")
        {
            try
            {
                //lock (MsgQueueHelperLocker.MQClearAllMsgLocker)
                //{
                    MessageQueue myQueue = new MessageQueue(string.IsNullOrEmpty(StrPath) ? QPath : StrPath);
                    myQueue.Purge();
                //}
                //Console.WriteLine("已清空对了{0}上的所有消息", Path);
                return new Tuple<bool, string>(true, "");
            }
            catch (MessageQueueException e)
            {
                //Console.WriteLine(e.Message);
                return new Tuple<bool, string>(false, e.Message);
            }
        }


        /// <summary>
        /// 5.连接队列并获取队列的全部消息
        /// </summary>
        /// <param name="StrPath"></param>
        /// <param name="deQueue">是否取出</param>
        /// <param name="EncodingType"></param>
        /// <returns></returns>
        public static List<Tuple<string, Message>> GetAllMessage(string StrPath = "", bool deQueue = false, System.Text.Encoding EncodingType = null)
        {
            List<Tuple<string, Message>> retMsg = new List<Tuple<string, Message>>();
            try
            {
                bool IsNullEncodingType = false;
                if (EncodingType == null)
                {
                    EncodingType = System.Text.Encoding.Unicode;
                    IsNullEncodingType = true;
                }
                //lock (MsgQueueHelperLocker.MQGetAllMsgLocker)
                //{
                    MessageQueue myQueue = new MessageQueue(string.IsNullOrEmpty(StrPath) ? QPath : StrPath);
                    Message[] allMessage = myQueue.GetAllMessages();//不会从队列中取出
                    for (int i = 0; i < allMessage.Length; i++)
                    {
                        if (deQueue)
                            myQueue.ReceiveById(allMessage[i].Id);//从队列中取出


                        Stream st = allMessage[i].BodyStream;
                        byte[] BodyBytes = new byte[st.Length];
                        st.Read(BodyBytes, 0, BodyBytes.Length);


                        #region 自动获取流的编码方式


                        //var EncType = TextFileEncodingDetector.DetectUnicodeInByteSampleByHeuristics(BodyBytes);


                        //IdentifyEncoding OIdentifyEncoding = new IdentifyEncoding();
                        //if (IsNullEncodingType)
                        //{
                        //    sbyte[] tsbyte = new sbyte[BodyBytes.Length];
                        //    Buffer.BlockCopy(BodyBytes, 0, tsbyte, 0, BodyBytes.Length);
                        //    EncodingType = OIdentifyEncoding.GetEncoding(OIdentifyEncoding.GetEncodingName(tsbyte));
                        //}


                        #endregion


                        int SeekNum = skipLength(BodyBytes);
                        if (SeekNum > 0)
                        {
                            BodyBytes = BodyBytes.Skip(SeekNum).ToArray();
                            SeekNum = 0;
                        }


                        // 设置当前流的位置为流的开始 
                        st.Seek(0, SeekOrigin.Begin);


                        retMsg.Add(new Tuple<string, Message>(EncodingType.GetString(BodyBytes), allMessage[i]));
                    }
                //}
            }
            catch (Exception ex)
            {
                retMsg = new List<Tuple<string, Message>>();
            }
            //Console.ReadLine();
            return retMsg;
        }
    }


}
0 0
原创粉丝点击