QuickStart Series--wcf--06 Concurrent current limit, reliable sessions, and queue services

Source: Internet
Author: User
Tags msmq

This part will introduce some relatively deep knowledge points, including through the concurrent limit to ensure the availability of the service, through the reliable session mechanism to ensure the reliability of the session information, through the queue service to decouple the client and the server, improve the system can serve the number of services and can play the role of shaving, and finally the previous transaction knowledge will be supplemented.

For WCF services, it is hosted in a resource-constrained environment, in order to maximize service performance, it needs to increase its throughput as a service concurrency. However, in the absence of traffic control, too much concurrency can cause the entire service to crash due to resource exhaustion. Therefore, for relatively balanced concurrency and system availability, it is necessary to design a gate (throttling) to control the number of concurrent numbers.

Because the concurrency of WCF belongs to the behavior of the service itself, it is controlled through the service behavior, The Concurrencymodel attribute in ServiceBehaviorAttribute (which is similar to the callback Callbackbehaviorattribute) defines the single, Reentrant and multiple three typical concurrency patterns, single means that an instance context InstanceContext can only be used for the processing of one request, and reentrant also indicates that a power context can only be used to handle a single request at a time, However, if a callback is involved, it can also be used for processing other service invocation requests, multiple indicates that a power context can handle multiple service requests at the same time. In addition, when the ReleaseServiceInstanceOnTransactionComplete property of the service behavior is set to TRUE, its synchronous mode must be single because the instance cannot be disposed while other requests are still in process. Additionally, you can suppress concurrent operations by setting the Usersynchronizationcontext property to False.

You can limit the flow by setting the relevant properties of the System.ServiceModel.Description.ServiceThrottlingBehavior, including:

Maxconcurrentcalls: The maximum number of concurrent messages that the current ServiceHost can handle, the default is single core 16.

Maxconcurrentinstances: The number of service instance contexts that the current ServiceHost allows to exist, with a default of 116.

MaxConcurrentSessions: The default is 100 when the maximum number of concurrent sessions allowed for a pro ServiceHost.

In fact, WCF builds a dedicated internal component, Flowthrottle, that contains a capacity property that represents the maximum traffic, and a queue and counter. Servicethrottle Three traffic limiters are like three gates set up in the channel dispatcher, the first limiting traffic to concurrent sessions, the second limiting the number of concurrent requests, and the third limiting the number of concurrent instance contexts. Why is this order of judgment still in doubt ?

As a basic platform of communication, it is necessary to maintain the reliability of the message, because the network layer cannot guarantee the effective delivery of the message because of the network environment, so it is necessary to implement the reliable session mechanism in the application layer to achieve the end-to-end reliable information transmission. For possible transmissions, common problems include the issue of duplicate messages and unordered messages. Speaking of this, we have to mention the TCP protocol, which is used to solve the IP layer message transmission is not possible and no connection problem, it through 3 this handshake to establish a long connection, through the message acknowledgement and time-out retransmission mechanism to ensure the reliability of the message. So what's the difference between it and the RM in WCF that we're going to mention now? Mainly includes the following 4 points: WCF reliable message is soap-based, and TCP is based on the message segment, which is independent of the transport protocol, not limited to the TCP protocol, and there is no specific transfer session limit, can span multiple transport connections or sessions; TCP provides end-to-end reliable transmission within the current connection. WS-RM provides a reliable transmission of two soap endpoints, regardless of the transmission connection limit.

In essence, the principle of the reliable transmission of WS-RM is similar to the active window mechanism of TCP, which first creates a connection (CreateSequence), the server returns to a identifier, and then begins the data transfer. Sequence's head contains identifier and Messageno, which is used to identify the order, and also includes Acksto, Expires, offer parameters, and finally terminatesequence. The main note is that in the request-reply mode of communication, in order to reduce traffic, the message will contain 2 parts, part is the reply to the previous message (Sequenceacknowledgement), part of the new message, the common reliable session configuration is as follows.

1<system.serviceModel>2<bindings>3<customBinding>4<binding name="OrderedDelivery">5<reliablesession ordered="true"/>6<binaryMessageEncoding>7<readerquotas maxarraylength="2147483647"/>8</binaryMessageEncoding>9<tcptransport maxbuffersize="2147483647"Maxreceivedmessagesize="2147483647"></tcpTransport>Ten</binding> One</customBinding> A</bindings> -</system.serviceModel>
View Code

Finally, a table provides a simple introduction to the best practices for reliable sessions.

Way Interpretation
set maxtransferwindowsize
Use network effectively
Full load Operation service
start flow control
set maxpendingchannels
Reliable sessions and hosts A reliable session is stateful, with AppDomain maintenance, and in the duplex scenario, each client requires two HTTP connections, so there may be a situation where the resource is using an excessive deadlock, which is required to be handled in the following settings. <system.net> <connectionmanagement><add name = "*" maxconnection= "XX"/> </connectionmanagement > <system.net>

