MSMQメッセージキュー、MSMQメッセージの傍受、メッセージスキャン

29396 ワード

 
  
 
  
namespace FSMP.PTS.MSMQ
{
   public class MSMQHelper
    {
        /// 
        /// MSMQ      
        /// 
        public static string MsmqString
        {
            get
            {
                string Name = "fsmpptsmsmq";
                return string.Format(@".\Private$\{0}", Name);
            }
        }
 
        /// 
        ///     
        /// 
        /// "head">   
        /// "json">json  
        /// "Priority">  
     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;
        /// 
        ///         
        /// 
        private int IntervalTime = AppConfig.IntervalTime * 60000;
        /// 
        /// N           
        /// 
        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("             !");
        }
 
        /// 
        ///       
        /// 
        /// "e">
        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()));
            }
        }
 
        /// 
        ///   
        /// 
        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("          !");
            }
        }
    }
}