세션 샘플에서는 MSMQ(메시지 큐) 전송을 통해 대기 중인 통신에서 관련 메시지 집합을 보내고 받는 방법을 보여 줍니다. 이 샘플에서는 바인딩을 netMsmqBinding
사용합니다. 서비스는 대기 중인 메시지를 수신하는 서비스를 관찰할 수 있도록 하는 자체 호스팅 콘솔 애플리케이션입니다.
비고
이 샘플에 대한 설치 절차 및 빌드 지침은 이 항목의 끝에 있습니다.
대기 중인 통신에서 클라이언트는 큐를 사용하여 서비스와 통신합니다. 보다 정확하게 말하자면, 클라이언트는 큐에 메시지를 보냅니다. 서비스는 큐에서 메시지를 받습니다. 따라서 서비스와 클라이언트는 큐를 사용하여 통신하기 위해 동시에 실행될 필요가 없습니다.
경우에 따라 클라이언트는 그룹에서 서로 관련된 메시지 집합을 보냅니다. 메시지를 함께 또는 지정된 순서로 처리해야 하는 경우 큐를 사용하여 단일 수신 애플리케이션에서 처리하기 위해 메시지를 그룹화할 수 있습니다. 이는 서버 그룹에 여러 수신 애플리케이션이 있고 동일한 수신 애플리케이션에서 메시지 그룹을 처리해야 하는 경우에 특히 중요합니다. 대기 중인 세션은 한 번에 처리해야 하는 관련 메시지 집합을 보내고 받는 데 사용되는 메커니즘입니다. 큐에 대기된 세션은 이 패턴을 나타내기 위해 트랜잭션이 필요합니다.
샘플에서 클라이언트는 단일 트랜잭션 범위 내에서 세션의 일부로 서비스에 많은 메시지를 보냅니다.
서비스 계약은 IOrderTaker
큐에 사용하기에 적합한 단방향 서비스를 정의하는 계약입니다. 다음 샘플 코드에 표시된 계약에 사용된 내용은 SessionMode 메시지가 세션의 일부임을 나타냅니다.
[ServiceContract(Namespace = "http://Microsoft.ServiceModel.Samples", SessionMode=SessionMode.Required)]
public interface IOrderTaker
{
[OperationContract(IsOneWay = true)]
void OpenPurchaseOrder(string customerId);
[OperationContract(IsOneWay = true)]
void AddProductLineItem(string productId, int quantity);
[OperationContract(IsOneWay = true)]
void EndPurchaseOrder();
}
서비스는 첫 번째 작업이 트랜잭션에 참여하지만 트랜잭션을 자동으로 완료하지 않는 방식으로 서비스 작업을 정의합니다. 후속 작업도 동일한 트랜잭션에 참여하지만 자동으로 완료되지는 않습니다. 세션의 마지막 작업은 트랜잭션을 자동으로 완료합니다. 따라서 동일한 트랜잭션이 서비스 계약의 여러 작업 호출에 사용됩니다. 작업이 예외를 발생시키는 경우 트랜잭션이 롤백되고 세션이 큐에 다시 들어갑니다. 마지막 작업이 성공적으로 완료되면 트랜잭션이 커밋됩니다. 서비스는 PerSession
를 InstanceContextMode로 사용하여 서비스의 동일한 인스턴스에서 세션의 모든 메시지를 수신합니다.
[ServiceBehavior(InstanceContextMode=InstanceContextMode.PerSession)]
public class OrderTakerService : IOrderTaker
{
PurchaseOrder po;
[OperationBehavior(TransactionScopeRequired = true,
TransactionAutoComplete = false)]
public void OpenPurchaseOrder(string customerId)
{
Console.WriteLine("Creating purchase order");
po = new PurchaseOrder(customerId);
}
[OperationBehavior(TransactionScopeRequired = true,
TransactionAutoComplete = false)]
public void AddProductLineItem(string productId, int quantity)
{
po.AddProductLineItem(productId, quantity);
Console.WriteLine("Product " + productId + " quantity " +
quantity + " added to purchase order");
}
[OperationBehavior(TransactionScopeRequired = true,
TransactionAutoComplete = true)]
public void EndPurchaseOrder()
{
Console.WriteLine("Purchase Order Completed");
Console.WriteLine();
Console.WriteLine(po.ToString());
}
}
서비스가 자체 호스팅됩니다. MSMQ 전송을 사용하는 경우 사용되는 큐를 미리 만들어야 합니다. 이 작업은 수동으로 또는 코드를 통해 수행할 수 있습니다. 이 샘플에서 서비스는 큐의 존재를 확인하기 위한 코드를 포함하며, 필요한 경우 큐를 만듭니다. 큐 이름은 AppSettings 클래스를 사용하여 구성 파일에서 읽습니다.
// Host the service within this EXE console application.
public static void Main()
{
// Get MSMQ queue name from app settings in configuration.
string queueName = ConfigurationManager.AppSettings["queueName"];
// Create the transacted MSMQ queue if necessary.
if (!MessageQueue.Exists(queueName))
MessageQueue.Create(queueName, true);
// Create a ServiceHost for the OrderTakerService type.
using (ServiceHost serviceHost = new ServiceHost(typeof(OrderTakerService)))
{
// Open the ServiceHost to create listeners and start listening for messages.
serviceHost.Open();
// The service can now be accessed.
Console.WriteLine("The service is ready.");
Console.WriteLine("Press <ENTER> to terminate service.");
Console.WriteLine();
Console.ReadLine();
// Close the ServiceHost to shutdown the service.
serviceHost.Close();
}
}
MSMQ 큐 이름은 구성 파일의 appSettings 섹션에 지정됩니다. 서비스의 엔드포인트는 구성 파일의 system.serviceModel 섹션에 정의되고 바인딩을 netMsmqBinding
지정합니다.
<appSettings>
<!-- Use appSetting to configure MSMQ queue name. -->
<add key="queueName" value=".\private$\ServiceModelSamplesSession" />
</appSettings>
<system.serviceModel>
<services>
<service name="Microsoft.ServiceModel.Samples.OrderTakerService"
behaviorConfiguration="CalculatorServiceBehavior">
...
<!-- Define NetMsmqEndpoint -->
<endpoint address="net.msmq://localhost/private/ServiceModelSamplesSession"
binding="netMsmqBinding"
contract="Microsoft.ServiceModel.Samples.IOrderTaker" />
...
</service>
</services>
...
</system.serviceModel>
클라이언트는 트랜잭션 범위를 만듭니다. 세션의 모든 메시지는 트랜잭션 범위 내의 큐로 전송되므로 모든 메시지가 성공하거나 실패하는 원자 단위로 처리됩니다. 트랜잭션은 호출 Complete하여 커밋됩니다.
//Create a transaction scope.
using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required))
{
// Create a client with given client endpoint configuration.
OrderTakerClient client = new OrderTakerClient("OrderTakerEndpoint");
// Open a purchase order.
client.OpenPurchaseOrder("somecustomer.com");
Console.WriteLine("Purchase Order created");
// Add product line items.
Console.WriteLine("Adding 10 quantities of blue widget");
client.AddProductLineItem("Blue Widget", 10);
Console.WriteLine("Adding 23 quantities of red widget");
client.AddProductLineItem("Red Widget", 23);
// Close the purchase order.
Console.WriteLine("Closing the purchase order");
client.EndPurchaseOrder();
//Closing the client gracefully closes the connection and cleans up resources.
client.Close();
// Complete the transaction.
scope.Complete();
}
비고
세션의 모든 메시지에 대해 단일 트랜잭션만 사용할 수 있으며 트랜잭션을 커밋하기 전에 세션의 모든 메시지를 보내야 합니다. 클라이언트를 닫으면 세션이 닫힙니다. 따라서 세션의 모든 메시지를 큐로 보내려면 트랜잭션이 완료되기 전에 클라이언트를 닫아야 합니다.
샘플을 실행하면 서비스 및 클라이언트 콘솔 창에 클라이언트 및 서비스 활동이 모두 표시됩니다. 서비스가 클라이언트에서 메시지를 수신하는 것을 볼 수 있습니다. 각 콘솔 창에서 Enter 키를 눌러 서비스 및 클라이언트를 종료합니다. 큐가 사용 중이므로 클라이언트와 서비스가 동시에 실행될 필요가 없습니다. 클라이언트를 실행하고 종료한 다음 서비스를 시작하고 해당 메시지를 계속 받을 수 있습니다.
클라이언트에서.
Purchase Order created
Adding 10 quantities of blue widget
Adding 23 quantities of red widget
Closing the purchase order
Press <ENTER> to terminate client.
서비스에서.
The service is ready.
Press <ENTER> to terminate service.
Creating purchase order
Product Blue Widget quantity 10 added to purchase order
Product Red Widget quantity 23 added to purchase order
Purchase Order Completed
Purchase Order: 7c86fef0-2306-4c51-80e6-bcabcc1a6e5e
Customer: somecustomer.com
OrderDetails
Order LineItem: 10 of Blue Widget @unit price: $2985
Order LineItem: 23 of Red Widget @unit price: $156
Total cost of this order: $33438
Order status: Pending
샘플 설정, 빌드 및 실행
Windows Communication Foundation 샘플 에 대한One-Time 설정 절차를 수행했는지 확인합니다.
솔루션의 C#, C++또는 Visual Basic .NET 버전을 빌드하려면 Windows Communication Foundation 샘플 빌드의 지침을 따릅니다.
단일 또는 컴퓨터 간 구성에서 샘플을 실행하려면 Windows Communication Foundation 샘플실행의 지침을 따릅니다.
기본적으로 NetMsmqBinding 전송 보안이 활성화됩니다. MSMQ 전송 보안에는 두 가지 관련 속성이 있습니다. 즉, MsmqAuthenticationModeMsmqProtectionLevel.
기본적으로 인증 모드가 설정 Windows
되고 보호 수준이 설정Sign
됩니다. MSMQ가 인증 및 서명 기능을 제공하려면 도메인의 일부여야 하며 MSMQ에 대한 Active Directory 통합 옵션을 설치해야 합니다. 이러한 조건을 충족하지 않는 컴퓨터에서 이 샘플을 실행하면 오류가 발생합니다.
작업 그룹에 조인된 컴퓨터에서 샘플 실행
컴퓨터가 도메인에 속하지 않거나 Active Directory 통합이 설치되어 있지 않은 경우 다음 샘플 구성과 같이 인증 모드 및 보호 수준을 설정하여
None
전송 보안을 해제합니다.<system.serviceModel> <services> <service name="Microsoft.ServiceModel.Samples.OrderTakerService" behaviorConfiguration="OrderTakerServiceBehavior"> <host> <baseAddresses> <add baseAddress= "http://localhost:8000/ServiceModelSamples/service"/> </baseAddresses> </host> <!-- Define NetMsmqEndpoint --> <endpoint address= "net.msmq://localhost/private/ServiceModelSamplesSession" binding="netMsmqBinding" bindingConfiguration="Binding1" contract="Microsoft.ServiceModel.Samples.IOrderTaker" /> <!-- The mex endpoint is exposed at--> <!--http://localhost:8000/ServiceModelSamples/service/mex. --> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" /> </service> </services> <bindings> <netMsmqBinding> <binding name="Binding1"> <security mode="None" /> </binding> </netMsmqBinding> </bindings> <behaviors> <serviceBehaviors> <behavior name="OrderTakerServiceBehavior"> <serviceMetadata httpGetEnabled="True"/> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel>
샘플을 실행하기 전에 서버와 클라이언트 모두에서 구성을 변경해야 합니다.
비고
보안 모드를
None
로 설정하는 것은 MsmqAuthenticationMode, MsmqProtectionLevel, 그리고Message
보안을None
로 설정하는 것과 동일합니다.