WCF Learning--windows Transaction System

Source: Internet
Author: User
Tags terminates

Recently began to learn WCF-related knowledge, although the actual work of using the company's own set of SOA system, but Microsoft's set of service architecture has a lot of reference. In addition to some of the basic uses of WCF, relatively complex content has distributed transactions and communication security, etc., but the basic is associated with the ws-protocol cluster. In order to elicit transaction processing in WCF, today gives priority to the transaction processing model under Windows, to be honest with TransactionScope for many years, I have never known how it works. Recall that there are implementations similar to this in Java, whether EJB or spring. Learn the principles of this section today by learning Jing Jinnan's WCF Service Framework parsing.

First, recall the concept of transaction and related application mechanism. Transactions have acid (atomicity, consistency, isolation, persistence) features, major scenarios such as bank transfers, and most databases support transactional operations (SQL Server,oracle,db2,mysql-innodb). The most common implementation of transactions is the use of transactions in SQL statements, begin TRANSACTION, COMMIT TRANSACTION, ROLLBACK TRANSACTION, Transactions can also be controlled through the Dbtransaction object of ADO, but these can only support a single linked local transaction, not a distributed transaction. But in actual projects, the participants in a transaction tend not to be distributed across the same network node, sometimes in different types of transactional resources (not just databases, but also file systems, registries, etc.). Typical business scenarios for distributed transactions are in three categories: the access of multiple resources into the same transaction, the incorporation of multiple services into the same transaction (involving transaction flows between services), and the incorporation of multiple resources and services into the same transaction (as shown).

Next go to the transactional model under core content windows, and the transaction model typically consists of three roles:

Applications (also including services, components, etc.), Resource Manager RM (a software program that manages the transaction-specific resources), the transaction Manager TM (the middleware program that manages the entire transaction). Transactions are performed in order to implement a set of related operations as an integral whole, ensuring that the data is consistent and, in effect, serving the application. The application is primarily responsible for starting transaction & transaction marshaling (marshaling) and propagation (propagation), committing transactions.

Access to transactional resources is required through the Resource manager, depending on whether the target resource can be persisted, the corresponding resource manager is divided into: persistence (durable) resource manager, such as database Manager and careful queue, recoverable when the transaction is rolled back; volatile (volatile) The resource manager is used to manage memory-like resources without recoverability. Its primary responsibility is to help the application implement operations on the target resource, register to the appropriate transaction manager to accept recovery requests when rolling back, and report the results of local transactions to the transaction manager. Transaction manager

The transaction manager is the hub of the entire model, coordinating all the transaction participants, providing the start, commit, and rollback services of the transaction. Windows provides three different transaction managers, including the lightweight transaction manager LTM, the kernel transaction manager KTM, and the Distributed Transaction Coordinator DTC. However, it can be seen from here that transaction services do not have cross-platform features, so this part of the content is mainly used as reference learning, focusing on the principle of understanding. The lightweight transaction manager and the Kernel transaction manager are responsible for SQL Server and Windows file & Registry, respectively, and are efficient but not distributed. The Distributed Transaction Coordinator manages distributed transactions across boundaries, supports the OLE-TX and Ws-at protocols, and each Windows computer has a unique DTC for managing all local resource managers, which is distributed but less efficient. It is important to note that the transaction begins with the default LTM as the transaction manager, and in the course of its progress, the transaction is promoted (Transaction Promotion) based on the actual situation. For example, reading and writing to the registry will escalate to KTM, involving cross-domain marshaling being promoted to DTC.

So we don't have to ask, how is distributed transaction implemented? The two most critical concepts are the transaction registration & Transaction Submission tree (Transaction commit trees) and the two-phase commit protocol, which are described in the next two separate concepts.

The purpose of Transaction registration (Transaction Enlist) is to establish a relationship between transaction participants and to facilitate collaboration between them, as shown in the entire process:

The above transactions involve two machines, and the transaction is opened by ServiceA and is used as the environment transaction for the current execution context (Ambient Transaction). When ServiceA invokes a native resource manager (such as SQL Server), the RM is incorporated into this transaction. The Resource Manager RM makes transaction registrations to the local DTC so that the DTC establishes a hierarchy relationship with RM. When ServiceA calls ServiceB, the current transaction information (the Distributed transaction ID and the native DTC information) is marshaled, the service receives the post-fetch information to rebuild the transaction, and sets it to the environment transaction with the same ID as the original transaction. At the same time, SERVICEB based on the obtained MACHINEA DTC message, let the local DTC to the Machinea DTC transaction registration, so that the two machines DTC establish a subordinate relationship, then the RM also included in the DTC management. After the registration process is completed, the following transaction submission tree is formed:

In a distributed environment, transaction submissions need to ensure that when the operation succeeds, all data that needs to be persisted is written to the target resource by the corresponding Resource Manager rm, and the data in all RM fails when it is restored to its original state. To achieve this, distributed transaction submissions require a "two-phase commit" protocol, followed by a detailed description of the two phases:

