1. 程式人生 > >MSMQ 訊息佇列、監聽MSMQ訊息、訊息掃描

MSMQ 訊息佇列、監聽MSMQ訊息、訊息掃描


 

 
namespace FSMP.PTS.MSMQ
{
   public class MSMQHelper
    {
        /// <summary>
        /// MSMQ服務地址配置
        /// </summary>
        public static string MsmqString         {             get             {                 string
 Name = "fsmpptsmsmq";                 return string.Format(@".\Private$\{0}", Name);             }         }         ///
 <summary>         /// 傳送訊息         /// </summary>         /// <param name="head">標識碼</param>         /// <param name="json">json資料</param>         /// <param name="Priority">級別</param>      public static bool SendMessage(int head, string json, System.Messaging.MessagePriority Priority)         {             bool IsTrue = false;             try             {                 System.Messaging.MessageQueue mq = null;
		//佇列訊息名稱是否存在
                if (System.Messaging.MessageQueue.Exists(MsmqString))
                {
                    mq = new System.Messaging.MessageQueue(MsmqString);
                    System.Messaging.Message message = new System.Messaging.Message();
                    //為了避免存放訊息佇列的計算機重新啟動而丟失訊息,可以通過設定訊息物件的Recoverable屬性為true,
                    //在訊息傳遞過程中將訊息儲存到磁碟上來保證訊息的傳遞,預設為false。 
                    message.Recoverable = true;
                    message.Priority = Priority;
                    message.Label = head.ToString();
                    message.Body = json;
                    message.Formatter = new System.Messaging.XmlMessageFormatter(new Type[] { typeof(string) });
                    mq.Send(message);
                    IsTrue = true;
                }
                else
                {
		    //此處如果不存在佇列,可以建立佇列:mq = MessageQueue.Create(MsmqString);
                    Common.WriteToLogFile(String.Format("{0}佇列名稱不存在!", MsmqString));
                }
            }
            catch (Exception ex)
            {
                Common.WriteToLogFile(string.Format("傳送MQ異常錯誤:{0}", ex.ToString()));
            }
            return IsTrue;
        }
    }
}

 

 
namespace FSMP.PTS.Service
{
    public partial class WindowsService : ServiceBase
    {
        public WindowsService()
        {
            InitializeComponent();
        }
 
        System.Timers.Timer timer1;  //計時器
 
        private bool IsStatus = true;
	
        private Thread PuschThread;
        /// <summary>
        /// 定時監控掃描時間
        /// </summary>
        private int IntervalTime = AppConfig.IntervalTime * 60000;
        /// <summary>
        /// N分鐘無狀態回覆則轉簡訊
        /// </summary>
        private int PushSmsMinute = AppConfig.PushSmsMinute;
 
        protected override void OnStart(string[] args)
        {
            timer1 = new System.Timers.Timer();
            timer1.Interval = IntervalTime;  //設定計時器事件間隔執行時間預設15分鐘執行一次
            timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_Elapsed);
            timer1.Enabled = true;
 
            //監聽
            IsStatus = true;
            PuschThread = new Thread(new ThreadStart(RecevieMessage));
            PuschThread.IsBackground = true;
            PuschThread.Start();
            Common.WriteToLogFile("家校寶訊息監控服務開始執行!");
        }
 
        protected override void OnStop()
        {
            this.timer1.Enabled = false;
            IsStatus = false;
            Common.WriteToLogFile("家校寶訊息監控服務停止執行!");
        }
 
