다음을 통해 공유


Windows Communication Foundation에 대한 메시지 큐

MsmqToWcf 샘플에서는 MSMQ(메시지 큐) 애플리케이션이 WCF(Windows Communication Foundation) 서비스에 MSMQ 메시지를 보내는 방법을 보여 줍니다. 서비스는 대기 중인 메시지를 수신하는 서비스를 관찰할 수 있도록 하는 자체 호스팅 콘솔 애플리케이션입니다.

서비스 계약은 IOrderProcessor큐에 사용하기에 적합한 단방향 서비스를 정의하는 계약입니다. MSMQ 메시지에 작업 헤더가 없으므로 다른 MSMQ 메시지를 작업 계약에 자동으로 매핑할 수 없습니다. 따라서 하나의 작업 계약만 있을 수 있습니다. 서비스에 대해 둘 이상의 작업 계약을 정의하려는 경우 애플리케이션은 MSMQ 메시지의 헤더(예: 레이블 또는 correlationID)를 사용하여 디스패치할 작업 계약을 결정할 수 있는 정보를 제공해야 합니다.

MSMQ 메시지에는 작업 계약의 다른 매개 변수에 매핑되는 헤더에 대한 정보가 포함되어 있지 않습니다. 매개 변수는 기본 MSMQ 메시지를 포함하는 형식 MsmqMessage<T>(MsmqMessage<T>)입니다. (MsmqMessage<T>) 클래스의 MsmqMessage<T>"T" 형식은 MSMQ 메시지 본문으로 serialize되는 데이터를 나타냅니다. 이 샘플에서는 PurchaseOrder 형식이 MSMQ 메시지 본문으로 직렬화됩니다.

다음 샘플 코드는 주문 처리 서비스의 서비스 계약을 보여줍니다.

// Define a service contract.
[ServiceContract(Namespace = "http://Microsoft.ServiceModel.Samples")]
[ServiceKnownType(typeof(PurchaseOrder))]
public interface IOrderProcessor
{
    [OperationContract(IsOneWay = true, Action = "*")]
    void SubmitPurchaseOrder(MsmqMessage<PurchaseOrder> msg);
}

서비스가 자체 호스팅됩니다. MSMQ를 사용하는 경우 사용되는 큐를 미리 만들어야 합니다. 이 작업은 수동으로 또는 코드를 통해 수행할 수 있습니다. 이 샘플에서 서비스는 큐의 존재를 확인하고 필요한 경우 만듭니다. 큐 이름은 구성 파일에서 읽습니다.

public static void Main()
{
    // Get the MSMQ queue name from the application settings in
    // configuration.
    string queueName = ConfigurationManager.AppSettings["queueName"];
    // Create the MSMQ queue if necessary.
    if (!MessageQueue.Exists(queueName))
        MessageQueue.Create(queueName, true);
    …
}

서비스는 다음 샘플 코드와 같이 ServiceHostOrderProcessorService에 대해 생성하고 엽니다.

using (ServiceHost serviceHost = new ServiceHost(typeof(OrderProcessorService)))
{
    serviceHost.Open();
    Console.WriteLine("The service is ready.");
    Console.WriteLine("Press <ENTER> to terminate service.");
    Console.ReadLine();
    serviceHost.Close();
}

MSMQ 큐 이름은 다음 샘플 구성과 같이 구성 파일의 appSettings 섹션에 지정됩니다.

비고

큐 이름은 로컬 컴퓨터를 나타낼 때 점(.)을 사용하고 경로에서는 백슬래시 구분 기호를 사용합니다. WCF 엔드포인트 주소는 msmq.formatname 체계를 지정하고 로컬 컴퓨터에 localhost를 사용합니다. 각 MSMQ 형식 이름 주소 지정 지침에 대한 큐 주소는 msmq.formatname 스키마를 따릅니다.

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

클라이언트 애플리케이션은 다음 샘플 코드와 같이 이 메서드를 사용하여 Send 큐에 지속성 및 트랜잭션 메시지를 보내는 MSMQ 애플리케이션입니다.

//Connect to the queue.
MessageQueue orderQueue = new MessageQueue(ConfigurationManager.AppSettings["orderQueueName"]);

// 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;

// Submit the purchase order.
Message msg = new Message();
msg.Body = po;
//Create a transaction scope.
using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required))
{

    orderQueue.Send(msg, MessageQueueTransactionType.Automatic);
    // Complete the transaction.
    scope.Complete();

}
Console.WriteLine("Placed the order:{0}", po);
Console.WriteLine("Press <ENTER> to terminate client.");
Console.ReadLine();

샘플을 실행하면 서비스 및 클라이언트 콘솔 창에 클라이언트 및 서비스 활동이 모두 표시됩니다. 서비스가 클라이언트에서 메시지를 수신하는 것을 볼 수 있습니다. 각 콘솔 창에서 Enter 키를 눌러 서비스 및 클라이언트를 종료합니다. 큐 시스템이 사용되고 있기 때문에, 클라이언트와 서비스가 동시에 가동될 필요가 없습니다. 예를 들어 클라이언트를 실행하고 종료한 다음 서비스를 시작하면 해당 메시지가 계속 수신됩니다.

샘플 설정, 빌드 및 실행

  1. Windows Communication Foundation 샘플 에 대한One-Time 설정 절차를 수행했는지 확인합니다.

  2. 서비스가 먼저 실행되면 큐가 있는지 확인합니다. 큐가 존재하지 않으면 서비스가 큐를 생성합니다. 서비스를 먼저 실행하여 큐를 만들거나 MSMQ 큐 관리자를 통해 만들 수 있습니다. 다음 단계에 따라 Windows 2008에서 큐를 만듭니다.

    1. Visual Studio 2012에서 서버 관리자를 엽니다.

    2. 기능 탭을 확장합니다.

    3. 프라이빗 메시지 큐 마우스 오른쪽 단추로 클릭하고 새 프라이빗 큐선택합니다.

    4. 트랜잭션 체크박스를 선택하세요.

    5. 새 큐의 이름으로 ServiceModelSamplesTransacted 입력합니다.

  3. 솔루션의 C# 또는 Visual Basic .NET 버전을 빌드하려면 Windows Communication Foundation 샘플빌드의 지침을 따릅니다.

  4. 단일 컴퓨터 구성에서 샘플을 실행하려면 Windows Communication Foundation 샘플 실행의 지침을 따릅니다.

컴퓨터에서 샘플 실행

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

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

  3. Client.exe.config 파일에서 orderQueueName을 변경하여 "."가 아닌 서비스 컴퓨터 이름을 지정합니다.

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

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

참고하십시오