Partager via


Comment : échanger des messages avec des points de terminaison WCF et des applications Message Queuing

Vous pouvez intégrer des applications Message Queuing (MSMQ) existantes aux applications Windows Communication Foundation (WCF) en utilisant la liaison d'intégration MSMQ qui convertit les messages MSMQ en messages WCF et vice versa. Cela vous permet d'appeler des applications réceptrices MSMQ depuis des clients WCF ainsi que d'appeler les services WCF depuis des applications expéditrices MSMQ.

De cette section, nous vous expliquons comment utiliser MsmqIntegrationBinding pour les communications mises en file d'attente entre (1) un client WCF et un service d'application MSMQ écrit à l'aide de System.Messaging et (2) un client d'application MSMQ et un service WCF.

Pour un exemple complet montrant comment appeler une application de récepteur MSMQ à partir d'un client WCF, consultez l'exemple Windows Communication Foundation to Message Queuing.

Pour un exemple complet montrant comment appeler un service WCF à partir d'un client MSMQ, consultez l'exemple Message Queuing to Windows Communication Foundation.

Pour créer un service WCF qui reçoit des messages depuis un client MSMQ

  1. Configurez une interface qui définit le contrat de service pour le service WCF qui reçoit les messages mis en file d'attente depuis une application expéditrice MSMQ, comme le montre l'exemple de code suivant.

    <ServiceContract(Namespace:="http:'Microsoft.ServiceModel.Samples")> _
    <ServiceKnownType(GetType(PurchaseOrder))> _
    Public Interface IOrderProcessor
        <OperationContract(IsOneWay:=True, Action:="*")> _
        Sub SubmitPurchaseOrder(ByVal msg As MsmqMessage(Of PurchaseOrder))
    End Interface
    
    [ServiceContract(Namespace = "http://Microsoft.ServiceModel.Samples")]
    [ServiceKnownType(typeof(PurchaseOrder))]
    public interface IOrderProcessor
    {
        [OperationContract(IsOneWay = true, Action = "*")]
        void SubmitPurchaseOrder(MsmqMessage<PurchaseOrder> msg);
    }
    
  2. Implémentez l'interface et appliquez l'attribut ServiceBehaviorAttribute à la classe, comme le montre l'exemple de code suivant.

    Public Class OrderProcessorService
        Implements IOrderProcessor
    
        <OperationBehavior(TransactionScopeRequired:=True, TransactionAutoComplete:=True)> _
        Public Sub SubmitPurchaseOrder(ByVal ordermsg As MsmqMessage(Of PurchaseOrder)) Implements IOrderProcessor.SubmitPurchaseOrder
            Dim po As PurchaseOrder = ordermsg.Body
            Dim statusIndexer As New Random()
            po.Status = statusIndexer.Next(3)
            Console.WriteLine("Processing {0} ", po)
        End Sub
    End Class
    
    public class OrderProcessorService : IOrderProcessor
    {
        [OperationBehavior(TransactionScopeRequired = true, TransactionAutoComplete = true)]
        public void SubmitPurchaseOrder(MsmqMessage<PurchaseOrder> ordermsg)
        {
            PurchaseOrder po = (PurchaseOrder)ordermsg.Body;
            Random statusIndexer = new Random();
            po.Status = (OrderStates)statusIndexer.Next(3);
            Console.WriteLine("Processing {0} ", po);
        }
    
        // Host the service within this EXE console application.
    public static void Main()
    {
        // Get base address from appsettings in configuration.
        Uri baseAddress = new Uri(ConfigurationManager.AppSettings["baseAddress"]);
    
        // Create a ServiceHost for the CalculatorService type and provide the base address.
        using (ServiceHost serviceHost = new ServiceHost(typeof(IOrderProcessor), baseAddress))
        {
        // Open the ServiceHostBase to create listeners and start listening for messages.
            serviceHost.Open();
    
        // The service can now be accessed.
            Console.WriteLine("The service is ready.");
            Console.WriteLine("The service is running in the following account: {0}", WindowsIdentity.GetCurrent().Name);
            Console.WriteLine("Press <ENTER> to terminate service.");
            Console.WriteLine();
            Console.ReadLine();
    
        // Close the ServiceHostBase to shutdown the service.
            serviceHost.Close();
        }
    }
    
    }
    
  3. Créez un fichier de configuration qui spécifie la liaison MsmqIntegrationBinding.

    <configuration>
      <appSettings>
        <!-- use appSetting to configure MSMQ queue name -->
        <add key="orderQueueName" value=".\private$\Orders" />
        <add key="baseAddress" value="https://localhost:8000/ServiceModelSamples/Service" />
      </appSettings>
      <system.serviceModel>
        <services>
          <service 
            name="Microsoft.ServiceModel.Samples.OrderProcessorService" >
            <endpoint address="msmq.formatname:DIRECT=OS:.\private$\Orders"
                                    binding="msmqIntegrationBinding"
                      bindingConfiguration="OrderProcessorBinding" 
                      contract="Microsoft.ServiceModel.Samples.IOrderProcessor">
            </endpoint>
          </service>
        </services>
    
        <bindings>
          <msmqIntegrationBinding>
            <binding name="OrderProcessorBinding" >
              <security mode="None" />
            </binding>
          </msmqIntegrationBinding>
        </bindings>
    
      </system.serviceModel >
    
    </configuration>
    
  4. Instanciez un objet ServiceHost qui utilise la liaison configurée.

