jeudi 21 mars 2019

Laravel lockForUpdate + Transaction

We're using lockForUpdate like this:

DB::beginTransaction();

try {
    UserBalance::where('user_id', 2)
                    ->lockForUpdate()
                    ->first();
    $balance->usd += 100;
    $balance->save();
} catch (\Exception $e) {
    DB::rollback();
    return json_encode ([
        'success' => false,
        'message' => 'error',
    ]);
}
DB::commit();

Everything ok, i tried with some "sleep(20)" before the commit and sent another requisition (without the sleep) and the row is really locked, but we're facing a problem. When we run this from a cron multiple times, it seems that the function run on the exactly same millisecond, then the lock doesn't seems to work, is this possible? Is there any other solution instead of using a queue?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire