基于WCF框架的分布式事务处理方案
第一:服务契约(ServiceContract)中的配置
ServiceContract(SessionMode = SessionMode.Required)] public interface IDistributedTransaction { [TransactionFlow(TransactionFlowOption.Allowed)] [OperationContract] void Add(); }
第二:服务契约实现的配置
[OperationBehavior(TransactionAutoComplete = true, TransactionScopeRequired = true)] public void Add() { conn1.Open(); SqlCommand command = new SqlCommand("insert into test2 values(111)", conn1); command.ExecuteNonQuery(); DataBaseOperation.DisplayTransactioninfo.Display(System.Transactions.Transaction.Current); }
第三:WebConfig 配置
<service name="ServerConsole.Transaction.DistributedTransactionService1" behaviorConfiguration="metadatabehaviors"> <host> <baseAddresses> <add baseAddress="http://localhost:8027"/> <add baseAddress="net.tcp://localhost:8028"/> </baseAddresses> </host> <endpoint address="DistributedTransactionService1" binding="netTcpBinding" bindingConfiguration="tranbinding" contract="ServerConsole.Transaction.IDistributedTransaction"></endpoint> </service> <bindings> <netTcpBinding> <binding name="tranbinding" transactionFlow="true" transactionProtocol="WSAtomicTransactionOctober2004"> <reliableSession enabled="true" ordered="true"/> </binding> </netTcpBinding> </bindings>
第四:客户端 使用
using (TransactionScope transcope = new TransactionScope()) { try { Transaction.Current.TransactionCompleted += new TransactionCompletedEventHandler(Current_TransactionCompleted); tranclient.Add(); tranclient2.Add(); transcope.Complete(); } catch (Exception err) { Transaction.Current.Rollback(); } } static void Current_TransactionCompleted(object sender, TransactionEventArgs e) { if (e.Transaction.TransactionInformation.Status == System.Transactions.TransactionStatus.Committed) Console.WriteLine(e.Transaction.TransactionInformation.DistributedIdentifier); }
客户端使用TransactionScope类来进行环境事务的设置,这样就很方便知道事务的执行范围,在TransactionScope里面我们可以通过Transaction.Current获取到当前上下文的事务对象,由于事务对象是存储在线程独立存储区里的,所以跨线程访问是没用的,通过依赖事务进行传递。
参考:http://www.cnblogs.com/wangiqngpei557/archive/2011/12/22/2298500.html#