This section will introduce Microsoft MSMQ, although very old, but still need to do a basic understanding, of course, it is now more recommended RABBITMQ Open source queue framework, anyway, in the Internet scenario, Message Queuing is the best solution to solve peak-valley balance. It is similar to the human traditional letter correspondence, the sender only needs the addressee address, the postal code and the name information, still will put the letter in the mailbox, but the recipient only then checks the receiving letter regularly. In order to use Message Queuing, MSMQ is first installed through Windows features, including components such as AD service integration, HTTP support, triggers, multicast support, and DCOM proxy. Message Queuing information is stored in the%windir%\system32\msmq\storage, which is common, and queues are categorized as follows.

Normal queue: Specific application created, business-based queues, divided into public and private, public queues are registered in the AD domain, and their Windows authentication mechanism based on domain accounts.

Manage queues: Acknowledgment messages are stored in the management queue, including success confirmations and failed acknowledgments.

Reply queue: MSMQ is completely in one-way message exchange Mode, after the message is sent there is no reply message returned to the sender, but in some scenarios, need to include a simple acknowledgment of the reply content, which is related to the service queue

Log queue: When a message is successfully sent or accepted, MSMQ can store a copy of the message as a send or accept log, divided into source and destination logs.

transactional queues: Like SQL Server, MSMQ belongs to the transaction manager (Rm,resourcemanager) and can be enlisted into a distributed transaction.

Dead-letter queue: Unable to deliver information within a limited time

Report queue: is a public queue that stores report information for route tracking

Sub-queue: is a message container, a common operation for Message Queuing is to transfer messages from one queue to another, its typical applications include: Orderly submission, you can put the chaotic message temporarily in the sub-queue, ordered after ordering; poison queue, when the frequent error, It can be temporarily present in a corresponding sub-queue to allow other messages to be processed in a timely manner.

MSMQ-based APIs are concentrated in system.messaging, and their common path formats and their examples are shown below.

queue type

mode

Journal queue (Public) {machinename}\{queuename}\journal$
Log Queue (private) {machinename}\private$\{queuename}\journal$
System log Queue {machinename}\ journal$
system dead-letter queue {machinename}\ deadletter$
system transaction Dead-letter queue {machinename}\ xactdeadletter$
public queue direct=http://xionger-pc/msmq/myqueue
Example String Path = @ ". \private$\myqueue"; MessageQueue queue = new MessageQueue (path);

Its constructor, in addition to path, also includes sharedModeDenyReceive, which represents the current application exclusive destination queue, Enablecache represents the creation of the connection cache, and Queueaccessmodel represents the object due to what action (Peek, Receive, Send).

The whole structure includes: creation and deletion of message queue, query of message queue, creation of a MessageQueue object, format name of message queue, sending of message, MSMQ message, receiving and viewing of message

Its transaction model, transaction bulk operations, sessions, error handling and other operations are relatively complex, this part is not introduced.

Transaction protocol, including OLETX and ws-at two kinds: The former uses RPC as a means of communication, using binary encoding, is the most efficient distributed processing protocol, but only for the Windows platform; the latter ws-at is a member of the WS-*, supporting cross-platform.

Ws-coordination defines an extensible framework for coordinating all participants in a distributed activity through a coordinator and several coordination protocols, at the core of which is the coordinator, which provides activation services (Activation service), Registration services (registration Service) and protocol services (PROTOCOL). The establishment of a transaction model for two different applications will eventually boil down to the exchange of endpoint references between protocol services,

Next, go to the highly practical WCF Transaction Programming section, which consists of the following 3 concepts:

through the service contract to determine the transaction flow (Transaction flow) strategy , by defining the Transactionflowattribute to determine the transaction policy, notallowed that the client's transaction is not allowed to be transferred to the server, The server also does not have views to accept incoming transactions, allowed instead, mandatory indicates that the client must make service calls in the transaction.

The flow of transactions is implemented by binding , and the relevant configuration is shown below.

1<system.serviceModel>2<bindings>3<netTcpBinding>4<binding name ="transactionaltcpbinding"transactionflow="true"Transactionprotocol="WSAtomicTransactionOctober2004"/>5</netTcpBinding>6<ws2007HttpBinding>7<binding name="transactionalhttpbinding"transactionflow="true"></binding>8</ws2007HttpBinding>9</bindings>Ten</system.serviceModel>
View Code

The related behavior of the transaction is controlled through the service/operation behavior , as shown in the following configuration.

[ServiceBehavior (Transactionisolationlevel = isolationlevel.readcommitted, transactiontimeout = "00:05:00", TransactionAutoCompleteOnSessionClose = True)]

Here's an example of how to create a transactional service (a bank transfer operation that involves a bank fetch and another bank's deposit).

Step 1 The implementation of the service contract and service, add the attribute on the Service interface method [TransactionFlow (transactionflowoption.allowed)], add the [OperationBehavior on the Service implementation method ( Transactionscoperequired=true)].

Step 2 Deploy the service.

Step 3 calls Bankingservice.

Step 4 Set up the DTC, which is set in the Administration tool in Control Panel as shown in.

Step 5 takes the Ws-at protocol, which is added in the binding configuration item: <transactionflow transactionprotocol= "WSAtomicTransactiona11" >

Tip: So far, we still feel that this part of distributed transactions is more complex, preferably virtual out of the multi-machine distributed environment to practice and learn.

Resources:

[1] Jing Jinnan . WCF fully parses [M]. Shanghai : Electronic Industry Publishing house ,.

QuickStart Series--wcf--06 Concurrent current limit, reliable sessions, and queue services

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.