20K面试高频追问与企业级实战经验 - 一、分布式事务(面试必问TOP3)
本文是 20K面试高频追问与企业级实战经验 的分章阅读版。
一、分布式事务(面试必问TOP3)
Seata四大模式对比
| 模式 | 原理 | 侵入性 | 性能 | 适用场景 |
| AT | 自动反向SQL(undo_log) + 全局锁 | 零侵入(@GlobalTransactional) | 高 | 大多数业务 |
| TCC | Try/Confirm/Cancel三阶段 | 高侵入 | 最高 | 资金类场景 |
| SAGA | 长事务编排+补偿 | 中等 | 中 | 跨企业长流程 |
| XA | 数据库2PC | 零侵入 | 最低 | 性能不敏感 |
Seata AT工作流程
TC(协调者) + TM(事务管理器) + RM(资源管理器) 三角色:
TM(Order) TC(Seata Server) RM(Inventory)
│ │ │
│ ①申请全局XID │ │
│──────────────────────────→│ │
│←───── XID:192.168.1.1:8091:123456789 ──────────────│
│ │ │
│ ②执行本地SQL+注册分支 │ │
│──────────────────────────→│ │
│ before-image→after-image │ │
│ →undo_log │ │
│ │ │
│ ③远程调用Inventory扣减 │ │
│──────────────────────────────────────────────────────→│
│ │ ④Inventory RM注册分支 │
│ │←─────────────────────────│
│ │ before/after image │
│ │ →undo_log │
│ │ │
│ ⑤全局Commit/Rollback │ │
│──────────────────────────→│ │
│ │ 异步删undo_log(提交) │
│ │ 或读undo_log反向补偿(回滚) │
Seata TCC三大难题(22K追问必考)
// 空回滚 + 悬挂 + 幂等性 统一解决方案
public class InventoryTccActionImpl implements InventoryTccAction {
// 统一用事务控制表解决三个问题
// tcc_transaction_log: {xid, branch_id, status, create_time}
@Override
@TwoPhaseBusinessAction(name = "deductStock",
commitMethod = "confirm", rollbackMethod = "cancel")
public boolean tryDeduct(BusinessActionContext ctx, String sku, int qty) {
String xid = ctx.getXid();
// 防悬挂: 检查是否已经Cancel
if (tccLogDao.existsByXidAndStatus(xid, "cancelled")) {
return false; // Cancel已执行,Try不再执行
}
// 幂等: 检查是否已经Try过
if (tccLogDao.existsByXid(xid)) {
return true; // 已执行过,直接返回
}
// 业务: 冻结库存
inventoryDao.freezeStock(sku, qty);
// 记录Try状态
tccLogDao.insert(xid, ctx.getBranchId(), "trying");
return true;
}
@Override
public boolean confirm(BusinessActionContext ctx) {
String xid = ctx.getXid();
// 幂等: 已confirm则直接返回
if (tccLogDao.isStatus(xid, "confirmed")) return true;
// 确认扣减: 冻结→实际扣减
inventoryDao.confirmDeduct(ctx.getActionContext("sku").toString(),
Integer.parseInt(ctx.getActionContext("qty").toString()));
tccLogDao.updateStatus(xid, "confirmed");
return true;
}
@Override
public boolean cancel(BusinessActionContext ctx) {
String xid = ctx.getXid();
// 幂等: 已cancel则直接返回
if (tccLogDao.isStatus(xid, "cancelled")) return true;
// 空回滚: Try未执行,直接记录cancel状态
if (!tccLogDao.existsByXid(xid)) {
tccLogDao.insert(xid, ctx.getBranchId(), "cancelled");
return true;
}
// 释放冻结库存
inventoryDao.unfreezeStock(ctx.getActionContext("sku").toString(),
Integer.parseInt(ctx.getActionContext("qty").toString()));
tccLogDao.updateStatus(xid, "cancelled");
return true;
}
}
分布式事务选型决策
面试追问: "你们项目用哪种分布式事务?"
决策树:
是否涉及资金? ──是→ TCC(强一致+高性能)
└──否→ 是否跨多个数据库?
├──是→ Seata AT(零侵入+自动补偿)
└──否→ 本地消息表(最终一致+简单可靠)
跨企业长流程? → SAGA(补偿机制+长事务)
已有MQ基础设施? → 可靠消息最终一致性(Transactional Outbox)
面试话术:"我们订单→库存→支付用Seata AT模式(零侵入+自动undo)。
资金转账用TCC(需要冻结/确认/取消的精确控制)。
跨企业API调用用SAGA+补偿(长流程+对方系统不可控)。"
undo_log边界case
- undo_log存什么:before-image(修改前) + after-image(修改后) + xid + branchId
- after-image与当前数据不一致 → 脏写检测 → 抛异常需人工介入
- 全局锁机制:TC维护,本地事务提交前需获取全局锁防脏写
相关页面