引入背景:假如我們每天有10000個訂單生成,需要同步到倉儲系統中去,以前做法是開啟一個crontab去跑這些任務,但是發現總有感覺同步效率低,間隔時間都是分鐘級別的。
解決方案測試:我們將同步訂單的任務表添加一個hash作為key,作為分發條件,因為mysql中select如果做mod函數是用不到索引的,所以我們自己做隨機hash,但是務必不需要范圍太大,以免服務器資源不夠,方法是根據hashkey投放到不同的進程中進行同步,測試代碼如下
<?php /** * Created by PhpStorm. * User: xujun * Date: 2017/8/26 * Time: 9:37 */ //假定需要處理的數據如下 class Process{ public $mpid=0; public $max_precess=5; //代替從數據庫中讀取的內容 public $task = [ ['uid'=>1,'uname'=>'bot','hash'=>1,'handle'=>'test'], ['uid'=>2,'uname'=>'bot1','hash'=>2,'handle'=>'test'], ['uid'=>3,'uname'=>'bot2','hash'=>3,'handle'=>'test'], ['uid'=>4,'uname'=>'bot3','hash'=>4,'handle'=>'test'], ['uid'=>2,'uname'=>'bot4','hash'=>2,'handle'=>'test'], ['uid'=>3,'uname'=>'bot5','hash'=>3,'handle'=>'test'], ['uid'=>4,'uname'=>'bot6','hash'=>1,'handle'=>'test'], ]; public $works = []; public $swoole_table = NULL; //public $new_index=0; function test($index,$task){ print_r("[".date('Y-m-d H:i:s')."]".'work-index:'.$index.'處理'.$task['uname'].'完成'.PHP_EOL); } public function __construct(){ try { $this->swoole_table = new swoole_table(1024); $this->swoole_table->column('index', swoole_table::TYPE_INT);//用于父子進程間數據交換 $this->swoole_table->create(); swoole_set_process_name(sprintf('php-ps:%s', 'master')); $this->mpid = posix_getpid(); $this->run(); $this->processWait(); }catch (\Exception $e){ die('ALL ERROR: '.$e->getMessage()); } } public function run(){ for ($i=0; $i < $this->max_precess; $i++) { $this->CreateProcess(); } } private function getTask($index){ $_return = []; foreach ($this->task as $v){ if($v['hash']==$index){ $_return[] = $v; } } return $_return; } public function CreateProcess($index=null){ if(is_null($index)){//如果沒有指定了索引,新建的子進程,開啟計數 $index=$this->swoole_table->get('index'); if($index === false){ $index = 0; }else{ $index = $index['index']+1; } print_r($index); } $this->swoole_table->set('index',array('index'=>$index)); $process = new swoole_process(function(swoole_process $worker)use($index){ swoole_set_process_name(sprintf('php-ps:%s',$index)); $task = $this->getTask($index); foreach ($task as $v){ call_user_func_array(array($this,$v['handle']),array($index,$v)); } sleep(20); }, false, false); $pid=$process->start(); $this->works[$index]=$pid; return $pid; } public function rebootProcess($ret){ $pid=$ret['pid']; $index=array_search($pid, $this->works); if($index!==false){ $index=intval($index); $new_pid=$this->CreateProcess($index); echo "rebootProcess: {$index}={$new_pid} Done\n"; return; } throw new \Exception('rebootProcess Error: no pid'); } public function processWait(){ while(1) { if(count($this->works)){ $ret = swoole_process::wait(); if ($ret) { $this->rebootProcess($ret); } }else{ break; } } } } $process = new Process();
這里代碼中,使用了swoole_table作為進程間共享的內存,為了分配index。以及當進程退出后,父進程通過wait重新拉起該進程任務。
測試截圖
進程ps
結果 休眠20s后退出后會被自動拉起
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持。
【網站聲明】本站除付費源碼經過測試外,其他素材未做測試,不保證完整性,網站上部分源碼僅限學習交流,請勿用于商業用途。如損害你的權益請聯系客服QQ:2655101040 給予處理,謝謝支持。