/**
* 使用swoole多进程上传文件到网宿服务器
* Created by PhpStorm.
* User: leeo
* Date: 2016/9/29
* Time: 15:26
*/
// 引入文件上传类
include_once "FileHandleClass.php";
$obj_fetch = new FileHandleClass();
$workers = [];
$worker_num = 2;
// 清空上次的日志文件
if(file_exists("logs/push.log")){
file_put_contents("logs/push.log","");
}
if(file_exists("logs/pop.log")){
file_put_contents("logs/pop.log","");
}
$filename = "data/2015-06-test.txt";// 需要上传的文件信息集合
$stream = file_get_contents($filename);
$data = json_decode($stream,true);
$total = count($data);
$every = intval($total / $worker_num) + 1; // 每个进程需要循环的次数
for($i = 0; $i < $worker_num; $i++){
$process = new swoole_process('callback_function', false, false);
$process->useQueue();
$pid = $process->start();
$workers[$pid] = $process;
}
function callback_function(swoole_process $worker){
global $obj_fetch;
while($recv = $worker->pop()){
file_put_contents("logs/pop.log",$recv."\r\n",FILE_APPEND);
$recv = json_decode($recv,true);
$obj_fetch->fetch($recv['full_path'],$recv['file_name']);
}
echo $worker->callback .'--'.$worker->pipe.PHP_EOL;
$worker->exit(0);
}
// 将资源存入队列中
$n = 0;
foreach($workers as $pid => $process){
if($n == $worker_num - 1){
$ret = array_slice($data,$n*$every);
}else{
$ret = array_slice($data,$n*$every,$every);
}
foreach($ret as $k=>$v){
$kv = json_encode($v);
$process->push($kv);
file_put_contents("logs/push.log",$kv."\r\n",FILE_APPEND);
}
$n++;
}
for($i = 0; $i < $worker_num; $i++)
{
$ret = swoole_process::wait();
$pid = $ret['pid'];
unset($workers[$pid]);
echo "Worker Exit, PID=".$pid.PHP_EOL;
}