(Rpm) for the first time was the "distributed transaction" is about as simple and clear

I do not know if you encounter such a situation, to buy a small shop selling things, paid the money, but because the owner deal with a number of other things, actually forget you pay, you are called to re-pay.

Author: caffe latte Source: coffee latte micro-channel public number | 2018-08-14 09:28

 

Or online shopping has been charged obviously, but I did not tell the transaction. This series of cases are caused because there is no transaction. This illustrates the importance of some of the matters in life.

With the transaction, you go to buy a small shop selling things, and that is cold number-crunching. With the transaction, you go shopping online, which produce orders for debit transactions.

Specific definition affairs

All operations in the transaction to provide a mechanism for an activity according to an indivisible into the execution unit, a transaction consisting of all the operations only in the case where in order to submit all normal operations can be performed, as long as either operation fails, will lead to a rollback of the entire transaction.

Simply put, the transaction provides an "either do nothing, or do a full (All or Nothing)" mechanism.

Local transaction database

ACID

When it comes to database transaction would have to say that the four ACID properties of database transactions:

A: atomicity (Atomicity), all operations in one transaction (transaction) is either completed or not completed all, does not end in the middle of a link.

Transaction error occurs during execution, it will be rolled back (Rollback) to the state before the start of the transaction, as the transaction never performed the same.

Like you to buy something or pay receipt together are executed or unable to pronounce the goods, money back.

C: Consistency (Consistency), the consistency of the transaction refers to a transaction executed before and after the implementation of the database must be in a consistent state.

If the transaction is successfully completed, the system will correctly apply all changes, the system is active.

If an error occurs in a transaction, all changes in the system will automatically roll back, the system returns to its original state.

I: Isolation (Isolation), refers to the concurrent environment, when different transactions while manipulating the same data, each transaction has its own full data space.

Modifications made by concurrent transactions must modify the isolation to do with any other concurrent transactions. When viewing the transaction data is updated state data which is either state before another transaction modifies it, either state after another transaction modifies it, the transaction will not see an intermediate state of the data.

Figuratively, you buy things that matter, does not affect other people.

D: Persistent (Durability), refers to the end as long as the transaction is successful, it updates to the data must be preserved ***.

Even if a system crash occurs, restart the database system, the database can be restored to the state of affairs when a successful conclusion.

An analogy, when you buy something needs to be recorded on the books, even if the boss forget that there are well documented.

The principle InnoDB

InnoDB is a MySQL storage engine, most people are more familiar with MySQL, briefly we outline some of the basic principles of database transactions to achieve.

In local affairs, services and resources in the affairs of the package can be seen as a whole, as shown below:

 

Our local transaction is managed by the resource manager:

 

The ACID transactions is guaranteed by InnoDB logs and locks. Transaction isolation is achieved through the mechanism of database locks, durability by Redo Log (redo logs) to achieve, atomic and consistency is achieved by Undo Log.

Undo Log principle is simple, in order to satisfy transaction atomicity, any data before the operation, the first backup data to a place (where the backup data is stored is referred to Undo Log). Then modifying the data.

If an error or a user performs a Rollback statement, the system can use the backup Undo Log in to restore the data to its state before the transaction began.

Undo and contrary Log, Redo Log record new data is backed up. Before a transaction is committed, as long as the Redo Log persistence, you do not need the data persistence.

When the system crashes, although the data are not persistent, but Redo Log has persisted. The system can be based on the content Redo Log in to restore all data to the state ***. Interested in the specific implementation process students can go to their own search for expansion.

Distributed Transaction

What is Distributed Transaction

Distributed Transaction participants of the transaction, transactional servers, server and transaction manager resource are located on different nodes of different distributed systems.

简单的说,就是一次大的操作由不同的小操作组成,这些小的操作分布在不同的服务器上,且属于不同的应用,分布式事务需要保证这些小操作要么全部成功,要么全部失败。

本质上来说,分布式事务就是为了保证不同数据库的数据一致性。

分布式事务产生的原因

从上面本地事务来看,我们可以分为两块:

  • Service 产生多个节点
  • Resource 产生多个节点

Service 多个节点

随着互联网快速发展,微服务,SOA 等服务架构模式正在被大规模的使用。

举个简单的例子,一个公司之内,用户的资产可能分为好多个部分,比如余额,积分,优惠券等等。

在公司内部有可能积分功能由一个微服务团队维护,优惠券又是另外的团队维护。

 

 

这样的话就无法保证积分扣减了之后,优惠券能否扣减成功。

