[WCF MSMQ] 1. 基本应用

来源:互联网 发布:中国联通wap网络 编辑:程序博客网 时间:2024/06/05 10:55

MSMQ 的好处,微软的相关文档里长篇累牍说了很多,无需我再补充什么。对我而言,比较看重它的离线处理能力,在某些场合这个功能非常有用。加上 MSMQ 3.0 多路广播能力,实在没有理由不吸引我。

由于消息队列异步处理特征,因此在 Queued Contracts 中,我们只能使用 IsOneWay = true 的OperationContract,且不能使用 Fault Contracts 。开发模式上除了将 Binding 换成NetMsmqBinding 外,和以往并没有太大的区别。不过,我强烈建议先看看 SDK 中 MessageQueue 的相关帮助信息。

 
[ServiceContract]
public interface IService
{
  [OperationContract(IsOneWay=true)]
  void Test(DateTime d);
}

[ServiceBehavior]
public class MyService : IService
{
  [OperationBehavior]
  public void Test(DateTime d)
  {
    Console.WriteLine(d);
    Console.WriteLine(DateTime.Now);
  }
}

public class WcfTest
{
  public static void Test()
  {
    if (!MessageQueue.Exists(@"./private$/myqueue"))
    {
      MessageQueue.Create(@"./private$/myqueue", true);
    }

    IService client = ChannelFactory<IService>.CreateChannel(new NetMsmqBinding(NetMsmqSecurityMode.None),
     new EndpointAddress("net.msmq://localhost/private/myqueue"));

    using (client as IDisposable)
    {
      client.Test(DateTime.Now);
    }

    Thread.Sleep(2000);

    AppDomain.CreateDomain("Server").DoCallBack(delegate
    {
      ServiceHost host = new ServiceHost(typeof(MyService), new Uri("net.msmq://localhost/private/myqueue"));
      host.AddServiceEndpoint(typeof(IService), new NetMsmqBinding(NetMsmqSecurityMode.None), "");
      host.Open();
    });
  }
}


输出:
2007-5-3 14:21:23
2007-5-3 14:21:26

在上面的例子中,我们使用 MessageQueue 来创建私有消息队列,由于没有控制器(MSMQ domain controller)进行安全验证,所以我们必须显示关闭其安全设置。另外,我们将客户端调用放在服务启动之前来演示离线操作过程。看看结果,还不错。