如何在 Dubbo 接口注解一键开启 TCC 并指定 confirmMethod?

解读

国内互联网大厂在落地高并发账务、库存、营销等场景时,TCC(Try-Confirm-Cancel) 模式是分布式事务的主流选型。Dubbo 从 3.0 开始把 Seata 的 TCC 能力 通过注解方式原生接入,“一键开启” 指的是只用一个注解就能完成事务注册、资源登记、confirm/cancel 方法绑定,无需再手写 Seata 的 @TwoPhaseBusinessAction。面试官问“一键开启并指定 confirmMethod”,核心想验证两点:

  1. 你是否知道 Dubbo 侧注解的最新封装(不是 Seata 的老注解);
  2. 你是否清楚接口级别与实现级别的分工,以及方法签名约束。

知识点

  1. @DubboTCC(dubbo-tcc-api 模块)
    作用在接口方法上,属性:
    • confirmMethod:String,必填,对应实现类里的 confirm 方法名;
    • cancelMethod:String,必填;
    • useTCCFence:boolean,默认 true,开启幂等防悬挂;
    • timeout:long,默认 60 000 ms,覆盖全局事务超时。
  2. 方法约束
    Try/Confirm/Cancel 三方法必须同名+参数列表完全一致,且实现类里必须 public。
  3. 启动依赖
    引入 dubbo-tcc-spring-boot-starter(groupId=org.apache.dubbo,version≥3.2.0),Seata-all 会自动传递,无需额外 @EnableTCC。
  4. 事务上下文传递
    Dubbo 的 RpcContext 内部把 Seata 的 XID 透传到下游,业务代码零侵入。
  5. 注册中心要求
    必须开启 Seata-Server 1.6+,且 TC 地址在 application.yml 里通过 seata.tx-service-group 映射。

答案

在 Dubbo 接口方法上直接加 @DubboTCC 注解,把 confirmMethod 指向实现类里的确认方法即可,一行代码开启 TCC:

public interface StockService {
    @DubboTCC(confirmMethod = "confirmDeduct", cancelMethod = "cancelDeduct")
    boolean tryDeduct(Long skuId, Integer num);
}

实现类:

@DubboService
public class StockServiceImpl implements StockService {
    @Override
    public boolean tryDeduct(Long skuId, Integer num) {
        // 预留库存
        return true;
    }
    public boolean confirmDeduct(Long skuId, Integer num) {
        // 真正扣减
        return true;
    }
    public boolean cancelDeduct(Long skuId, Integer num) {
        // 释放预留
        return true;
    }
}

启动类无需加任何注解,只要依赖 dubbo-tcc-spring-boot-starter 即可自动装配。部署时保证 Seata-Server 已启动,业务库包含 undo_log 表,TCC 事务就一键生效。

拓展思考

  1. 接口多方法场景:每个方法都可以单独加 @DubboTCC,confirm/cancel 方法名可以不同,但建议保持“tryXxx → confirmXxx → cancelXxx”命名,方便运维一眼识别。
  2. 与 Spring Cloud 的互调:下游如果是 Spring Cloud 服务,只要同样引入 Seata 并暴露 REST 接口,Dubbo 侧 TCC 事务上下文通过 header 传递,Seata 的 RootContext 可自动解析,实现异构系统 TCC 联动。
  3. 性能调优:高并发大促时把 useTCCFence 设为 true 并给 tcc_fence_log 表建联合索引 (xid, branch_id),可把悬挂异常率压到 0.1% 以下;另外 confirmMethod 里建议异步化扣减 Redis 库存,再回写数据库,降低 RT 30% 以上。