PHP asynchronously requests API and rolls back directly after failure
淡淡烟草味
淡淡烟草味 2017-05-16 13:13:11
0
3
433

After PHP operates the DB, it will request the API interfaces of two other services. Now there is a question, if the request fails, how to roll back the DB? Methods other than rolling back the database

淡淡烟草味
淡淡烟草味

reply all(3)
Peter_Zhu

To put it bluntly, it is a programming problem. If it is based on transactions, it can be:

function save_if_success($transaction, $result)
{
    if ($result) $transaction->commit();
    else $transaction->rollback();
}
$db_ret = db();
save_if_success($transaction, api1($db_ret) && api2($db_ret));

The disadvantage is that it can only roll back the database

It is generally best to implement the undo logic yourself, which can undo both database operations and API operations. It is very convenient to use exceptions


function revoke_if_failed($do_func, $do_func_params, $revoke_callback, $revoke_params, $exception) {
    try
    {
        $do_func_ret = call_user_func_array($do_func, $do_func_params);
    }
    catch($exception $e)
    {
        call_user_func_array($revoke_callback, $revoke_params);
        throw;
    }
    return $do_func_ret;
}

try
{
    $dbret = db();
    $api1_ret = revoke_if_failed(api1, [$dbret], revoke_db, [$dbret], OperationFailedException::class);
    revoke_if_failed(api2, [$api1_ret], revoke_api1, [$api1_ret], OperationFailedException::class);
}
catch (OperationFailedException $e)
{
    return ERR;
}
return SUCCESS;

Can also be used in combination

淡淡烟草味

Isn’t DB just a database?
I have never encountered related questions, so I will take the liberty to answer:
Is it possible to generate a mark for each operation and put it in the cache (or various storage media). This has a validity period. If the next step is not executed after the validity period, it will be rolled back. (logical operation)

某草草

(@ο@) Wow~, it involves a problem of distributed things. Let’s see how the masters solve multiple RPCs

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template