Windows Communication Foundation 到消息队列

WcfToMsmq 示例演示 Windows Communication Foundation (WCF) 应用程序如何将消息发送到消息队列(MSMQ)应用程序。 此服务是自承载控制台应用程序,通过它可以观察服务接收排队消息。 服务和客户端不必同时运行。

服务从队列接收消息并处理订单。 该服务创建事务队列并设置消息接收的消息处理程序,如以下示例代码所示。

static void Main(string[] args)
{
    if (!MessageQueue.Exists(
              ConfigurationManager.AppSettings["queueName"]))
       MessageQueue.Create(
           ConfigurationManager.AppSettings["queueName"], true);
        //Connect to the queue
        MessageQueue Queue = new
    MessageQueue(ConfigurationManager.AppSettings["queueName"]);
    Queue.ReceiveCompleted +=
                 new ReceiveCompletedEventHandler(ProcessOrder);
    Queue.BeginReceive();
    Console.WriteLine("Order Service is running");
    Console.ReadLine();
}

在队列中收到消息时,将调用消息处理程序 ProcessOrder

public static void ProcessOrder(Object source,
    ReceiveCompletedEventArgs asyncResult)
{
    try
    {
        // Connect to the queue.
        MessageQueue Queue = (MessageQueue)source;
        // End the asynchronous receive operation.
        System.Messaging.Message msg =
                     Queue.EndReceive(asyncResult.AsyncResult);
        msg.Formatter = new System.Messaging.XmlMessageFormatter(
                                new Type[] { typeof(PurchaseOrder) });
        PurchaseOrder po = (PurchaseOrder) msg.Body;
        Random statusIndexer = new Random();
        po.Status = PurchaseOrder.OrderStates[statusIndexer.Next(3)];
        Console.WriteLine("Processing {0} ", po);
        Queue.BeginReceive();
    }
    catch (System.Exception ex)
    {
        Console.WriteLine(ex.Message);
    }

}

该服务从 MSMQ 消息正文中提取 ProcessOrder ,并处理顺序。

MSMQ 队列名称是在配置文件的 appSettings 部分中指定的,如以下示例配置所示。

<appSettings>
    <add key="orderQueueName" value=".\private$\Orders" />
</appSettings>

注释

队列名称为本地计算机使用圆点 (.),并在其路径中使用反斜杠分隔符。

客户端创建采购订单并在交易范围内提交采购订单,如以下示例代码所示。

// Create the purchase order
PurchaseOrder po = new PurchaseOrder();
// Fill in the details
...

OrderProcessorClient client = new OrderProcessorClient("OrderResponseEndpoint");

MsmqMessage<PurchaseOrder> ordermsg = new MsmqMessage<PurchaseOrder>(po);
using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required))
{
    client.SubmitPurchaseOrder(ordermsg);
    scope.Complete();
}
Console.WriteLine("Order has been submitted:{0}", po);

//Closing the client gracefully closes the connection and cleans up resources
client.Close();

客户端按顺序使用自定义客户端将 MSMQ 消息发送给队列。 由于接收和处理消息的应用程序是 MSMQ 应用程序,而不是 WCF 应用程序,因此这两个应用程序之间没有隐式服务协定。 因此,在此方案中无法使用 Svcutil.exe 工具创建代理。

对于使用 MsmqIntegration 绑定发送消息的所有 WCF 应用程序,自定义客户端实质上是相同的。 与其他客户不同,它不包括一系列服务操作。 这仅仅是一项提交消息的操作。

[System.ServiceModel.ServiceContractAttribute(Namespace = "http://Microsoft.ServiceModel.Samples")]
public interface IOrderProcessor
{
    [OperationContract(IsOneWay = true, Action = "*")]
    void SubmitPurchaseOrder(MsmqMessage<PurchaseOrder> msg);
}

public partial class OrderProcessorClient : System.ServiceModel.ClientBase<IOrderProcessor>, IOrderProcessor
{
    public OrderProcessorClient(){}

    public OrderProcessorClient(string configurationName)
        : base(configurationName)
    { }

    public OrderProcessorClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress address)
        : base(binding, address)
    { }

    public void SubmitPurchaseOrder(MsmqMessage<PurchaseOrder> msg)
    {
        base.Channel.SubmitPurchaseOrder(msg);
    }
}

运行示例时,客户端和服务活动会显示在服务和客户端控制台窗口中。 可以看到服务从客户端接收消息。 在每个控制台窗口中按 Enter 可以关闭服务和客户端。 请注意:由于正在使用队列,因此不必同时启动和运行客户端和服务。 例如,可以运行客户端,将其关闭,然后启动服务,但仍会收到其消息。

注释

此示例需要安装消息队列。 请参阅 消息队列中的安装说明。

设置、生成和运行示例

  1. 确保已为 Windows Communication Foundation 示例 执行One-Time 安装过程。

  2. 如果先运行服务,则它将检查以确保队列存在。 如果队列不存在,服务将创建一个队列。 可以先运行服务来创建队列,也可以通过 MSMQ 队列管理器创建一个队列。 按照以下步骤在 Windows 2008 中创建队列。

    1. 在 Visual Studio 2012 中打开服务器管理器。

    2. 展开“功能”选项卡

    3. 右键单击 专用消息队列,然后选择“ 新建>专用队列”。

    4. 选中“事务性”框

    5. 输入 ServiceModelSamplesTransacted 作为新队列的名称。

  3. 若要生成解决方案的 C# 或 Visual Basic 版本,请按照 生成 Windows Communication Foundation 示例中的说明进行操作。

  4. 若要在单台计算机配置中运行示例程序,请按照 运行 Windows 通信基础 (Windows Communication Foundation) 示例程序中的说明进行操作。

在多台计算机上运行示例

  1. 将 \service\bin\ 文件夹中的服务程序文件(在语言特定的文件夹下)复制到服务计算机。

  2. 将 \client\bin\ 文件夹中的客户端程序文件(在特定于语言的文件夹下)复制到客户端计算机。

  3. 在 Client.exe.config 文件中,更改客户端终结点地址以指定服务计算机名称而不是“.”。

  4. 在服务计算机上,从命令提示符启动 Service.exe。

  5. 在客户端计算机上,在命令提示符下启动 Client.exe。

另请参阅

  • 如何使用 WCF 终结点和消息队列应用程序交换消息
  • 消息队列