Distributed transaction--"Freshman admission system"

Source: Internet
Author: User
Tags connectionstrings


Preface 

Before you understand a distributed transaction, you need to understand what a transaction is. Business (Transaction) is like being an object, being a boyfriend or a friend, or being a stranger, without a good friend saying so.

Official explanation: A transaction provides a mechanism for incorporating all operations involved in an activity into an indivisible unit of execution, and all operations that comprise a transaction can be committed only if all operations are performed properly, as long as any one of the operations fails, resulting in a rollback of the entire transaction. Simply put: A transaction provides a mechanism to "either do it or do it all." Instant feeling, business has the spirit of the East University old man ~


Transaction Characteristics

atomicity (atomicity), Consistency (consistence), Isolation (isolation), persistence (durability), which are carried out around the atomicity of a transaction. Atomicity embodies the indivisibility of the transaction, the entire transaction is isolated from the outside world, from a consistent state to another consistent state, after the last transaction execution, the memory of the data into the database, is called persistent.


Distributed Transactions

A personal understanding is that a transaction involving multiple servers is called a distributed transaction. When a distributed transaction ends, the atomicity of the transaction requires that all servers either commit the transaction or terminate it altogether. One of the servers acts as the coordinator, allowing all servers to maintain the same results through the protocol.

For example, permissions can control the ability of students to log into the entire cloud platform via a mailbox. The basis for the rights to provide students with information, if the basis of the students to modify the number, then the corresponding in the authority system, the examination system will be the student number of the synchronization changes.

Transactions are not confined to the internal execution of a system, and can be synchronized across the system to achieve data.


Example

The distributed transactions I know are generally present in the database, or in the VS code. Here is a simple demo that I hope you can get a better understanding of distributed transactions in WCF.

Code background: Client A to the service side B transfer, a reduce the amount of money, B to increase the corresponding transfer information, the amount.


Client:


IAccount class:

