Home > Article > Backend Development > mysql - php concurrency processing?
I want to make a third-party payment interface, but I am worried that there may be concurrency in placing orders.
<code><?php $fp = fopen('test.txt', 'r'); $try = 10; do{ $lock = flock($fp,LOCK_EX);//独占锁 //没有获得锁释放cpu重新获取 if(!lock){ usleep(50000); //0.05 } }while(!$lock && --$try > 0); if($lock){ /***********拿到锁的用户执行********/ //在这里生成订单号,写入数据库, 跳转到支付页面..... flock($fp,LOCK_UN); fclose($fp); }else{ fclose($fp); die("系统繁忙,稍后再试"); }</code>
I found the above code from the Internet and modified it. I always feel that it is a bit weak. I don’t know if it will work or if you have any better suggestions?
I want to make a third-party payment interface, but I am worried that there may be concurrency in placing orders.
<code><?php $fp = fopen('test.txt', 'r'); $try = 10; do{ $lock = flock($fp,LOCK_EX);//独占锁 //没有获得锁释放cpu重新获取 if(!lock){ usleep(50000); //0.05 } }while(!$lock && --$try > 0); if($lock){ /***********拿到锁的用户执行********/ //在这里生成订单号,写入数据库, 跳转到支付页面..... flock($fp,LOCK_UN); fclose($fp); }else{ fclose($fp); die("系统繁忙,稍后再试"); }</code>
I found the above code from the Internet and modified it. I always feel that it is a bit weak. I don’t know if it will work or if you have any better suggestions?
You can use redis's atomic row operation to implement locking and set a key as a mark.
You can use nmq to do it.
The poster adds an exclusive lock through a file. Does it mean that every order is generated, the lock is obtained first, and then the order is created? This is equivalent to turning the creation of the entire order into a serial operation. The order is placed. TPS may be too small
The poster mentioned concurrency because the user clicked the order button twice, resulting in repeated orders? If so, then there are many solutions to this scenario. Please refer to which distributed transaction middleware can ensure idempotence. , you can solve your problem through requestId/token
There is no need to set a lock in the program, just create a unique index in the database, so the performance is the best.
Using redis locking to implement
swoole+mysql