知识卡片
两阶段提交必须持久决议
2PC先要求参与者准备并承诺可提交,协调者根据全部准备结果形成持久决议,再反复通知完成。原书伪代码忽略prepare=false、缺持久决议与恢复状态,不能据此称已实现原子性;外部支付未支持准备协议时也不能被简单纳入。
这张卡片看不懂?
这张卡片的反馈已满 10 条,暂时无法继续提交。
已有反馈 · 0 / 10 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- Data Storage Strategies · 查看原书依据
To handle these complex scenarios, we implement a two-phase commit protocol. Following is how it works in practice: public class DistributedTransactionManager { public TransactionContext begin() { String txId = generateTransactionId(); // Phase 1: Prepare Map<String, ServiceStatus> serviceStatuses = new HashMap<>(); for (DistributedService service : participatingServices) { try { boolean prepared = service.prepare(txId); serviceStatuses.put(service.getName(), new ServiceStatus(prepared)); } catch (Exception e) { // If any service fails to prepare, abort the transaction rollback(txId, serviceStatuses); throw new TransactionPreparationException(e); } } // Phase 2: Commit boolean success = true; for (DistributedService service : participatingServices) { try { service.commit(txId); } catch (Exception e) { success = false; // Log the failure for manual recovery if needed logFailure(txId, service.getName(), e); } } if (!success) { // Initiate recovery process for partial commit initiateRecoveryProcess(txId, serviceStatuses); throw new TransactionCommitException(); } return new TransactionContext(txId); } } This implementation guards against partial failures.