PHP 併發場景的 3 種解決方案

在秒殺,搶購等併發場景下,可能會出現超賣的現象,在 PHP 語言中並沒有原生提供併發的解決方案,因此就需要藉助其他方式來實現併發控制。

列出常見的解決方案有:

使用隊列,額外起一個進程處理隊列,併發請求都放到隊列中,由額外進程串行處理,併發問題就不存在了,但是要額外進程支持以及處理延遲嚴重,本文不先不討論這種方法。

利用數據庫事務特徵,做原子更新,此方法需要依賴數據庫的事務特性。

藉助文件排他鎖,在處理下單請求的時候,用 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
$http = new swoole_http_server("0.0.0.0", 9511);
$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+");
 // 非阻塞模式, 如果不希望 flock() 在鎖定時堵塞,則給 lock 加上 LOCK_NB
 if(flock($fp,LOCK_EX | LOCK_NB))   //鎖定當前指針
 {
 // 成功取得鎖後,放心處理訂單
 $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);
 } else {
 // 如果獲取鎖失敗,馬上進入這裏執行
 echo "{$uniqid} - 系統繁忙,請稍後再試".PHP_EOL;
 }
 fclose($fp);
});
$http->start();

使用 ab 測試

$ ab -t 20 -c 10 http://192.168.1.104:9511/

最後給出三種處理方式的測試結果比較

redis 事務方式:

......
Concurrency Level:      10
Time taken for tests:   20.005 seconds
Complete requests:      17537
Failed requests:        0
Total transferred:      2578380 bytes
HTML transferred:       0 bytes
Requests per second:    876.62 [#/sec] (mean)
Time per request:       11.407 [ms] (mean)
Time per request:       1.141 [ms] (mean, across all concurrent requests)
Transfer rate:          125.86 [Kbytes/sec] received
......

文件排他鎖(阻塞模式):

......
Concurrency Level:      10
Time taken for tests:   20.003 seconds
Complete requests:      8205
Failed requests:        0
Total transferred:      1206282 bytes
HTML transferred:       0 bytes
Requests per second:    410.19 [#/sec] (mean)
Time per request:       24.379 [ms] (mean)
Time per request:       2.438 [ms] (mean, across all concurrent requests)
Transfer rate:          58.89 [Kbytes/sec] received
...... 

文件排他鎖(非阻塞模式):

......
Concurrency Level:      10
Time taken for tests:   20.002 seconds
Complete requests:      8616
Failed requests:        0
Total transferred:      1266846 bytes
HTML transferred:       0 bytes
Requests per second:    430.77 [#/sec] (mean)
Time per request:       23.214 [ms] (mean)
Time per request:       2.321 [ms] (mean, across all concurrent requests)
Transfer rate:          61.85 [Kbytes/sec] received
......

經測試結果對比,redis 事務方式優於文件排他鎖方式,而文件排他鎖方式中,非阻塞模式優於阻塞模式。

更多學習內容請訪問:

騰訊T3-T4標準精品PHP架構師教程目錄大全,只要你看完保證薪資上升一個臺階(持續更新)​

以上內容希望幫助到大家,很多PHPer在進階的時候總會遇到一些問題和瓶頸,業務代碼寫多了沒有方向感,不知道該從那裏入手去提升,對此我整理了一些資料,包括但不限於:分佈式架構、高可擴展、高性能、高併發、服務器性能調優、TP6,laravel,YII2,Redis,Swoole、Swoft、Kafka、Mysql優化、shell腳本、Docker、微服務、Nginx等多個知識點高級進階乾貨需要的可以免費分享給大家,需要的可以加入我的官方羣點擊此處

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章