ByteTCC 源码分析 - 事务流程 - 基于Feign发起分支事务请求

245 阅读2分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第4天

TransactionInterceptor & TransactionAspectSupport

  1. 获取TransacationInfo(获取事务、封装事务状态、开启事务、链入事务链)
  2. 执行业务逻辑
  3. 事务正常处理/事务异常处理

CompensableFeignHandler & InvocationHandler 动态代理

装饰器模式

classDiagram
class CompensableFeignHandler
CompensableFeignHandler : +delegate InvocationHandler
InvocationHandler <|-- CompensableFeignHandler : 

beanRegistry.setLoadBalancerInterceptor()设置CompensableLoadBalancerInterceptor重构负载均衡算法。

CompensableFeignInterceptor & feign.RequestInterceptor

处理feign.RequestTemplate。增加或修改请求头信息。

在使用feign做服务间调用的时候,通过实现RequestInterceptor接口的apply方法,修改请求的头部或编码信息。feign在发送请求之前都会调用该接口的apply方法。

执行业务逻辑 - 通过Feign发起分支事务请求

bytetcc-supports-springcloud.xml -> 
bytetcc-supports-springcloud-core.xml -> 

CompensableCoordinatorController

POST /org/bytesoft/bytetcc/prepare/{xid} prepare
POST /org/bytesoft/bytetcc/commit/{xid}/{opc} commit
POST /org/bytesoft/bytetcc/rollback/{xid} rollback

GET /org/bytesoft/bytetcc/recover/{flag} recover
POST /org/bytesoft/bytetcc/forget/{xid} forget

Feign 负载均衡

按事务负载
按请求负载

请求流程

1. 主事务:CompensableHandlerInterceptor & org.springframework.web.servlet.HandlerInterceptor

实现HandlerInterceptor拦截器,重载preHandle、postHandle、afterCompletion。

preHandle获取请求头org.bytesoft.bytetcc.transaction不存在,说明不是事务请求。如果存在值的话,表明是作为子事务执行的。解析org.bytesoft.bytetcc.transaction的值,构造分布式事务上下文TransactionContext,配合主事务开启子事务。

org.bytesoft.bytetcc.transaction不存在直接返回true,不再继续执行逻辑。preHandle执行结束。

transactionText:代表分布式事务,处理获取一个二进制字节数组,通过工具方法的处理,可以从二进制字节数组反序列化出TransactionContext分布式事务上下文。

处理响应

2. 主事务:业务方法

3. 主事务:子事务 - feign - CompensableFeignHandler

增加负载均衡逻辑

4. 主事务:子事务 - feign - ReflectiveFeign.FeignInvocationHandler

5. 主事务:子事务 - feign - CompensableFeignInterceptor

通过Header传递org.bytesoft.bytetcc.transactionorg.bytesoft.bytetcc.propagation用于子事务需要的分布式事务上下文数据。

6. 子事务

通过请求header和响应header互相传递及同步分布式事务的上下文和信息