Resource多个节点

同样的,互联网发展得太快了,我们的 MySQL 一般来说装***的数据就得进行分库分表。

对于一个支付宝的转账业务来说,你给朋友转钱,有可能你的数据库是在北京,而你的朋友的钱是存在上海,所以我们依然无法保证他们能同时成功。

分布式事务的基础

从上面来看分布式事务是随着互联网高速发展应运而生的,这是一个必然。

我们之前说过数据库的 ACID 四大特性,已经无法满足我们分布式事务,这个时候又有一些新的大佬提出一些新的理论。

CAP

CAP 定理,又被叫作布鲁尔定理。对于设计分布式系统(不仅仅是分布式事务)的架构师来说,CAP 就是你的入门理论。

C (一致性):对某个指定的客户端来说,读操作能返回***的写操作。

对于数据分布在不同节点上的数据来说,如果在某个节点更新了数据,那么在其他节点如果都能读取到这个***的数据,那么就称为强一致,如果有某个节点没有读取到,那就是分布式不一致。

A (可用性):非故障的节点在合理的时间内返回合理的响应(不是错误和超时的响应)。可用性的两个关键一个是合理的时间,一个是合理的响应。

合理的时间指的是请求不能***被阻塞,应该在合理的时间给出返回。合理的响应指的是系统应该明确返回结果并且结果是正确的,这里的正确指的是比如应该返回 50,而不是返回 40。

P (分区容错性):当出现网络分区后,系统能够继续工作。打个比方,这里集群有多台机器,有台机器网络出现了问题,但是这个集群仍然可以正常工作。

熟悉 CAP 的人都知道,三者不能共有,如果感兴趣可以搜索 CAP 的证明,在分布式系统中,网络无法 100% 可靠,分区其实是一个必然现象。

如果我们选择了 CA 而放弃了 P,那么当发生分区现象时,为了保证一致性,这个时候必须拒绝请求,但是 A 又不允许,所以分布式系统理论上不可能选择 CA 架构,只能选择 CP 或者 AP 架构。

对于 CP 来说,放弃可用性,追求一致性和分区容错性,我们的 ZooKeeper 其实就是追求的强一致。

对于 AP 来说,放弃一致性(这里说的一致性是强一致性),追求分区容错性和可用性,这是很多分布式系统设计时的选择,后面的 BASE 也是根据 AP 来扩展。

顺便一提,CAP 理论中是忽略网络延迟,也就是当事务提交时,从节点 A 复制到节点 B 没有延迟,但是在现实中这个是明显不可能的,所以总会有一定的时间是不一致。

同时 CAP 中选择两个,比如你选择了 CP,并不是叫你放弃 A。因为 P 出现的概率实在是太小了,大部分的时间你仍然需要保证 CA。

就算分区出现了你也要为后来的 A 做准备,比如通过一些日志的手段,是其他机器回复至可用。

BASE

BASE 是 Basically Available(基本可用)、Soft state(软状态)和 Eventually consistent (最终一致性)三个短语的缩写,是对 CAP 中 AP 的一个扩展。

基本可用:分布式系统在出现故障时,允许损失部分可用功能,保证核心功能可用。

软状态:允许系统中存在中间状态,这个状态不影响系统可用性,这里指的是 CAP 中的不一致。

最终一致:最终一致是指经过一段时间后,所有节点数据都将会达到一致。

BASE 解决了 CAP 中理论没有网络延迟,在 BASE 中用软状态和最终一致,保证了延迟后的一致性。

BASE 和 ACID 是相反的,它完全不同于 ACID 的强一致性模型,而是通过牺牲强一致性来获得可用性,并允许数据在一段时间内是不一致的,但最终达到一致状态。

分布式事务解决方案

有了上面的理论基础后,这里开始介绍几种常见的分布式事务的解决方案。

是否真的要分布式事务

在说方案之前,首先你一定要明确你是否真的需要分布式事务?

上面说过出现分布式事务的两个原因,其中有个原因是因为微服务过多。我见过太多团队一个人维护几个微服务,太多团队过度设计,搞得所有人疲劳不堪。

而微服务过多就会引出分布式事务,这个时候我不会建议你去采用下面任何一种方案,而是请把需要事务的微服务聚合成一个单机服务,使用数据库的本地事务。

因为不论任何一种方案都会增加你系统的复杂度,这样的成本实在是太高了,千万不要因为追求某些设计,而引入不必要的成本和复杂度。

