php多进程swoole中swoole_http_server和swoole_process巧妙处理

3 篇文章 0 订阅
1 篇文章 0 订阅

在日常处理使用php处理业务逻辑的时候总会遇到过快执行与慢执行同时都要执行,例如表单上传的时候要发送邮件给用户,同时用户也是非常多,不可能提交很少的数据提交时间需要10-20秒这个时候客户就会觉得好垃圾啊,什么鸟程序。这个时候他来了他来了他脚踏祥云swoole他来了。

下面代码运行是这样的例如https://www.xxx.com/index.php?_acid=3&s=/api/play/qingyouji.html这个是我要快速输出给前端的东西。

下面这部分东西是我要异步的东西。把我要异步的都放置守护进程来完成。

$urls=[
            'https://www.xxx.com/index.php?_acid=3&s=/api/index/index.html',
            'https://www.xxx.com/index.php?_acid=3&s=/api/index/tehui.html',
            'https://www.xxx.com/index.php?_acid=3&s=/api/play/dangjituijian.html',
            'https://www.xxx.com/index.php?_acid=3&s=/api/play/qingyouji.html'
  ];

最后浏览器上运行 http:xxx.aizxy.cn:9501就可以了,剩下的API接口要怎么写我就不废话了。

<?php

$http = new swoole_http_server("xxx.aizxy.cn", 9501);
$http->set([
     'worker_num' =>3, //工作进程数
     'daemonize' => true, //是否后台运行
]);
$http->on('request','Run');
function Run($request, $response)
{
	$url=$request->server['request_uri'];
	if($url!='/favicon.ico'){
		$urls=[
			'https://www.xxx.com/index.php?_acid=3&s=/api/index/index.html',
			'https://www.xxx.com/index.php?_acid=3&s=/api/index/tehui.html',
			'https://www.xxx.com/index.php?_acid=3&s=/api/play/dangjituijian.html',
			'https://www.xxx.com/index.php?_acid=3&s=/api/play/qingyouji.html'
		];
		handel($urls);
	}
	$data='https://www.xxx.com/index.php?_acid=3&s=/api/play/qingyouji.html';
	$data=file_get_contents($data);
	$response->end($data);
}
//处理进程
function handel($urls)
{
	$worker_num = 5;
	$process_pool = [];
	$process= null;
	$pid = posix_getpid();
	$customMsgKey = 1;
    $mod = 2 | swoole_process::IPC_NOWAIT;//这里设置消息队列为非阻塞模式
    for($i=0;$i<$worker_num; $i++) {
    	$process=new swoole_process('sub_process');
    	$process->useQueue($customMsgKey, $mod);
    	$process->start();
    	$pid = $process->pid;
    	$process_pool[$pid] = $process;
    }
    //由于所有进程是共享使用一个消息队列,所以只需向一个子进程发送消息即可
    $process = current($process_pool);
    foreach ($urls as $url) {
    	$process->push($url);
    }

}
//管道
function sub_process(swoole_process $worker)
{
    sleep(1); //防止父进程还未往消息队列中加入内容直接退出
    while($url = $worker->pop()){
    	if ($url === false) {
    		break;
    	}
    	$sub_pid = $worker->pid;
    	$content=file_get_contents($url);//异步请求不返回
    	//file_put_contents(__DIR__.'/a.txt',"[$sub_pid] url : $url.$content".PHP_EOL,FILE_APPEND);
        sleep(1);//这里的sleep模拟任务耗时,否则可能1个worker就把所有信息全接受了
    }
    $worker->exit(0);
}
$http->start();

有些小伙伴如果进程被占用了netstat  -anp  |  grep 9501

然后再杀死进程kill -9 10908

最后再次运行即可。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值