Go微服务分布式事务SAGA模式与TCC实现 📅 发布时间:2026/8/22 12:49:23 👁 浏览次数: Go微服务分布式事务SAGA模式与TCC实现文章导语微服务架构下数据分布在多个数据库中传统的ACID事务不再适用。分布式事务的解决方案中SAGA和TCC是最常用的两种模式。本文在Go中实现这两种模式的核心逻辑。一、SAGA编排模式typeSagaStepstruct{Actionfunc(ctx context.Context)errorCompensatefunc(ctx context.Context)error}typeSagastruct{steps[]SagaStep log[]int// 已执行的步骤索引}func(s*Saga)Execute(ctx context.Context)error{fori,step:ranges.steps{iferr:step.Action(ctx);err!nil{// 执行补偿returns.compensate(ctx,i)}s.logappend(s.log,i)}returnnil}func(s*Saga)compensate(ctx context.Context,failedAtint)error{fori:failedAt-1;i0;i--{iferr:s.steps[i].Compensate(ctx);err!nil{log.Printf(补偿步骤%d失败: %v,i,err)}}returnfmt.Errorf(事务在步骤%d失败,failedAt)}// 使用saga:Saga{steps:[]SagaStep{{Action:createOrder,Compensate:cancelOrder},{Action:deductInventory,Compensate:restoreInventory},{Action:processPayment,Compensate:refundPayment},},}saga.Execute(ctx)二、TCC模式typeTCCServiceinterface{Try(ctx context.Context)errorConfirm(ctx context.Context)errorCancel(ctx context.Context)error}typeTCCCoordinatorstruct{services[]TCCService}func(c*TCCCoordinator)Execute(ctx context.Context)error{// Phase 1: Tryfor_,svc:rangec.services{iferr:svc.Try(ctx);err!nil{// 回滚已Try的服务c.cancel(ctx)returnerr}}// Phase 2: Confirmfor_,svc:rangec.services{iferr:svc.Confirm(ctx);err!nil{// Confirm失败需要重试或人工介入returnerr}}returnnil}三、全文总结SAGA适合长事务通过补偿实现最终一致性TCC适合资源预留场景Try-Confirm-Cancel三阶段分布式事务代价高优先考虑业务层面的最终一致性参考文献Hector Garcia-Molina - Sagas论文Seata分布式事务框架《微服务架构设计模式》