在Windows服务中处理MSMQ消息

9
我有一个处理MSMQ消息的Windows服务,它依赖于以下逻辑:
· Windows服务中有一个计时器。每隔10分钟它将执行名为“ProcessMessages”的方法。
· 在此方法内部,它首先通过调用队列的GetAllMessages方法创建现有messageIds列表。
· 对于每个messageId,它使用ReceiveById接收消息并将其存储到文件中。
是否有更好的方法来实现消息处理?
参考:http://www.switchonthecode.com/tutorials/creating-a-simple-windows-service-in-csharp 注意:当我将代码制作成服务时,以下代码未能给出所需的结果;但是事件查看器中没有错误(我没有进行任何显式日志记录)。当它是一个简单的控制台应用程序时,它工作得很好。如何纠正它?[当我将账户更改为“User”时,它现在正在工作,如下面的注释所示]
我的实际要求是在固定时间间隔内处理所有消息-例如只在每天的上午10点和11点处理。最佳方法是什么?
namespace ConsoleSwitchApp
{
    class Program : ServiceBase
    {
        private static Timer scheduleTimer = null;
        static MessageQueue helpRequestQueue = null;
        static System.Messaging.XmlMessageFormatter stringFormatter = null;

        static void Main(string[] args)
        {
            ServiceBase.Run(new Program());
        }

        public Program()
        {
            this.ServiceName = "LijosService6";

            //Queue initialize
            helpRequestQueue = new MessageQueue(@".\Private$\MyPrivateQueue", false);
            stringFormatter = new System.Messaging.XmlMessageFormatter(new string[] { "System.String" });

            //Set Message Filters
            MessagePropertyFilter filter = new MessagePropertyFilter();
            filter.ClearAll();
            filter.Body = true;
            filter.Label = true;
            filter.Priority = true;
            filter.Id = true;
            helpRequestQueue.MessageReadPropertyFilter = filter;

            //Start a timer
            scheduleTimer = new Timer();
            scheduleTimer.Enabled = true;
            scheduleTimer.Interval = 120000;//2 mins
            scheduleTimer.AutoReset = true;
            scheduleTimer.Start();
            scheduleTimer.Elapsed += new ElapsedEventHandler(scheduleTimer_Elapsed);
        }

        protected static void scheduleTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            ProcessMessages();
        }

        private static void ProcessMessages()
        {
            string messageString = "1";

            //Message Processing
            List<string> messageIdList = GetAllMessageId();
            foreach (string messageId in messageIdList)
            {
                System.Messaging.Message messages = helpRequestQueue.ReceiveById(messageId);
                //Store the message into database

                messages.Formatter = stringFormatter;
                string messageBody = System.Convert.ToString(messages.Body);

                if (String.IsNullOrEmpty(messageString))
                {
                    messageString = messageBody;
                }
                else
                {
                    messageString = messageString + "___________" + messageBody;
                }
            }

            //Write File
            string lines = DateTime.Now.ToString();
            lines = lines.Replace("/", "-");
            lines = lines.Replace(":", "_");
            System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test" + lines + ".txt");
            file.WriteLine(messageString);
            file.Close();
        }

        private static List<string> GetAllMessageId()
        {
            List<string> messageIdList = new List<string>();

            DataTable messageTable = new DataTable();
            messageTable.Columns.Add("Label");
            messageTable.Columns.Add("Body");

            //Get All Messages
            System.Messaging.Message[] messages = helpRequestQueue.GetAllMessages();
            for (int index = 0; index < messages.Length; index++)
            {
                string messageId = (System.Convert.ToString(messages[index].Id));
                messageIdList.Add(messageId);

                messages[index].Formatter = stringFormatter;
                messageTable.Rows.Add(new string[] { messages[index].Label, messages[index].Body.ToString() });
            }

            return messageIdList;
        }


        protected override void OnStart(string[] args)
        {
            base.OnStart(args);
        }

        protected override void OnStop()
        {
            base.OnStop();
        }
    }
}

namespace ConsoleSwitchApp
{
    [RunInstaller(true)]
    public class MyWindowsServiceInstaller : Installer
    {
        public MyWindowsServiceInstaller()
        {
            var processInstaller = new ServiceProcessInstaller();
            var serviceInstaller = new ServiceInstaller();

            //set the privileges
            processInstaller.Account = ServiceAccount.LocalSystem;
            serviceInstaller.DisplayName = "LijosService6";
            serviceInstaller.StartType = ServiceStartMode.Manual;

            //must be the same as what was set in Program's constructor

           serviceInstaller.ServiceName = "LijosService6";

            this.Installers.Add(processInstaller);
            this.Installers.Add(serviceInstaller);
        }
    }
}

1
这可能是一个权限问题。尝试使用其他内置账户。 - M.Babcock
@M.Babcock 谢谢。当我使用 ServiceAccount.User 并提供我的用户名和密码时,服务起作用了。这里建议使用哪个账户? - LCJ
1
我强烈建议在生产环境中不要使用专用用户帐户来解决此问题。该问题可能与此KB文章有关(它是关于Vista的,但在7和2008中可能存在相同的问题)。 - M.Babcock
你问题中的链接已经失效了,供你参考。 - RJ Cuthbertson
2个回答

17

一个不错的替代使用定时器的方法是使用MessageQueue.BeginReceive方法,在ReceiveCompleted事件中完成工作。这样,您的代码将等待队列中有消息,然后立即处理该消息,然后检查下一条消息。

以下是链接到MSDN文章的完整示例。

private void Start()
{
    MessageQueue myQueue = new MessageQueue(".\\myQueue");

    myQueue.ReceiveCompleted += 
        new ReceiveCompletedEventHandler(MyReceiveCompleted);

    myQueue.BeginReceive();
}

private static void MyReceiveCompleted(Object source, 
    ReceiveCompletedEventArgs asyncResult)
{
    try
    {
        MessageQueue mq = (MessageQueue)source;
        Message m = mq.EndReceive(asyncResult.AsyncResult);

        // TODO: Process the m message here

        // Restart the asynchronous receive operation.
        mq.BeginReceive();
    }
    catch(MessageQueueException)
    {
        // Handle sources of MessageQueueException.
    }

    return; 
}

6
使用Windows任务计划程序运行控制台应用程序。 - neildt

2

为什么不要订阅 ReceiveCompleted 事件?如果发送方和接收方都是你正在工作的 .Net 项目,那么另一个选择是使用 WCF over MSMQ


我的要求是在固定的时间段内处理所有消息 - 比如每天上午10点和11点。最好的方法是什么? - LCJ
1
也许你应该授予匿名域帐户对 MSMQ 的访问权限。 - paramosh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接