The following tutorial column of laravel will introduce to you several solutions to using laravel to solve inventory overflow. I hope it will be helpful to friends in need!
Database fields
/** * 错误示范 * Create by Peter Yang * 2021-06-08 10:57:59 * @return string */ function test1() { //商品id $id = request()->input('id'); $product = Product::where('id', $id)->firstOrFail(); if ($product->num decrement('num'); return "success"; }
Use go to simulate concurrency
package mainimport ( "fmt" "github.com/PeterYangs/tools/http" "sync")func main() { client := http.Client() wait := sync.WaitGroup{} for i := 0; i <p>View inventory in the database</p><p><img src="https://img.php.cn/upload/article/000/000/020/b3a44af246aab48e87b85467ea9f1568-1.png" alt="Detailed solution: Use laravel to solve the inventory overflow problem"><br><strong>The inventory has exceeded</strong></p><h2> <span class="header-link octicon octicon-link">##2.redis atomic lock</span><pre class="brush:php;toolbar:false"> /** * redis原子锁 * Create by Peter Yang * 2021-06-08 11:00:31 */ function test2() { //商品id $id = request()->input('id'); $lock = \Cache::lock("product_" . $id, 10); try { //最多等待5秒,5秒后未获取到锁,则抛出异常 $lock->block(5); $product = Product::where('id', $id)->firstOrFail(); if ($product->num decrement('num'); return 'success'; }catch (LockTimeoutException $e) { return '当前人数过多'; } finally { optional($lock)->release(); } }
Stock is normal
/** * mysql悲观锁 * Create by Peter Yang * 2021-06-08 11:00:47 */ function test3() { //商品id $id = request()->input('id'); try { \DB::beginTransaction(); $product = Product::where('id', $id)->lockForUpdate()->first(); if ($product->num decrement('num'); \DB::commit(); return "success"; } catch (\Exception $exception) { } }
##4.mysql optimistic lock
/** * mysql乐观锁 * Create by Peter Yang * 2021-06-08 11:00:47 */ function test4() { //商品id $id = request()->input('id'); $product = Product::where('id', $id)->first(); if ($product->num num]); if (!$res) { return '当前人数过多'; } return 'success'; }
Optimize optimistic lock
Modify the inventory sql to
\DB::update('UPDATE `product` SET num = num -1 WHERE id = ? AND num-1 >= 0', [$id]);
The above is the detailed content of Detailed solution: Use laravel to solve the inventory overflow problem. For more information, please follow other related articles on the PHP Chinese website!