如果你确定需要引入分布式事务可以看看下面几种常见的方案。

2PC

说到 2PC 就不得不聊数据库分布式事务中的 XA Transactions。

 

在 XA 协议中分为两阶段:

  • 事务管理器要求每个涉及到事务的数据库预提交(precommit)此操作,并反映是否可以提交。
  • 事务协调器要求每个数据库提交数据,或者回滚数据。

优点:

  • 尽量保证了数据的强一致,实现成本较低,在各大主流数据库都有自己实现,对于 MySQL 是从 5.5 开始支持。

缺点:

  • 单点问题:事务管理器在整个流程中扮演的角色很关键,如果其宕机,比如在***阶段已经完成,在第二阶段正准备提交的时候事务管理器宕机,资源管理器就会一直阻塞,导致数据库无法使用。
  • 同步阻塞:在准备就绪之后,资源管理器中的资源一直处于阻塞,直到提交完成,释放资源。
  • 数据不一致:两阶段提交协议虽然为分布式数据强一致性所设计,但仍然存在数据不一致性的可能。

比如在第二阶段中,假设协调者发出了事务 Commit 的通知,但是因为网络问题该通知仅被一部分参与者所收到并执行了 Commit 操作,其余的参与者则因为没有收到通知一直处于阻塞状态,这时候就产生了数据的不一致性。

总的来说,XA 协议比较简单,成本较低,但是其单点问题,以及不能支持高并发(由于同步阻塞)依然是其***的弱点。

TCC

关于 TCC(Try-Confirm-Cancel)的概念,最早是由 Pat Helland 于 2007 年发表的一篇名为《Life beyond Distributed Transactions:an Apostate’s Opinion》的论文提出。

TCC 事务机制相比于上面介绍的 XA,解决了如下几个缺点:

  • 解决了协调者单点,由主业务方发起并完成这个业务活动。业务活动管理器也变成多点,引入集群。
  • 同步阻塞:引入超时,超时后进行补偿,并且不会锁定整个资源,将资源转换为业务逻辑形式,粒度变小。
  • 数据一致性,有了补偿机制之后,由业务活动管理器控制一致性。

 

对于 TCC 的解释:

  • Try 阶段:尝试执行,完成所有业务检查(一致性),预留必需业务资源(准隔离性)。
  • Confirm 阶段:确认真正执行业务,不作任何业务检查,只使用 Try 阶段预留的业务资源,Confirm 操作满足幂等性。要求具备幂等设计,Confirm 失败后需要进行重试。
  • Cancel 阶段:取消执行,释放 Try 阶段预留的业务资源,Cancel 操作满足幂等性。Cancel 阶段的异常和 Confirm 阶段异常处理方案基本上一致。

举个简单的例子:如果你用 100 元买了一瓶水, Try 阶段:你需要向你的钱包检查是否够 100 元并锁住这 100 元,水也是一样的。

如果有一个失败,则进行 Cancel(释放这 100 元和这一瓶水),如果 Cancel 失败不论什么失败都进行重试 Cancel,所以需要保持幂等。

如果都成功,则进行 Confirm,确认这 100 元被扣,和这一瓶水被卖,如果 Confirm 失败无论什么失败则重试(会依靠活动日志进行重试)。

对于 TCC 来说适合一些:

  • 强隔离性,严格一致性要求的活动业务。
  • 执行时间较短的业务。

实现参考:https://github.com/liuyangming/ByteTCC/。

本地消息表

本地消息表这个方案最初是 eBay 提出的,eBay 的完整方案 https://queue.acm.org/detail.cfm?id=1394128。

此方案的核心是将需要分布式处理的任务通过消息日志的方式来异步执行。消息日志可以存储到本地文本、数据库或消息队列,再通过业务规则自动或人工发起重试。

人工重试更多的是应用于支付场景,通过对账系统对事后问题的处理。

 

对于本地消息队列来说核心是把大事务转变为小事务。还是举上面用 100 元去买一瓶水的例子。

1. 当你扣钱的时候,你需要在你扣钱的服务器上新增加一个本地消息表,你需要把你扣钱和减去水的库存写入到本地消息表,放入同一个事务(依靠数据库本地事务保证一致性)。

2. 这个时候有个定时任务去轮询这个本地事务表,把没有发送的消息,扔给商品库存服务器,叫它减去水的库存,到达商品服务器之后,这时得先写入这个服务器的事务表,然后进行扣减,扣减成功后,更新事务表中的状态。