<span style= "font-family:kaiti_gb2312;" >using system;using system.collections.generic;using system.linq;using system.runtime.serialization;using System.servicemodel;using system.text;namespace wcf_attranstest.service{    //Establish service Contract B transfer WCF service    [ Servicecontract]<span style= "Font-family:simsun;" >//features </span> public    interface Iaccountb    {        [OperationContract]        [TransactionFlow ( transactionflowoption.allowed)]//allows clients to use transactions,        void deposit (int depositorid, double amount);//Deposit Method    }}</ Span>

Transactionflowoption.allowed indicates that Opreation can participate in the transaction flow. Another attribute can be seen in the IACCOUNTB on the server side : transactionflowoption. Mandatory. This property is a distributed transaction that must be based on the incoming transaction and throws an exception if the client does not have a transaction.


Program Console:

<span style= "font-family:kaiti_gb2312;" >using system;using system.collections.generic;using system.linq;using system.text;using System.Transactions; Using system.servicemodel;using system.servicemodel.channels;using wcf_attranstest.service;using System.Data;using        System.data.sqlclient;using system.configuration;//Establish a Transfer client namespace wcf_attranstest.client{class Program {             How does the static void Main (string[] args) {/* client and server-side communication occur? * According to our previous study, from the practical point of view, we define the contract and implementation on the server, * Configure the open endpoint, open the metadata Exchange, add the service reference on the client, and then just a new object called Xxxclient.             This object has all the methods in the service contract and is called directly.             * In fact, the client and the server to establish a channel in the middle, through the channel communication.             * The client establishes a channel between the two endpoints and then encapsulates the * call to the service-side service as a message along the channel, the server-side obtains the message, establishes the service object on the server side *, and then performs the operation to encapsulate the return value into a message to the client. *///system.servicemodel provides a class named Channelfactory<>, which accepts the service contract interface as a generic parameter//, so that the new instance is called a service            Channel factory for contract xxx.            New instance of a channel factory, the service contract interface as a generic parameter. Channelfactory<iaccountb> myfactory = new Channelfactory<iaccountb> ("Endpointconfig");            Generate a channel, the factory is created by the contract interface, so in this is also the first IACCOUNTB interface iaccountb myclient = Myfactory.createchannel ();            Double amount = 500;            int depositorid = 1;                using (TransactionScope SCOP = new TransactionScope ())//Make code block transactional code {#region Data access, reduce deposit on specified account String connstr = configurationmanager.connectionstrings["ConnStr"].                ToString ();  A client reduces the amount of calls to B of the WCF service SqlCommand Mysqlcommand = new SqlCommand ("Update account set amount = amount-@amount                where Depositorid = @depositorid ");                Mysqlcommand.connection = new SqlConnection (CONNSTR);                SqlParameter par1 = new SqlParameter ("@amount", sqldbtype.decimal); Par1.                Value = amount;                MYSQLCOMMAND.PARAMETERS.ADD (PAR1);                PAR1 = new SqlParameter ("@depositorid", SqlDbType.Int); Par1.                Value = Depositorid;                MYSQLCOMMAND.PARAMETERS.ADD (PAR1);                MySqlCommand.Connection.Open ();                Mysqlcommand.executenonquery ();                MySqlCommand.Connection.Close ();                    #endregion try {myclient.deposit (Depositorid, amount);//The contract method of the call channel                Scop.complete (); } catch (Exception e) {Transaction.Current.Rollback ();//If the transaction execution is unsuccessful, rollback to a does not The state of <span style= "FONT-FAMILY:SIMSUN;FONT-SIZE:18PX;" ></span><pre name= "code" class= "CSharp" ></span><span style= "font-family:kaiti_gb2312;" }}}}}</span>

Service side:

IACCOUNTB class:

<span style= "font-family:kaiti_gb2312;" >using system;using system.collections.generic;using system.linq;using system.runtime.serialization;using System.servicemodel;using system.text;namespace wcf_attranstest.service{    //Establish system B transfer WCF service    [ServiceContract ] public    interface IACCOUNTB    {        [OperationContract]               [TransactionFlow ( transactionflowoption.mandatory)]<span style= "font-family:arial, Helvetica, Sans-serif;" >//operation must follow incoming transactions, participate in distributed transactions </span>        void deposit (int depositorid, double amount);//Transfer: Account ID, transfer amount    }}</span>


Accountbservice class:

<span style= "font-family:kaiti_gb2312;" >using system;using system.collections.generic;using system.linq;using system.runtime.serialization;using System.servicemodel;using system.text;using system.configuration;using system.data;using System.Data.SqlClient; The implementation of the service using system.transactions;using microsoft.ktmintegration;using SYSTEM.IO;//WCF transfers. Namespace Wcf_attranstest.service{[servicebehavior (InstanceContextMode = instancecontextmode.single)]public class accountbservice:iaccountb{[OperationBehavior (transactionscoperequired = true)]//client can initiate a distributed transaction with public void deposit    (int depositorid, double amount)        {Transaction ambienttransaction = transaction.current;        #region Create a new transactional file, string path = @ "C:\test.txt";//Implement the deposit operation to complete two tasks, the first transfer information written to C:\text.text, the use of a transactional file Transactedfile.open FileStream fs = Transactedfile.open (path, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite, Sy Stem. Io.        Fileshare.readwrite); FileStream fs = File.Open (Path, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite, System.IO.FileShare.ReadWrite); String filecontent = String. Format ("Transfer from System A to System b\r\n user id:{0}\r\n Transfer amount is: {1}", Depositorid. ToString (), amount.        ToString ());        byte[] Bytearrar = Encoding.UTF8.GetBytes (filecontent); Fs.        Write (Bytearrar, 0, Bytearrar.count ()); Fs.        Flush (); Fs.        Close (); #endregion #region data access, increase the deposit on the specified account string connstr = configurationmanager.connectionstrings["ConnStr"].        ToString (); SqlCommand Mysqlcommand = new SqlCommand ("Update account set amount = Amount + @amount where Depositorid = @depositorid")        ;        Mysqlcommand.connection = new SqlConnection (CONNSTR);        SqlParameter par1 = new SqlParameter ("@amount", sqldbtype.decimal); Par1.        Value = amount;        MYSQLCOMMAND.PARAMETERS.ADD (PAR1);        PAR1 = new SqlParameter ("@depositorid", SqlDbType.Int); Par1.        Value = Depositorid;        MYSQLCOMMAND.PARAMETERS.ADD (PAR1); Mysqlcommand.        Connection.Open ();        Mysqlcommand.executenonquery ();        MySqlCommand.Connection.Close (); #endregion}}}</span>


Summary

Distributed is not only reflected in the transaction, it represents the spirit of teamwork, and a big problem is divided into fragmented small problems assigned to more computer conquer. Later on the Internet, search the difference between distributed and clustered: distributed is to shorten the execution time of a single task to improve efficiency, the cluster is to improve the efficiency by increasing the number of tasks executed per unit of time. Distributed is like doing a complex arithmetic problem, assigning subtraction to different people, and everyone studies a piece, and the whole is out. Cluster is a group of people to do the problem, a fixed number of questions will be shared.

The information society is changing rapidly, and the cloud and big data will be the next wave.

 



Distributed transaction--"Freshman admission system"

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.