Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use python to complete a distributed transaction TCC

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains "how to use python to complete a distributed transaction TCC". The content of the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to use python to complete a distributed transaction TCC".

1. TCC composition

TCC is divided into three stages.

Try phase: try to execute, complete all business checks (consistency), reserve necessary business resources (quasi-isolation)

Confirm phase: if the Try of all branches is successful, go to the Confirm phase. Confirm really executes the business, does not make any business inspection, and only uses the business resources reserved during the Try phase.

Cancel phase: if one of the Try of all branches fails, then go to the Cancel phase. Cancel releases the business resources reserved during the Try phase.

In TCC distributed transactions, there are three roles, just like classic XA distributed transactions:

An AP/ application that initiates a global transaction and defines which transaction branches the global transaction contains

RM/ resource manager, responsible for the management of branch transaction resources

TM/ transaction manager, responsible for coordinating the correct execution of global transactions, including Confirm,Cancel execution, and handling network exceptions

If we want to do a business similar to inter-bank transfer, TransOut and TransIn are in different microservices.

A typical timing diagram of a successfully completed TCC transaction is as follows:

2. TCC practice

For the previous interbank transfer operation, the easiest thing to do is to adjust the balance in the Try phase, reverse the balance in the Cancel phase, and empty in the Confirm phase. The problem with this is that if the A deduction succeeds, the amount transferred to B fails, and finally rollback, adjusting the balance of A to the initial value. In the process, if A finds that his balance has been deducted, but cashier B has not received the balance for a long time, it will cause trouble to A.

Better still, the amount of A transfer is frozen in the Try phase, the actual deduction is made by Confirm, and the funds are unfrozen by Cancel, so that the data that users see at any stage is clear.

Let's do a specific development of a TCC transaction

At present, the open source framework available for TCC is mainly the Java language, with seata as the representative. Our example is in Python, using a distributed transaction framework called https://github.com/yedf/dtm, which supports distributed transactions with great elegance. Let's explain the composition of TCC in detail.

First of all, we create two tables, one is the user balance table and the other is the frozen funds table. The statement is as follows:

CREATE TABLE dtm_ busi.`user _ roomt` (`id` int (11) AUTO_INCREMENT PRIMARY KEY, `update_ id` int (11) not NULL UNIQUE, `balance` decimal (10L2) NOT NULL DEFAULT '0.00create_, `update_ time` datetime DEFAULT now () CREATE TABLE dtm_ busi.`user _ account_ trading` (`id` int (11) AUTO_INCREMENT PRIMARY KEY, `trading_ id` int (11) not NULL UNIQUE, `trading_ balance` decimal (10Power2) NOT NULL DEFAULT '0.005, `create_ time` datetime DEFAULT now (), `update_ time` datetime DEFAULT now ()

In the trading table, trading_balance records the amount being traded.

We first write the core code, freeze / unfreeze funds, and check the constraint balance+trading_balance > = 0. If the constraint is not established, the execution fails.

Def tcc_adjust_trading (cursor, uid, amount): affected = utils.sqlexec (cursor, "update dtm_busi.user_account_trading set trading_balance=trading_balance +% d where user_id=%d and trading_balance +% d + (select balance from dtm_busi.user_account where id=%d) > = 0"% (amount, uid, amount, uid) if affected = = 0: raise Exception ("update error, maybe balance not enough")

Then adjust the balance.

Def tcc_adjust_balance (cursor, uid, amount): utils.sqlexec (cursor, "update dtm_busi.user_account_trading set trading_balance = trading_balance+% d where user_id=%d"% (- amount, uid)) utils.sqlexec (cursor, "update dtm_busi.user_account set balance=balance+%d where user_id=%d"% (amount, uid))

Let's write a specific Try/Confirm/Cancel handler.

@ app.post ("/ api/TransOutTry") def trans_out_try (): # transaction and exception handling tcc_adjust_trading (c, out_uid,-30) return {"dtm_result": "SUCCESS"} @ app.post ("/ api/TransOutConfirm") def trans_out_confirm (): # transaction and exception handling tcc_adjust_balance (c, out_uid -30) return {"dtm_result": "SUCCESS"} @ app.post ("/ api/TransOutCancel") def trans_out_cancel (): # transaction and exception handling tcc_adjust_trading (c, out_uid, 30) return {"dtm_result": "SUCCESS"} @ app.post ("/ api/TransInTry") def trans_in_try (): # transaction and exception handling tcc_adjust_trading (c, in_uid 30) return {"dtm_result": "SUCCESS"} @ app.post ("/ api/TransInConfirm") def trans_in_confirm (): # transaction and exception handling tcc_adjust_balance (c, in_uid, 30) return {"dtm_result": "SUCCESS"} @ app.post ("/ api/TransInCancel") def trans_in_cancel (): # transaction and exception handling tcc_adjust_trading (c, in_uid -30) return {"dtm_result": "SUCCESS"}

At this point, the handling functions of each subtransaction have been OK, and then the TCC transaction is opened and branch calls are made.

@ app.get ("/ api/fireTcc") def fire_tcc (): # initiate tcc transaction gid = tcc.tcc_global_transaction (dtm, utils.gen_gid (dtm), tcc_trans) return {"gid": gid} # specific handling of tcc transaction def tcc_trans (t): req = {"amount": 30} # the load of the business request # invokes the Try of the transfer service | Confirm | Cancel t.call_branch (req, svc + "/ TransOutTry") Svc + "/ TransOutConfirm", svc + "/ TransOutCancel") # call the Try transferred to the service | Confirm | Cancel t.call_branch (req, svc + "/ TransInTry", svc + "/ TransInConfirm", svc + "/ TransInCancel")

At this point, a complete TCC distributed transaction is written.

If you want to run a successful example in its entirety, follow the tcc example as described in the dtmcli-py-sample project

3. Rollback of TCC

What if the bank finds that the account of user 2 is abnormal and the return fails when the amount is ready to be transferred to user 2? We modify the code to simulate this:

@ app.post ("/ api/TransInTry") def trans_in_try (): # transaction and exception handling tcc_adjust_trading (c, in_uid, 30) return {"dtm_result": "FAILURE"}

This is the sequence diagram of the transaction failure interaction:

The difference between this and a successful TCC is that when a sub-transaction returns a failure, the global transaction is rolled back later, and the Cancel operation of each sub-transaction is called to ensure that all global transactions are rolled back.

4. Abnormal TCC network

All kinds of network anomalies may occur in TCC during the whole global transaction, such as empty rollback, idempotence and suspension. Because the exception of TCC is similar to the transaction mode such as SAGA and reliable messages, we explain all the exception solutions in the exception handling chapter of the seven classic solutions of distributed transactions in this article.

Thank you for reading, the above is the content of "how to use python to complete a distributed transaction TCC". After the study of this article, I believe you have a deeper understanding of how to use python to complete a distributed transaction TCC, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report