本篇文章為大家展示了PHP中并發問題的解決方法,代碼簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
1、使用隊列,額外起一個進程處理隊列,并發請求都放到隊列中,由額外進程串行處理,并發問題就不存在了,但是要額外進程支持以及處理延遲嚴重,本文不先不討論這種方法。
2、利用數據庫事務特征,做原子更新,此方法需要依賴數據庫的事務特性。
3、借助文件排他鎖,在處理下單請求的時候,用flock鎖定一個文件,成功拿到鎖的才能處理訂單。
一、利用 Redis 事務特征
redis 事務是原子操作,可以保證訂單處理的過程中數據沒有被其它并發的進程修改。
示例代碼:
<?php $http = new swoole_http_server("0.0.0.0", 9509); // 監聽 9509 $http->set(array( 'reactor_num' => 2, //reactor thread num 'worker_num' => 4 //worker process num )); $http->on('request', function (swoole_http_request $request, swoole_http_response $response) { $uniqid = uniqid('uid-', TRUE); // 模擬唯一用戶ID $redis = new Redis(); $redis->connect('127.0.0.1', 6379); // 連接 redis $redis->watch('rest_count'); // 監測 rest_count 是否被其它的進程更改 $rest_count = intval($redis->get("rest_count")); // 模擬唯一訂單ID if($rest_count > 0){ $value = "{$rest_count}-{$uniqid}"; // 表示當前訂單,被當前用戶搶到了 // do something ... 主要是模擬用戶搶到單后可能要進行的一些密集運算 $rand = rand(100, 1000000); $sum=0; for ($i=0;$i<$rand;$i++){ $sum+=$i; } // redis 事務 $redis->multi(); $redis->lPush('uniqids', $value); $redis->decr('rest_count'); $replies = $redis->exec(); // 執行以上 redis 事務 // 如果 rest_count 的值被其它的并發進程更改了,以上事務將回滾 if(!$replies){ echo "訂單 {$value} 回滾".PHP_EOL; } } $redis->unwatch(); }); $http->start();
使用 ab 測試
$ ab -t 20 -c 10 http://192.168.1.104:9509/
二、利用文件排他鎖(阻塞模式)
阻塞模式下,如果進程在獲取文件排他鎖時,其它進程正在占用鎖的話,此進程會掛起等待其它進程釋放鎖后,并自己獲取到鎖后,再往下執行。
示例代碼:
<?php $http = new swoole_http_server("0.0.0.0", 9510); $http->set(array( 'reactor_num' => 2, //reactor thread num 'worker_num' => 4 //worker process num )); $http->on('request', function (swoole_http_request $request, swoole_http_response $response) { $uniqid = uniqid('uid-', TRUE); $redis = new Redis(); $redis->connect('127.0.0.1', 6379); $fp = fopen("lock.txt", "w+"); // 阻塞(等待)模式, 要取得獨占鎖定(寫入的程序) if(flock($fp,LOCK_EX)) //鎖定當前指針 { // 成功取得鎖后,放心處理訂單 $rest_count = intval($redis->get("rest_count")); $value = "{$rest_count}-{$uniqid}"; if($rest_count > 0){ // do something ... $rand = rand(100, 1000000); $sum=0; for ($i=0;$i<$rand;$i++){ $sum+=$i; } $redis->lPush('uniqids', $value); $redis->decr('rest_count'); } // 訂單處理完成后,再釋放鎖 flock($fp,LOCK_UN); } fclose($fp); }); $http->start();
使用 ab 測試
$ ab -t 20 -c 10 http://192.168.1.104:9510/
上述內容就是PHP中并發問題的解決方法,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。