如何限制WCF MSMQ端点



我是WCF的新手,刚刚学习如何使用MSMQ让客户端与主机(在控制台应用程序中)通信。

我希望能够从客户端发送消息到主机,并让主机立即接收它们,或者,如果主机停止,在重新启动时继续它离开的地方。

我已经得到了这几乎工作,但我发现,当我重新启动主机时,队列中有10个消息,消息没有按队列顺序处理。我假设有一些多线程正在进行,使它们出现无序。我希望能够限制WCF服务一次处理一条消息,以阻止这种情况发生(除非有更好的解决方案)。

对于我将要研究的系统来说,按顺序处理MSMQ消息而不是并行处理是至关重要的。

我的服务契约代码是:

[ServiceContract(Namespace = "http://www.heronfoods.com/DemoService")]
public interface IDemoService
{
    [OperationContract(IsOneWay = true)]
    void SendMessage(string message);
}

对于服务契约实现,我有这个。(控制台输出是因为这是一个供我学习的演示应用程序):

public class DemoService : IDemoService
{
    public void SendMessage(string message)
    {
        Console.WriteLine("{0} : {1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), message);
    }
}

主机应用程序是一个控制台应用程序,代码如下:

class Program
{
    static void Main(string[] args)
    {
        Console.Title = "WCF Host";
        using (var host = new ServiceHost(typeof(Library.DemoService)))
        {
            var endpoint = new ServiceEndpoint(
                ContractDescription.GetContract(typeof(Library.IDemoService)),
                new NetMsmqBinding(NetMsmqSecurityMode.None),
                new EndpointAddress("net.msmq://localhost/private/test"));
            host.AddServiceEndpoint(endpoint);
            host.Open();
            Console.WriteLine("Host Active");
            Console.ReadLine();
        }
    }
}

客户端同样简单:

class Program
{
    static void Main(string[] args)
    {
        Console.Title = "WCF Client";
        IDemoService proxy = ChannelFactory<IDemoService>.CreateChannel(
            new NetMsmqBinding(NetMsmqSecurityMode.None),
            new EndpointAddress("net.msmq://localhost/private/test")
            );
        do
        {
            string msg = Console.ReadLine();
            if (msg=="")
                break;
            else
                proxy.SendMessage(msg);
        } while (true);
    }
}

我假设您的队列不是事务性的。

虽然我不确定是否有办法将netMsmqBinding限制为单个线程,但您不应该应用此限制。

为了保证有序交付,您只需要使队列事务性,然后将exactlyOnce属性应用于netMsmqBinding配置。

最新更新