详解PHP swoole进程的使用方法
引入背景:假如我们每天有10000个订单生成,需要同步到仓储系统中去,以前做法是开启一个crontab去跑这些任务,但是发现总有感觉同步效率低,间隔时间都是分钟级别的。
解决方案测试:我们将同步订单的任务表添加一个混杂作为关键,作为分发条件,因为关系型数据库中挑选如果做现代的函数是用不到索引的,所以我们自己做随机哈希,但是务必不需要范围太大,以免服务器资源不够,方法是根据哈斯基投放到不同的进程中进行同步,测试代码如下
?php/** *由PhpStorm创建。*用户:徐俊*日期: 2017/8/26 *时间: 9:37 *//假定需要处理的数据如下进程类{ public $ mpid=0;public $ max _ process=5;//代替从数据库中读取的内容public $task=[ ['uid'=1,' uname'='bot ',' hash'=1,' handle'='test'],['uid'=2,' uname'='bot1 ',' hash'=2,' handle'='test'],['uid'=3,' handle'='test'],[' uname ' public $ works=[];public $ swoole _ table=NULL//public $ new _ index=0;函数测试($index,$task){ print_r('[').日期(' Y-m-d H:i:s ').']'.工作指数:$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(sprint f(' PHP-PS :% s ',' master '));$ this-mpid=POSix _ getpid();$ this-run();$ this-processWait();} catch(\ Exception $ e){ die(' ALL错误: ')。$ e-Getmessay());} } public function run(){ for($ I=0;$ I $ this-max _ process;$ I){ $ this-CreateProcess();} }私有函数getTask($ index){ $ _ return=[];foreach($ this-task as $ v){ if($ v[' hash ']==$ index){ $ _ return[]=$ v;} } return $ _ return}公共函数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(sprint f(' PHP-PS :% s ',$ index));$ task=$ this-getTask($ index);foreach($ task as $ v){ call _ user _ func _ array(array($ this,$v['handle']),array($index,$ v));}睡眠(20);},假,假);$ PID=$ process-start();$ this-works[$ index]=$ PID;返回$ pid}公共函数rebot process($ ret){ $ PID=$ ret[' PID '];$index=array_search($pid,$ this-works);if($index!==false){ $ index=int val($ index);$ new _ PID=$ this-create process($ index);echo ' rebot process : { $ index }={ $ new _ PID } Done \ n ';返回;}抛出新的\异常(' RebotProcessError :无PID’);}公共函数processWait(){ while(1){ if(count($ this-works)){ $ ret=swoole _ process : wait();if($ ret){ $ this-rebot process($ ret);} } else { break } } } } $ Process=new Process();这里代码中,使用了swoole_table作为进程间共享的内存,为了分配指数。以及当进程退出后,父进程通过等待重新拉起该进程任务。
测试截图
进程著名图象处理软件
结果休眠20多岁后退出后会被自动拉起
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。
版权声明:详解PHP swoole进程的使用方法是由宝哥软件园云端程序自动收集整理而来。如果本文侵犯了你的权益,请联系本站底部QQ或者邮箱删除。