        /// <summary>
        /// 定時掃描訊息
        /// </summary>
        /// <param name="e"></param>
        private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                var list = PushToMessage.get_pushtosms(AppConfig.PushSmsMinute);
                int MessageCount = list.Count;
                Common.WriteToLogFile(string.Format("共有{0}條已超出{1}分鐘未閱讀訊息資料", MessageCount, PushSmsMinute));
                if (MessageCount > decimal.Zero)
                {
                    this.timer1.Enabled = false;
                    foreach (var item in list)
                    {
                        var model = new PushToSmsModels.Req_getmobileModel
                        {
                            id = item.userid,
                            key = Common.CreateKey(item.userid)
                        };
                        var json = JsonConvert.SerializeObject(model);
                        var mobile = PushToMessage.get_usermobile(json);
                        var status = decimal.One;
                        //時間超出轉為簡訊傳送
                        if (!string.IsNullOrEmpty(mobile) && mobile.Length == 11)
                        {
                            var Custom = new Random(DateTime.Now.Millisecond).Next(10, 98).ToString();
                            var content = item.messagetype == 0 ? string.Format("{0} ({1})", item.content, "請登平臺檢視") : item.content;
                            var entity = new PushToSmsModels.smssendModel
                            {
                                ID = Common.GetRandomID().ToString(),
                                SchoolCode = item.schoolcode,
                                Mobile = mobile,
                                Content = content,
                                InputDate = DateTime.Now,
                                Status = -1,
                                Description = string.Empty,
                                TaskId = string.Empty,
                                TaskStatus = decimal.MinusOne,
                                TaskType = 0,
                                Custom = Custom,
                                LevelNo = 0,
                                VerifyStatus = 1
                            };
                            var s = PushToMessage.set_smssend(entity);
                            status = s ? decimal.Zero : decimal.One;
                        }
                        else
                        {
                            status = 9;
                            Common.WriteToLogFile(String.Format("手機長度錯誤,手機號碼:{0})", mobile));
                        }
                        var result = PushToMessage.update_pushtosms(item.schoolcode, item.userid, item.messageid, status);
                        Common.WriteToLogFile(String.Format("提交訊息狀態(schoolcode:{0},userid{1},messageid:{2},status:{3},DB:{4})", item.schoolcode, item.userid, item.messageid, status, result));
                    }
                    //重新開啟定時器使用
                    this.timer1.Enabled = true;
                    timer1.Interval = 1000;//1秒鐘執行一次
                }
                else
                {
                    timer1.Interval = IntervalTime; //每隔{IntervalTiem}毫秒 執行一次
                }
            }
            catch (Exception ex)
            {
                Common.WriteToLogFile(String.Format("訊息監控掃描資料異常:{1}", ex.ToString()));
            }
        }
 
        /// <summary>
        /// 監聽
        /// </summary>
        public void RecevieMessage()
        {
            try
            {
                while (IsStatus)
                {
                    if (MessageQueue.Exists(MSMQ.MSMQHelper.MsmqString))
                    {
                        MessageQueue mq = new MessageQueue(MSMQ.MSMQHelper.MsmqString);
                        System.Messaging.Message message = mq.Receive();
                        message.Formatter = new System.Messaging.XmlMessageFormatter(new Type[] { typeof(string) });
                        if (message != null)
                        {
                            //訊息型別 對應 FSMP.MSMQ.SendMessage.MessageType值
                            var Lable = message.Label.ToString();
                            string Body = message.Body.ToString();
                            Common.WriteToLogFile(string.Format("Lable:{0},Body:{1}", Lable, Body));
                            int success = 0;
                            int fail = 0;
                            if (Lable == ((int)MSMQ.MessageType.Message).ToString())
                            {
                                var messagelist = MSMQ.MessageDeserialize.MessageList(Body);
                                success = 0;
                                fail = 0;
                                foreach (var item in messagelist)
                                {
                                    var s = PushToMessage.set_pushtosms(item.SchoolCode, item.UserId, item.MessageId, (int)MessageType.Message, item.Content, decimal.MinusOne);
                                    if (s)
                                    {
                                        success++;
                                    }
                                    else
                                    {
                                        fail++;
                                    }
                                }
                                Common.WriteToLogFile(string.Format("訊息執行完畢,成功:{0},失敗:{1}", success, fail));
                            }
                            else if (Lable == ((int)MSMQ.MessageType.MessageRead).ToString())
                            {
                                var messageread = MSMQ.MessageDeserialize.MessageStatus(Body);
                                if (messageread != null)
                                {
                                    var s = PushToMessage.update_pushtosms(messageread.SchoolCode, messageread.UserId, messageread.MessageId, decimal.One);
                                    Common.WriteToLogFile(string.Format("訊息執行完畢,執行結果:{0}", s));
                                }
                            }
                            else if (Lable == ((int)MSMQ.MessageType.WorkBook).ToString())
                            {
                                var workbookllist = MSMQ.MessageDeserialize.WorkBoolList(Body);
                                success = 0;
                                fail = 0;
                                foreach (var item in workbookllist)
                                {
                                    var s = PushToMessage.set_pushtosms(item.SchoolCode, item.UserId, item.WorkBookId, (int)MessageType.WorkBook, item.Content, decimal.MinusOne);
                                    if (s)
                                    {
                                        success++;
                                    }
                                    else
                                    {
                                        fail++;
                                    }
                                }
                                Common.WriteToLogFile(string.Format("訊息執行完畢,成功:{0},失敗:{1}", success, fail));
 
                            }
                            else if (Lable == ((int)MSMQ.MessageType.WorkBookRead).ToString())
                            {
                                var wookbookread = MSMQ.MessageDeserialize.WorkBookStatus(Body);
                                success = 0;
                                fail = 0;
                                if (wookbookread != null)
                                {
                                    var s = PushToMessage.update_pushtosms(wookbookread.SchoolCode, wookbookread.UserId, wookbookread.WorkBookId, decimal.One);
                                    Common.WriteToLogFile(string.Format("訊息執行完畢,執行結果:{0}", s));
                                }
                            }
                            else
                            {
                                Common.WriteToLogFile(String.Format("未處理的MQ記錄(Lable:{0},Body:{1})", Lable, Body));
                            }
                        }
                        System.Threading.Thread.Sleep(100);
                    }
                    else
                    {
                        Common.WriteToLogFile(String.Format("{0}不存在", MSMQ.MSMQHelper.MsmqString));
                    }
                }
            }
            catch (Exception ex)
            {
                Common.WriteToLogFile(String.Format("接收MQ訊息異常錯誤:{0}", ex.ToString()));
            }
        }
 
    }
}

 

 
namespace FSMP.PTS.MSMQ
{
    public class SendMessage
    {

 

 
        static void Message(string Body)
        {
            var JsonModel = JsonConvert.DeserializeObject<MSMQModels.JxbMessageModel>(Body);
            if (JsonModel != null)
            {
                var model = new MSMQModels.MessageModel
                {
                    Content = JsonModel.title,
                    MessageId = JsonModel.id,
                    SchoolCode = JsonModel.schoolcode,
                    UserId = JsonModel.userstring
                };
                var JsonString = JsonConvert.SerializeObject(model);
                MSMQHelper.SendMessage((int)MessageType.Message, JsonString, System.Messaging.MessagePriority.High);
            }
            else
            {
                Common.WriteToLogFile("通知公告訊息解析失敗!");
            }
        }
	
 	
        static void WorkBook(string Body)
        {
            var JsonModel = JsonConvert.DeserializeObject<MSMQModels.JxbMessageModel>(Body);
            if (JsonModel != null)
            {
                var model = new MSMQModels.WorkBookModel
                {
                    Content = JsonModel.title,
                    UserId = JsonModel.userstring,
                    SchoolCode = JsonModel.schoolcode,
                    WorkBookId = JsonModel.id,
                };
                var JsonString = JsonConvert.SerializeObject(model);
                MSMQHelper.SendMessage((int)MessageType.WorkBook, JsonString, System.Messaging.MessagePriority.High);
            }
            else
            {
                Common.WriteToLogFile("作業練習訊息解析失敗!");
            }
        }

    }
}