示例一:
利用通道pop会自动挂起当前协程,等待生产者推送数据的特性,实现并发调用,并在协程完成后组合结果集。
$serv = new Swoole\Http\Server("127.0.0.1", 9503, SWOOLE_BASE);
$serv->on('request', function ($req, $resp) {
$chan = new Swoole\Coroutine\Channel(2);
go(function () use ($chan) {
$cli = new Swoole\Coroutine\Http\Client('www.qq.com', 80);
$cli->set(['timeout' => 10]);
$cli->setHeaders([
'Host' => "www.qq.com",
'User-Agent' => 'Chrome/49.0.2587.3',
'Accept' => 'text/html,application/xhtml+xml,application/xml',
'Accept-Encoding' => 'gzip',
]);
$ret = $cli->get('/');
$chan->push(['www.qq.com' => $cli->body]);
});
go(function () use ($chan) {
$cli = new Swoole\Coroutine\Http\Client('www.baidu.com', 80);
$cli->set(['timeout' => 10]);
$cli->setHeaders([
'Host' => "www.baidu.com",
'User-Agent' => 'Chrome/49.0.2587.3',
'Accept' => 'text/html,application/xhtml+xml,application/xml',
'Accept-Encoding' => 'gzip',
]);
$ret = $cli->get('/');
$chan->push(['www.baidu.com' => $cli->body]);
});
$result = [];
for ($i = 0; $i < 2; $i++)
{
// 当通道为空时,会自动挂起当前协程,等待生产者推送数据后,重新调度进来
$result += $chan->pop();
}
$resp->end(json_encode($result));
});
$serv->start();
示例二:
利用Swoole封装好的WaitGroup类,实现并发调用,并在协程完成后组合结果集。
底层也是基于通道的计数、push和pop实现的。
<?php
Co\run(function () {
$wg = new \Swoole\Coroutine\WaitGroup();
$result = [];
// 增加第一个计数
$wg->add();
// 启动第一个协程
go(function () use ($wg, &$result) {
//启动一个协程客户端client,请求淘宝首页
$cli = new \Swoole\Coroutine\Http\Client('www.taobao.com', 443, true);
$cli->setHeaders([
'Host' => 'www.taobao.com',
'User-Agent' => 'Chrome/49.0.2587.3',
'Accept' => 'text/html,application/xhtml+xml,application/xml',
'Accept-Encoding' => 'gzip',
]);
$cli->set(['timeout' => 1]);
$cli->get('/index.php');
$result['taobao'] = $cli->body;
$cli->close();
// 标记任务完成
$wg->done();
});
// 增加第二个计数
$wg->add();
// 启动第二个协程
go(function () use ($wg, &$result) {
//启动一个协程客户端client,请求百度首页
$cli = new \Swoole\Coroutine\Http\Client('www.baidu.com', 443, true);
$cli->setHeaders([
'Host' => 'www.baidu.com',
'User-Agent' => 'Chrome/49.0.2587.3',
'Accept' => 'text/html,application/xhtml+xml,application/xml',
'Accept-Encoding' => 'gzip',
]);
$cli->set(['timeout' => 1]);
$cli->get('/index.php');
$result['baidu'] = $cli->body;
$cli->close();
// 标记任务完成
$wg->done();
});
// 挂起当前协程,等待所有任务完成后恢复当前协程的执行
$wg->wait();
//这里 $result 包含了 2 个任务执行结果
var_dump($result);
});