日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > php >内容正文

php

[PHP] 使用 pcntl 库实现PHP多进程

發(fā)布時間:2025/3/21 php 14 豆豆
生活随笔 收集整理的這篇文章主要介紹了 [PHP] 使用 pcntl 库实现PHP多进程 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

最近因項目需要,需要大量同步數據,數據量基數在3000萬條左右,因此想到了開啟多進程來處理,下面是處理的完整代碼,基于laravel 5.1框架。
這是經過實際環(huán)境驗證過的,所以類似場景可以簡單修改下就可使用。

/*** ******數據同步腳本** @author yedonghai*/namespace App\Console\Commands;use DB;use Illuminate\Console\Command;use App\Services\ZzcService;class ZzcSyncCommand extends Command{/*** The name and signature of the console command.** @var string*/protected $signature = 'zzcsync:data';/*** The console command description.** @var string*/protected $description = 'sync zzc apply info';/*** Execute the console command.** @return mixed*/public function handle(){$userNum = 6500000;$workers = 30;$block = 50000;$loop = 0;$flag = 0;$processIds = [];do {$flag = $loop * $workers * $block;for ($i = 0; $i < $workers; $i++) {$minUserId = ($block * $i) + $flag;$maxUserId = $block * ($i + 1) + $flag;if ($minUserId < $userNum) {$processIds[$i] = pcntl_fork();switch ($processIds[$i]) {case -1 :echo "fork failed : {$i} \r\n";exit;case 0 :$this->_userReport($minUserId, $maxUserId);exit;default :break;}} else {break;}}while(count($processIds) > 0) {$mypid = pcntl_waitpid(-1, $status, WNOHANG);foreach ($processIds as $key => $pid) {if ($mypid == $pid || $mypid == -1) {unset($processIds[$key]);}}}$loop++;} while (empty($processIds) && $flag < $userNum);}/*** 子進程獲取指定數據** @param integer $minUserId 讀取區(qū)間的下限* @param integer $maxUserId 讀取區(qū)間的上限** @return array*/private function _userReport($minUserId, $maxUserId){$users = DB::table('users')->leftJoin('user_credits', 'user_credits.user_id', '=', 'users.id')->select('users.id', 'users.user_name as mobile', 'users.id_number as pid', 'users.truename as name')->where('user_credits.audit_limit', '>', 0)->where('users.id', '>=', $minUserId)->where('users.id', '<', $maxUserId)->get();foreach ($users as $userObj) {$userExist = DB::table('zzc_apply')->where('user_id', $userObj->id)->first();if (!empty((array)$userExist)) {continue;}$userArr = [];$userArr['loan_type'] = '消費貸';$userArr['loan_term'] = '3';$userArr['loan_purpose'] = '購物';$userArr['applicant']['name'] = $userObj->name;$userArr['applicant']['pid'] = $userObj->pid;$userArr['applicant']['mobile'] = $userObj->mobile;$user = json_encode($userArr);$zzcService = new ZzcService();$zzcService->createNezha($user);}}}

總結

以上是生活随笔為你收集整理的[PHP] 使用 pcntl 库实现PHP多进程的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。