MSMQ在.net即服务中

4 msmq .net-2.0

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

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

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

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

Ada*_*son 9

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

  • 如果使用此方法,请在再次调用BeginRecieve之前调用RecieveCompleted事件中的EndRecieve.在我想出这个之前有一些讨厌的行为. (4认同)

Kir*_*rst 6

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

但我强烈建议你尝试MSMQ + WCF.这是非常好的,你会了解更多关于WCF,这是伟大的东西.

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


小智 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...
        }
Run Code Online (Sandbox Code Playgroud)

  • 为什么不删除超时和睡眠?只需拨打"接收"并等待.当消息到达时,您将从队列中接收消息并继续. (9认同)