search

Home  >  Q&A  >  body text

PHP asynchronously requests API and rolls back directly after failure

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

淡淡烟草味淡淡烟草味2792 days ago451

reply all(3)I'll reply

  • 天蓬老师

    天蓬老师2017-05-16 13:15:11

    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

    reply
    0
  • 淡淡烟草味

    淡淡烟草味2017-05-16 13:15:11

    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)

    reply
    0
  • 某草草

    某草草2017-05-16 13:15:11

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

    reply
    0
  • Cancelreply