MSMQ在.net即服务中

时间:2009-08-12 01:00:34

标签: .net-2.0 msmq

我们有一个Java WebService,它使用MSMQ发送消息(带有一组记录的XML文件)。

我需要使用VB.net在.net中构建一个小应用程序,它应该选择这些消息并读取它们并插入到SQL数据库中。

你们有什么建议吗?我们如何实时阅读MSMQ消息。

任何资源或链接都会有很大的帮助。

3 个答案:

答案 0 :(得分:9)

System.Messaging命名空间中,.NET中提供了完整的MSMQ托管实现。您可以在消息队列上调用BeginReceive,然后异步等待消息到达。完成后,您可以调用EndReceive,处理消息并再次调用BeginReceive以等待下一个消息(或处理队列中的下一个消息)。

答案 1 :(得分:6)

在.NET中处理MSMQ消息的最佳方法是使用WCF。 Justin Wilcox有一个很棒的教程here

但我强烈建议您尝试MSMQ + WCF。它非常好,您将了解更多有关WCF的信息,这是很棒的事情。

更简单的方法是做一些像JustinD建议的事情。 System.Messaging命名空间非常易于使用。我唯一不同的是调用Receive方法而不指定超时。这会导致线程等待,直到队列中出现一条消息,此时将收到该消息。

答案 2 :(得分:5)

这里有一些示例C#.NET代码,可以帮助您开始从队列中读取...

using System.Messaging;
using System.IO;


MessageQueue l_queue = new MessageQueue(this.MessageQueuePath);
        l_queue.Formatter = new XmlMessageFormatter(new Type[] { typeof(System.String) });

        if (!l_queue.CanRead)
        {
            e.Result = MessageQueueError.InsufficientPermissions;
            return;
        }

        while (true)
        {
            // sleep 2 seconds between checks to keep this from overloading CPU like a madman
            System.Threading.Thread.Sleep(2000);

            Message l_msg = null;
            string l_msgID = String.Empty;

            // try and receive the message - a IOTimeout exception just means that there aren't any messages - move on
            try { l_msg = l_queue.Receive(TimeSpan.FromSeconds(5)); }
            catch (MessageQueueException ex)
            {
                if (ex.MessageQueueErrorCode != MessageQueueErrorCode.IOTimeout)
                    // log error
                else
                    continue;
            }
            catch (Exception ex) { // log error 
            }

            if (l_msg == null)
            {
                //log error
                continue;
            }

            // retrieve and log the message ID
            try { l_msgID = l_msg.Id; }
            catch (Exception ex) { // log error
            }

            // do whatever with the message...
        }