Home > Backend Development > PHP Tutorial > mysql - php concurrency processing?

mysql - php concurrency processing?

WBOY
Release: 2016-08-04 09:20:53
Original
946 people have browsed it

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>
Copy after login
Copy after login

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?

Reply content:

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>
Copy after login
Copy after login

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?

  1. You can use redis's atomic row operation to implement locking and set a key as a mark.

  2. You can use nmq to do it.

  1. 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

  2. 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

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template