两阶段提交和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 @ 2023-02-09 21:48  八英里  阅读(375)  评论(0编辑  收藏  举报