3. 商品服务器通过定时任务扫描消息表或者直接通知扣钱服务器,扣钱服务器在本地消息表进行状态更新。

4. 针对一些异常情况,定时扫描未成功处理的消息,进行重新发送,在商品服务器接到消息之后,首先判断是否是重复的。

如果已经接收,再判断是否执行,如果执行在马上又进行通知事务;如果未执行,需要重新执行由业务保证幂等,也就是不会多扣一瓶水。

本地消息队列是 BASE 理论,是最终一致模型,适用于对一致性要求不高的情况。实现这个模型时需要注意重试的幂等。

MQ 事务

在 RocketMQ 中实现了分布式事务,实际上是对本地消息表的一个封装,将本地消息表移动到了 MQ 内部。

下面简单介绍一下MQ事务,如果想对其详细了解可以参考:https://www.jianshu.com/p/453c6e7ff81c。

基本流程如下:

  • ***阶段 Prepared 消息,会拿到消息的地址。
  • 第二阶段执行本地事务。
  • 第三阶段通过***阶段拿到的地址去访问消息,并修改状态。消息接受者就能使用这个消息。

如果确认消息失败,在 RocketMQ Broker 中提供了定时扫描没有更新状态的消息。

如果有消息没有得到确认,会向消息发送者发送消息,来判断是否提交,在 RocketMQ 中是以 Listener 的形式给发送者,用来处理。

如果消费超时,则需要一直重试,消息接收端需要保证幂等。如果消息消费失败,这时就需要人工进行处理,因为这个概率较低,如果为了这种小概率时间而设计这个复杂的流程反而得不偿失。

Saga 事务

Saga 是 30 年前一篇数据库伦理提到的一个概念。其核心思想是将长事务拆分为多个本地短事务,由 Saga 事务协调器协调,如果正常结束那就正常完成,如果某个步骤失败,则根据相反顺序一次调用补偿操作。

Saga 的组成:每个 Saga 由一系列 sub-transaction Ti 组成,每个 Ti 都有对应的补偿动作 Ci,补偿动作用于撤销 Ti 造成的结果。这里的每个 T,都是一个本地事务。

可以看到,和 TCC 相比,Saga 没有“预留 try”动作,它的 Ti 就是直接提交到库。

Saga 的执行顺序有两种:

  • T1,T2,T3,...,Tn。
  • T1,T2,...,Tj,Cj,...,C2,C1,其中 0 < j < n 。

Saga 定义了两种恢复策略:

  • 向后恢复,即上面提到的第二种执行顺序,其中 j 是发生错误的 sub-transaction,这种做法的效果是撤销掉之前所有成功的 sub-transation,使得整个 Saga 的执行结果撤销。
  • Forward recovery for a scene to be successful, the execution order is like this: T1, T2, ..., Tj (failure), Tj (retry), ..., Tn of, where j is an error the sub-transaction. In this case it does not need to Ci.

Here we must note that there is no guarantee isolation in Saga mode, because there is no lock resource, other transactions can still cover or affect the current transaction.

Or example take 100 yuan to buy a bottle of water, here is the definition:

  • T1 = 100 yuan buckle, T2 = the user to add a bottle of water, T3 = Save stock bottle of water.
  • C1 = plus 100 yuan, C2 = Save the user to a bottle of water, C3 = a bottle of water was added to the stock.

We performed a T1, T2, T3 if a problem occurs, it performs the reverse operation C problem occurs.

The above mentioned problems can occur in isolation, if you do need to roll back this time T3, but the user has to drink the (separate transaction), the rollback will find the time, the user can not be reduced to a a bottle of water.

This is not a problem of isolation between transactions. Saga can see patterns or no effect on the isolation of large, you can refer to Huawei's solution: from the operational level to start adding a Session and lock mechanisms to ensure that resources can serialize operation.

This isolation can also be part of the resources by way of pre-freezing of funds at the operational level, *** can be obtained by reading the current state timely manner to update *** in the course of business operations. (Specific example: reference may Huawei Service Comb)

***

Again, I would not be able to do a distributed transaction, If you have to use it, in conjunction with their business analysis and see for yourself what kind of business is suitable, is strongly consistent care, or eventually agreed to.

*** In summary of some of the problems, you can find the answer themselves down from the article:

  • ACID CAP and the CA is the same as you?
  • What are the advantages and disadvantages of commonly used solutions for distributed transactions? What works best?
  • The reason distributed transactions occur? What used to address pain points?

Guess you like

Origin www.cnblogs.com/zhimingxin/p/11246089.html