分布式事务Saga(三)事务参与方管理SagaParticipantAspect

分布式事务Saga (一) TCC vs Saga
分布式事务Saga(二)事务管理者SagaTransactionalAspect
分布式事务Saga(三)事务参与方管理SagaParticipantAspect
分布式事务Saga(四)事务恢复SagaRecoveryManager

项目地址:https://github.com/yangxb2010000/saga

回到PaymentServiceImpl的makePayment方法,方法体比较好理解,重点看下accountClient、inventoryClient的定义
分布式事务Saga(三)事务参与方管理SagaParticipantAspect
AccountClient.payment是spring-cloud的rpc调用,在接口定义上添加了@SagaParticipative注解,该注解可以实现把当前rpc操作作为事务参与方添加到事务中
分布式事务Saga(三)事务参与方管理SagaParticipantAspect
@SagaParticipative注解的拦截代码实现
分布式事务Saga(三)事务参与方管理SagaParticipantAspect
SagaParticipativeInterceptor负责具体的拦截工作,核心逻辑就是构建Participant,并添加到当前事务中
分布式事务Saga(三)事务参与方管理SagaParticipantAspect
分布式事务Saga(三)事务参与方管理SagaParticipantAspect

基于上述SagaTransactionalAspect和SagaParticipativeAspect拦截器的实现,就保证了所有事务参与方的操作和回滚操作都被持久化存储了,无论任何时刻系统宕机,都可以基于持久化的日志对事务进行回滚操作,保证数据的最终一致性

事务回滚

其实上一篇已经说过事务的提交和回滚逻辑了,这个地方再回过头来看下,如果任何一个事务参与方返回失败,如何实现事务的回滚操作,可以看下PaymentServiceImpl中的mockPaymentInventoryWithException方法

分布式事务Saga(三)事务参与方管理SagaParticipantAspect

上图中位置会抛出异常,异常会被
SagaTransactionalInterceptor.interceptor捕获到,该位置会执行事务的回滚逻辑

分布式事务Saga(三)事务参与方管理SagaParticipantAspect

上图中的回滚操作最终会调用每一个已执行的参与方的cancel方法,看下具体调用实现

分布式事务Saga(三)事务参与方管理SagaParticipantAspect