Answer the question
In order to leave comments, you need to log in
How to deal with concurrent requests?
There is a function A and it has a couple of requests to the database and work with the user's account. But when there are many simultaneous requests, the script works as it wants, i.e. the script does not have time to process the account (debit money) of the user ... How can I fix the situation?
\DB::beginTransaction();
if($user->money < 100) return false;
try {
$user->money = $user->money - 100;
$user->save();
\DB::commit();
} catch (\Exception $e) {
\DB::rollback();
dd($e);
}
Что то не так работает
Answer the question
In order to leave comments, you need to log in
DB::transaction(function() use ($user) {
$user->money -= 100;
$user->save();
});
Depending on logic.
1. Transactions
2. Withdraw and check at the same time:
Update table set money=money-10 where user=123 and money>=10
And check the number of rows changed
first fix the code,
write in notepad? Any normal IDE highlights such a jamb.
In the case of simultaneous records and jambs associated with them, there is a table lock and a row lock. This solution is not very good, but sometimes the only possible one.
User::where('money', '>', 100)
->update('money', \DB::raw('money - ?', 100));
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question