다음을 통해 공유


Windows Communication Foundation과 메시지 큐잉 간의 연결

WcfToMsmq 샘플은 WCF(Windows Communication Foundation) 애플리케이션이 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 메시지를 큐로 보냅니다. 메시지를 수신하고 처리하는 애플리케이션은 WCF 애플리케이션이 아닌 MSMQ 애플리케이션이므로 두 애플리케이션 간에 암시적 서비스 계약이 없습니다. 따라서 이 시나리오에서는 Svcutil.exe 도구를 사용하여 프록시를 만들 수 없습니다.

사용자 지정 클라이언트는 바인딩을 사용하여 메시지를 보내는 모든 WCF 애플리케이션에서 MsmqIntegration 기본적으로 동일합니다. 다른 클라이언트와 달리 다양한 서비스 작업은 포함하지 않습니다. 메시지 제출 작업입니다.

[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 Communication Foundation 샘플 실행의 지침을 따릅니다.

컴퓨터에서 샘플 실행

  1. \service\bin\ 폴더의 언어별 폴더 아래에 있는 서비스 프로그램 파일을 서비스 컴퓨터로 복사합니다.

  2. 언어별 폴더 아래의 \client\bin\ 폴더에서 클라이언트 컴퓨터로 클라이언트 프로그램 파일을 복사합니다.

  3. Client.exe.config 파일에서 클라이언트 엔드포인트 주소를 변경하여 "." 대신 서비스 컴퓨터 이름을 지정합니다.

  4. 서비스 컴퓨터에서 명령 프롬프트에서 Service.exe 시작합니다.

  5. 클라이언트 컴퓨터의 명령 프롬프트에서 Client.exe 시작합니다.

참고하십시오