
Go语言分布式事务TCC模式实战1. TCC模式概述TCCTry-Confirm-Cancel是一种常用的分布式事务解决方案将业务逻辑拆分为三个阶段Try预留资源锁定事务Confirm确认执行使用预留资源Cancel取消执行释放预留资源2. TCC框架实现type TCCContext struct { TryTasks []TryTask ConfirmTasks []ConfirmTask CancelTasks []CancelTask } type TryTask func(ctx context.Context) error type ConfirmTask func(ctx context.Context) error type CancelTask func(ctx context.Context) error type TCCService struct { transactions map[string]*TCCContext mu sync.RWMutex } func (s *TCCService) Register(id string, try TryTask, confirm ConfirmTask, cancel CancelTask) { s.mu.Lock() defer s.mu.Unlock() s.transactions[id] TCCContext{ TryTasks: []TryTask{try}, ConfirmTasks: []ConfirmTask{confirm}, CancelTasks: []CancelTask{cancel}, } } func (s *TCCService) Execute(ctx context.Context, id string) error { s.mu.RLock() tx, ok : s.transactions[id] s.mu.RUnlock() if !ok { return errors.New(transaction not found) } for _, try : range tx.TryTasks { if err : try(ctx); err ! nil { s.rollback(ctx, tx) return err } } for _, confirm : range tx.ConfirmTasks { if err : confirm(ctx); err ! nil { s.rollback(ctx, tx) return err } } return nil } func (s *TCCService) rollback(ctx context.Context, tx *TCCContext) { for _, cancel : range tx.CancelTasks { cancel(ctx) } }3. 实战示例func Transfer(from, to string, amount int64) error { tccService : NewTCCService() tccService.Register(transfer, func(ctx context.Context) error { return FreezeAccount(ctx, from, amount) }, func(ctx context.Context) error { return ConfirmTransfer(ctx, from, to, amount) }, func(ctx context.Context) error { return UnfreezeAccount(ctx, from, amount) }, ) return tccService.Execute(context.Background(), transfer) }4. 总结TCC模式通过将分布式事务拆分为三个阶段结合业务层面的补偿逻辑实现了柔性事务的最终一致性。