废话不多说,先上代码:
Swoole \Coroutine\Http\Client('www.zyhuadu.com', 80); $cli->setHeaders([ 'Host' => "www.zyhuadu.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.html'); //数据进入 通道 $chan->push( array( 'index'=>0, ' strlen '=>strlen($cli->body), ) ); $cli-> close (); }); //请求二 go(function () use ($chan){ $cli = new Swoole\Coroutine\Http\Client('www.zyhuadu.com', 80); $cli->setHeaders([ 'Host' => "www.zyhuadu.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.html'); //echo $cli->body; $chan->push( array( 'index'=>1, 'strlen'=>strlen($cli->body), ) ); $cli->close(); }); //请求三 go(function () use ($chan){ $cli = new Swoole\Coroutine\Http\Client('www.zyhuadu.com', 80); $cli->setHeaders([ 'Host' => "www.zyhuadu.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.html'); //echo $cli->body; $chan->push( array( 'index'=>2, 'strlen'=>strlen($cli->body), ) ); $cli->close(); }); $i = 3; while ($i > 0) { //获取 返回数据 $data = $chan->pop(); print_r($data); $i--; } });
运行结果:
多次运行:
多次运行返回的顺序不同,因为每个请求,先返回不一定,先返回,先resume,然后pop
协程的方式,并行IO操作,最大执行时间取决于最长请求时间。
Co\Channel- Channel->push :当队列中有其他协程正在等待pop数据时,自动按顺序唤醒一个消费者协程。当队列已满时自动 yield 让出控制器,等待其他协程消费数据
- Channel->pop:当队列为空时自动yield,等待其他协程生产数据。消费数据后,队列可写入新的数据,自动按顺序唤醒一个生产者协程。