两阶段提交和TCC模式的区别

阶段TCC

阶段 阶段阶段阶段阶段阶段阶段阶段会验状态阶段

TCC TCC阶段阶段阶段阶段阶段阶段阶段阶段会验状态阶段阶段阶段阶段

 

 

 

复制代码
两阶段提交java代码实现

//定义事务
public class Transaction {
    //记录事务状态
    private boolean isCommitted;
    //记录事务ID
    private int transactionId;
 
    public Transaction(int transactionId) {
        this.transactionId = transactionId;
        this.isCommitted = false;
    }
 
    //尝试预提交事务
    public boolean tryPreCommit() {
        //验证事务是否可以执行
        if (checkTransaction()) {
            //如果可以执行,则将事务状态标记为“预提交”
            isCommitted = true;
            return true;
        }
        return false;
    }
 
    //提交事务
    public boolean commit() {
        //如果事务状态为“预提交”,则执行提交操作
        if (isCommitted) {
            //执行提交
            //……
            return true;
        }
        return false;
    }
 
    //验证事务是否可以执行
    private boolean checkTransaction() {
        //根据transactionId查询数据库,验证事务是否可以执行
        //……
        return true;
    }
}

TCC模式java代码实现

//定义事务
public class Transaction {
    //记录事务状态
    private int status;
    //记录事务ID
    private int transactionId;
 
    public Transaction(int transactionId) {
        this.transactionId = transactionId;
        this.status = 0;
    }
 
    //尝试预提交事务
    public boolean tryPreCommit() {
        //验证事务是否可以执行
        if (checkTransaction()) {
            //如果可以执行,则将事务状态标记为“尝试”
            status = 1;
            return true;
        }
        return false;
    }
 
    //确认提交事务
    public boolean confirm() {
        //如果事务状态为“尝试”,则执行确认操作
        if (status == 1) {
            //执行确认
            //……
            return true;
        }
        return false;
    }
 
    //取消提交事务
    public boolean cancel() {
        //如果事务状态为“尝试”,则执行取消操作
        if (status == 1) {
            //执行取消
            //……
            return true;
        }
        return false;
    }
 
    //验证事务是否可以执行
    private boolean checkTransaction() {
        //根据transactionId查询数据库,验证事务是否可以执行
        //……
        return true;
    }
}
复制代码

 

 
posted @   八英里  阅读(606)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
历史上的今天:
2022-02-09 BeyondCompare4完美“破解“
点击右上角即可分享
微信分享提示