【问题标题】:Getting the status of a transaction without callbacks in Ballerina在 Ballerina 中获取没有回调的交易状态
【发布时间】:2018-05-07 16:08:41
【问题描述】:

在 Ballerina 中,我们可以在我们提供的“onCommit”和“onAbort”函数中识别交易是否成功。但这使我们脱离了当前的方法。

我希望能够在同一方法中的事务之后的下一行中验证事务是成功还是失败。在我的场景中,我也不能使用全局变量来共享状态。我可以想到一些变通方法,例如在函数内部使用布尔值,但在事务外部使用。

boolean status=true;
transaction with retries = 4, oncommit = onCommitFunction, onabort = onAbortFunction {
    status = true;
    // any sql statement/s here
    var result = client->update("INSERT ....");
   match result {
            int c => {
                io:println("Inserted count: " + c);
                if (c == 0) {
                    status = false;
                    abort;
                }
            }
            error err => {
                status = false;
                retry;
            }
    }
}
// Here I want to know whether the transaction was a success or a failure
if(status) {
    // success action
} else {
    // Failed action
}

有没有更好更干净的方式让我在如上交易后立即知道交易是否成功?

提前致谢。

【问题讨论】:

    标签: transactions ballerina


    【解决方案1】:

    获取 Ballerina 交易状态的唯一方法是通过注册的回调函数。为什么您需要在交易后立即拥有它?您可以在注册的处理程序函数中实现相同的功能。拥有一个布尔变量是不正确的,因为它没有捕获准备或提交/中止阶段的失败。

    如果你想保存一些交易相关的信息,你可以使用当前的交易id,回调函数将被调用。

    transaction with retries = 4, oncommit = commitFunction, onabort = abortFunction {
        string txId = transactions:getCurrentTransactionId();
        //Store any information you need to access later using the txId - may be in a global map.
    } onretry {
        //Get called before retrying
    }
    
    function commitFunction(string transactionid) {
        //Retrive the saved information using the transactionid. 
    }
    
    function abortFunction(string transactionid) {
        //Retrive the saved information using the transactionid. 
    }
    

    【讨论】:

    • oncommit 函数是否与初始方法在同一个线程中运行?可以在这个 oncommit 方法中运行其他事务吗?因为在我的场景中,下一个事务取决于前一个。
    • 不要在这些处理程序方法中使用事务。将来我们将添加编译时检查以避免处理函数中的事务,因为它会导致复杂的事务块。如果第二个事务依赖于前一个事务,那么两者中的这些操作不应该属于一个事务吗?
    【解决方案2】:

    请检查以下代码是否对您有帮助!

    transaction with retries = 4, oncommit = onCommitFunction, onabort = onAbortFunction {
        // any sql statement/s here
        int result = client->insert("INSERT ....") but {error => -1};
        if (result < 0) {
            retry;
        } else if (resilt == 0) {
            abort;
        } else {
            // success action
        }
    }
    

    但是,如果您想在方法之外拥有事务的状态,那么我相信您必须在上述方法之外拥有一个布尔变量。

    【讨论】:

    • 我真正想要的是知道事务是否已经提交。因为,AFAIK,事务只有在提交后才能成功。但是在这种模式下,可能会有个别查询成功的情况(我在这种情况下删除/更新了数千条记录),但最终在提交时发生错误(网络错误)。在这种情况下,我们如何确定交易是否成功?或不?正如我所见,这种方法不会那样做。
    猜你喜欢
    • 2013-11-27
    • 1970-01-01
    • 2018-10-03
    • 1970-01-01
    • 1970-01-01
    • 2021-10-16
    • 1970-01-01
    • 2022-12-14
    • 2018-02-26
    相关资源
    最近更新 更多