The first stage-the preparation phase-the DTC of the root node initiates a request to all transaction participants to vote on the results of the local transaction, such as the recursive message propagation shown, the corresponding node feedback readiness, read-only, termination, and other voting types. If all voting results are ready and read-only on behalf of the submission, if any one is terminated then the representative terminates the submission. You can also set a time-out period if the entire transaction is rolled back beyond this time limit.

Phase II-COMMIT or rollback, the root node DTC initiates or terminates the entire transaction based on the poll result, using the same message propagation method as the first stage. When a transaction participant encounters an exception such as a network disconnection after the first phase of voting is completed, the child transaction is in the pending state. After this transaction is restarted, the DTC will ask the parent for the final result, and if the superior cannot confirm it continues to propagate to the root node until it gets a reply, the System Manager can force the commit or terminate the transaction if the time is too long.

In addition, in order to improve submission performance, the protocol determines whether a single-phase commit protocol is chosen based on the number of subordinate nodes that the node has, that is, the commit is initiated directly when the node has only one subordinate.

After the completion of the analysis of the principle, into the actual application, which is closely related to the work of the part. Based on the DTC-based Windows transaction architecture, WCF provides a complete distributed transaction solution. Provides a System.Transactions.Transaction imperative programming model and declarative programming for System.Transactions.TransactionScope.

The transaction class can be serialized as marshaled, and the resource manager is enlisted to the current transaction through EnlistDurable and EnlistVolatile, and the transaction submission tree is built. The Currrent property represents the current environment transaction (Ambient), which is stored in TLS on the current thread. The Transactioninformation property represents the basic information for a transaction, including the creation time, state, local identity, and distributed identity. And by IsolationLevel representing the isolation level, cloning transactions using the clone and Rollback methods, and rolling back transactions, it is important to note that the start and end of a transaction requires the same transaction to complete, and we refer to this transaction as a committed transaction (commitable Transaction), while other related transactions are referred to as dependent transactions (DependentTransaction). The commit transaction sets the time-out and isolation levels through the transactionoptions structure, or can be configured with the following configuration.

<system.transactions>

<defaultsettings timeout= "00:01:00"/>

<machinesettings maxtimeout= "00:10:00"/>

</system.transactions>

A COMMIT transaction commits a transaction through a commit method and an asynchronous Begin/endcommit method, as shown in the following example:

private static void Transfer (String accountfrom, String Accountto, double amount) {

Transaction originaltransaction = transaction.current;

CommittableTransaction ct = new committabletransaction ();

Try

{

transaction.current = ct;

Withdraw (accountfrom, amount);

Deposit (Accountto, amount);

Ct.commit ();

}

Catch

{

Ct. Rollback ();

Throw

}

finally {

Transaction.Current = originaltransaction;

Ct. Dispose ();

}

}

There is a Depedentclone method in the transaction class that is used to create its corresponding dependent transaction based on the current transaction, that is, its child transaction, passing the environment transaction of the current thread into the new transaction. The following code demonstrates the asynchronous way to bank transfer by relying on a transaction. It is important to note that because the options parameter specified when calling Dependentclone is Blockcommituntilcomplete, the main thread waits until the time-out when the dependent transaction does not end when the transaction is committed. There is also a transaction-based approach to the implementation is also very interesting, we are interested to see Mr. Jiang's original works.

private static void Transfer (String accountfrom, String Accountto, double amount)

{

Transaction originaltransaction = transaction.current;

CommittableTransaction ct = new committabletransaction ();

Try

{

transaction.current = ct;

ThreadPool.QueueUserWorkItem (state = {

Transaction.Current = state as dependenttransaction;

Try

{

Withdraw (accountfrom, amount);

Deposit (Accountto, amount);

(State as DependentTransaction). Complete ();

}

catch (Exception ex) {Transaction.Current.Rollback (ex);}

finally {

(State as DependentTransaction). Dispose ();

Transaction.Current = null;

}

}, Transaction.Current.DependentClone (Dependentcloneoption.blockcommituntilcomplete));

Ct.commit ();

}

Catch

{

Ct. Rollback ();

Throw

}

Finally

{

Transaction.Current = originaltransaction;

Ct. Dispose ();

}

}

At last, we introduce the most common TransactionScope class in actual work, such as the transaction method mentioned earlier, it is easy to implement.

static void Invokeintransaction (Action action)

{

using (TransactionScope ts = new TransactionScope ())

{

Ts.complete ();

}

}

Note that the TransactionScopeOption setting has the following three types: Required, which is used if an environment transaction is present, otherwise a new transaction is created before entering the scope, and the requiresnew is always creating new things in that range. ; Suppress, which indicates that the environment transaction is masked, that is, all operations are performed without environmental transactions. The required, requires_new, and not_supported in this Java EE spring are very similar, but for a mechanism similar to the one that is not covered by the Java EE and DTC, there is a chance to share it with you later.

Note: This article is mainly for their own study, the wrong place hope forgive me.

Resources:

[1] Jing Jinnan. WCF fully parses [M]. Shanghai: Electronic industry Press, 2012.

WCF Learning--windows Transaction System

Related Article

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.