Pour créer un client WCF qui envoie des messages à une application réceptrice MSMQ

  1. Configurez une interface qui définit le contrat de service pour le client WCF qui envoie les messages mis en file d'attente au récepteur MSMQ, comme le montre l'exemple de code suivant.

    <System.ServiceModel.ServiceContractAttribute(Namespace:="http:'Microsoft.ServiceModel.Samples")> _
    Public Interface IOrderProcessor
        <OperationContract(IsOneWay:=True, Action:="*")> _
        Sub SubmitPurchaseOrder(ByVal msg As MsmqMessage(Of PurchaseOrder))
    end interface
    
    Public Interface IOrderProcessorChannel
        Inherits IOrderProcessor, System.ServiceModel.IClientChannel
    End Interface
    
    [System.ServiceModel.ServiceContractAttribute(Namespace = "http://Microsoft.ServiceModel.Samples")]
    public interface IOrderProcessor
    {
        [OperationContract(IsOneWay = true, Action = "*")]
        void SubmitPurchaseOrder(MsmqMessage<PurchaseOrder> msg);
    }
    
    public interface IOrderProcessorChannel : IOrderProcessor, System.ServiceModel.IClientChannel
    {
    }
    
  2. Définissez une classe de client que le client WCF utilise pour appeler le récepteur MSMQ.

    Dim binding As New MsmqIntegrationBinding()
    Dim address As New EndpointAddress("msmq.formatname:DIRECT=OS:.\\private$\\Orders")
    Dim channelFactory As New ChannelFactory(Of IOrderProcessor)(binding, address)
    Dim channel As IOrderProcessor = channelFactory.CreateChannel()
    
    Dim po As New PurchaseOrder()
    po.customerId = "somecustomer.com"
    po.poNumber = Guid.NewGuid().ToString()
    
    Dim lineItem1 As New PurchaseOrderLineItem()
    lineItem1.productId = "Blue Widget"
    lineItem1.quantity = 54
    lineItem1.unitCost = 29.99F
    
    Dim lineItem2 = New PurchaseOrderLineItem()
    lineItem2.productId = "Red Widget"
    lineItem2.quantity = 890
    lineItem2.unitCost = 45.89F
    
    Dim lineItems(2) As PurchaseOrderLineItem
    lineItems(0) = lineItem1
    lineItems(1) = lineItem2
    
    po.orderLineItems = lineItems
    
    Dim ordermsg As MsmqMessage(Of PurchaseOrder) = New MsmqMessage(Of PurchaseOrder)(po)
    Using scope As New TransactionScope(TransactionScopeOption.Required)
        channel.SubmitPurchaseOrder(ordermsg)
        scope.Complete()
    End Using
    Console.WriteLine("Order has been submitted:{0}", po)
    
    MsmqIntegrationBinding binding = new MsmqIntegrationBinding();
    EndpointAddress address = new EndpointAddress("msmq.formatname:DIRECT=OS:.\\private$\\Orders");
    ChannelFactory<IOrderProcessor> channelFactory = new ChannelFactory<IOrderProcessor>(binding, address);
    IOrderProcessor channel = channelFactory.CreateChannel();
    
    PurchaseOrder po = new PurchaseOrder();
    po.customerId = "somecustomer.com";
    po.poNumber = Guid.NewGuid().ToString();
    
    PurchaseOrderLineItem lineItem1 = new PurchaseOrderLineItem();
    lineItem1.productId = "Blue Widget";
    lineItem1.quantity = 54;
    lineItem1.unitCost = 29.99F;
    
    PurchaseOrderLineItem lineItem2 = new PurchaseOrderLineItem();
    lineItem2.productId = "Red Widget";
    lineItem2.quantity = 890;
    lineItem2.unitCost = 45.89F;
    
    po.orderLineItems = new PurchaseOrderLineItem[2];
    po.orderLineItems[0] = lineItem1;
    po.orderLineItems[1] = lineItem2;
    
    
    MsmqMessage<PurchaseOrder> ordermsg = new MsmqMessage<PurchaseOrder>(po);
    using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required))
    {
        channel.SubmitPurchaseOrder(ordermsg);
        scope.Complete();
    }
    Console.WriteLine("Order has been submitted:{0}", po);
    
  3. Créez une configuration qui spécifie l'utilisation de la liaison MsmqIntegrationBinding.

    Dim binding As New MsmqIntegrationBinding("MyBindingConfig")
    
    MsmqIntegrationBinding binding = new MsmqIntegrationBinding("MyBindingConfig");
    
    <configuration>
        <system.serviceModel>
    
        <client>
          <endpoint  name="OrderResponseEndpoint" 
                    address="msmq.formatname:DIRECT=OS:.\private$\Orders"
                    binding="msmqIntegrationBinding"
                    bindingConfiguration="OrderProcessorBinding" 
                    contract="Microsoft.ServiceModel.Samples.IOrderProcessor">
          </endpoint>
        </client>
    
        <bindings>
          <msmqIntegrationBinding>
            <binding name="OrderProcessorBinding" >
              <security mode="None" />
            </binding>
          </msmqIntegrationBinding>
        </bindings>
    
      </system.serviceModel>
    
    </configuration>
    
  4. Créez une instance de la classe de client et appelez la méthode définie par le service qui reçoit le message.

    // Create the purchase order.
    PurchaseOrder po = new PurchaseOrder();
    po.customerId = "somecustomer.com";
    po.poNumber = Guid.NewGuid().ToString();
    
    PurchaseOrderLineItem lineItem1 = new PurchaseOrderLineItem();
    lineItem1.productId = "Blue Widget";
    lineItem1.quantity = 54;
    lineItem1.unitCost = 29.99F;
    
    PurchaseOrderLineItem lineItem2 = new PurchaseOrderLineItem();
    lineItem2.productId = "Red Widget";
    lineItem2.quantity = 890;
    lineItem2.unitCost = 45.89F;
    
    po.orderLineItems = new PurchaseOrderLineItem[2];
    po.orderLineItems[0] = lineItem1;
    po.orderLineItems[1] = lineItem2;
    
    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();
    
    Console.WriteLine();
    Console.WriteLine("Press <ENTER> to terminate client.");
    Console.ReadLine();
    

Voir aussi

Tâches

Comment : échanger des messages en file d'attente avec des points de terminaison WCF
Windows Communication Foundation to Message Queuing
Message Queuing to Windows Communication Foundation
Message Security over Message Queuing

Concepts

Vue d'ensemble des files d'attente
Installation de Message Queuing (MSMQ)

Autres ressources

Message Queuing Integration Binding Samples