协程应用问题

目的:使用协程并发下载网络图片 代码如下:

<?php
$server = new Swoole\Http\Server("127.0.0.1", 9502, SWOOLE_BASE);

$server->on('Request', 'onRequest');

function onRequest($request, $response)
{

    $arr = ["的","一","是","了","不","在","有","个","人","这","上","中","大","为","来","我","到","出","要","以","时","和","地","们","得","可","下","对","生","也","子","就","过","能","他","会","多","发","说","而","于","自","之","用","年","行","家","方","后","作"];

    $host = 'att.chaiwubi.com';

    //并发请求 n
    $n = count($arr)-1;
    for ($i = 0; $i < $n; $i++) {
        $cli = new \Swoole\Coroutine\Http\Client($host, 80);
        $cli->set(['timeout' => -1]);
        $cli->setHeaders([
            'Host' => $host,
            "User-Agent" => 'Chrome/49.0.2587.3',
            'Accept' => '*',
            'Accept-Encoding' => 'gzip'
        ]);
        $cli->setDefer();
        $cli->download('/wubi/86tj/'.$arr[$i].'gif', './uploads/'.$arr[$i].'.gif' );
        $clients[] = $cli;
    }
    for ($i = 0; $i < $n; $i++) {
        $r = $clients [$i]->recv();
        $result[] = $clients[$i]->body;
    }
    $response->end(json_encode($result));
}
$server->start();

需要30几秒才能完全结束。使用Swoole\Async::dnsLookup 5秒 之内能处理完毕。协程应用这块哪里出了问题?

2018-11-26 20:01
0
0

消逝

赞同来自:

代码格式全乱了?

2018-11-26 20:02
0

Rango - 一枚职业的码农

赞同来自:

因为每次都需要 DNS 解析,使用 Co::gethostbyname 解析域名,可以加快速度。

2018-11-27 21:44
0

消逝

赞同来自:

@Rango 改成Co::gethostbyname方式,也需要15秒 左右,太慢了。

2018-11-28 21:23

要回复问题请先登录注册