跨多个微服务的2PC分布式事务?

7

我阅读了关于2PC/XA分布式事务的一些信息,并且了解到JTA对其提供了支持。看起来有许多资源管理器(RM)(例如RDBMS或JMS),而一个 TransactionManager (TM) 实例可以跨多个 RM 管理全局事务。 TM <-> RM communication

我知道使用Saga模式会更好,但思考以下问题仍然很有趣:

  1. 2PC/XA分布式事务是否使得在一个应用程序和一个 TM 中只能从许多 RM 执行事务成为可能?
  2. 如果不行-如何使用2PC/XA分布式事务在许多微服务之间实现,以便在每个微服务仅访问自己的数据库的情况下使用2PC?我很高兴看到一个例子
  3. 我们需要将TransactionManager作为单独的微服务来提供在许多微服务之间提供 2PC 吗?

更新: 在JTA中TransactionManager 不提供REST API来管理跨微服务的事务。 LIXA 提供了这个功能。此文带有例子,可以作为回答的补充 :)


你是什么意思,"many RM's only from one service and one TM"? - WebServer
我对2PC/XA的理解是:如果我们有一个单体应用程序,具有两个不同的数据库连接 - 我清楚如何使用TransactionManager,它将成为此应用程序的一部分,因此我们可以委托将分布式事务管理跨多个数据库/JMS系统到TransactionManager。但是,我无法想象如何在使用每个服务模式的数据库的不同微服务之间管理多个数据库,而每个服务仅访问其DB。在这种情况下如何进行2PC/XA分布式事务? - Dmitriy Mishenyov
1个回答

10
在微服务中,事务需要通过公开准备和提交API来完成。还需要一个事务管理器来协调事务。
例如,假设有两个不同的银行,需要将Bank1的Account_A中的100美元转账到Bank2的Account_B中。此外,假设中央银行机构负责完成交易,则2PC的工作方式如下:
  1. Central banking authority(Transaction Manager) will receive request to transfer $100 from Account_A from Bank1 to Account_B from Bank2.

    a. https://CentralBank/Transaction?from=Bank1-Account_A&to=Bank2-Account_B&amount=100
    
  2. Central Bank will save this into its transaction database with some transaction Id = 123. Also it will return transaction id to call, so that at later point it can call to get status of transaction.

    a. add transaction 123 in database with status open
    
  3. PREPARE PHASE Transaction Manager will issue following RPC commands:

    a. https://Bank1/Prepare?Account=Account_A&money=100&action=subtract&transactionid=123
    b. https://Bank2/Prepare?Account=Account_B&money=100&action=add&transactionid=123
    
  4. COMMIT PHASE Once it gets successful response for both the calls in Prepare phase, then it moves to Commit phase where it issues following commands:

    a. move transaction 123 to committed state
    b. https://Bank1/Commit?transactionid=123
    c. https://Bank2/Commit?transactionid=123
    
  5. Once it gets successful response for both the calls in commit phase, central bank can move transaction to Completed state(optional)

  6. If any of the step from PREPARE or COMMIT phase fails then Transaction coordinator aborts the transaction by issuing following commands:

    a. move transaction 123 to Failed state
    b. https://Bank1/Rollback?transactionid=123
    c. https://Bank2/Rollback?transactionid=123
    

上述问题是分布式原子提交的一种形式,而2PC是其中一种方式。需要注意的是,2PC存在许多缺点,例如如果在准备阶段中央银行崩溃怎么办?还有如果4.c步骤失败但4.b成功等情况。讨论这些问题本身就是一个非常广泛的研究领域,但仍然需要注意这些问题。尽管有许多缺点,但由于其简单性,2PC被广泛使用。


我们是否需要将TransactionManager服务作为单独的微服务来提供多个微服务之间的2PC呢?

从理论上讲不需要。如果您仔细观察任何一个银行(Bank1或Bank2),它也可以作为事务管理员(只需一个单独的数据库表Transaction),但在实际应用中,通常会作为单独的微服务。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接