php Guzzle,异步请求的重要性

欢迎入企鹅群技术讨论:773298533
近期在写php接口开发,一个php文件里需要请求多个第三方接口,就在测试的时候打印耗时居然达到了1000ms!(一共需要请求四个第三方接口);
也在群友推荐接触到了guzzle类;能实现多个请求异步进行(好像是伪异步,懒得深究);
我用tp5写了个测试,guzzle和file_get_contents各请求四次,并且打印耗时,结果很明显
guzzle手册:http://guzzle-cn.readthedocs.io/zh_CN/latest/overview.html

多次测试结果
guz:300ms----fgc:845ms
guz:265ms----fgc:743ms
guz:277ms----fgc:789ms
guz:272ms----fgc:690ms
namespace app\open\controller;
use think\Request;
use think\Model;
use GuzzleHttp\Client;
use GuzzleHttp\Promise;
class Index
{
    public function index(){
list($msec, $sec) = explode(' ', microtime());
$time=(float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
    $client = new Client(['base_uri' => 'http://httpbin.org/']);

// Initiate each request but do not block
$promises = [
    'image' => $client->getAsync('http://h5api.m.taobao.com/h5/mtop.taobao.detail.getdetail/6.0/?appKey=12574478&api=mtop.taobao.detail.getdetail&v=6.0&type=json&data=%7B%22itemNumId%22%3A%22568914501203%22%7D'),
    'png'   => $client->getAsync('http://h5api.m.taobao.com/h5/mtop.taobao.detail.getdetail/6.0/?appKey=12574478&api=mtop.taobao.detail.getdetail&v=6.0&type=json&data=%7B%22itemNumId%22%3A%22568914501203%22%7D'),
    'jpeg'  => $client->getAsync('http://h5api.m.taobao.com/h5/mtop.taobao.detail.getdetail/6.0/?appKey=12574478&api=mtop.taobao.detail.getdetail&v=6.0&type=json&data=%7B%22itemNumId%22%3A%22568914501203%22%7D'),
    'webp'  => $client->getAsync('http://h5api.m.taobao.com/h5/mtop.taobao.detail.getdetail/6.0/?appKey=12574478&api=mtop.taobao.detail.getdetail&v=6.0&type=json&data=%7B%22itemNumId%22%3A%22568914501203%22%7D')
];

$results = Promise\unwrap($promises);
list($msec, $sec) = explode(' ', microtime());
$time2=(float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);


$client=file_get_contents('http://h5api.m.taobao.com/h5/mtop.taobao.detail.getdetail/6.0/?appKey=12574478&api=mtop.taobao.detail.getdetail&v=6.0&type=json&data=%7B%22itemNumId%22%3A%22568914501203%22%7D');
$client=file_get_contents('http://h5api.m.taobao.com/h5/mtop.taobao.detail.getdetail/6.0/?appKey=12574478&api=mtop.taobao.detail.getdetail&v=6.0&type=json&data=%7B%22itemNumId%22%3A%22568914501203%22%7D');
$client=file_get_contents('http://h5api.m.taobao.com/h5/mtop.taobao.detail.getdetail/6.0/?appKey=12574478&api=mtop.taobao.detail.getdetail&v=6.0&type=json&data=%7B%22itemNumId%22%3A%22568914501203%22%7D');
$client=file_get_contents('http://h5api.m.taobao.com/h5/mtop.taobao.detail.getdetail/6.0/?appKey=12574478&api=mtop.taobao.detail.getdetail&v=6.0&type=json&data=%7B%22itemNumId%22%3A%22568914501203%22%7D');
list($msec, $sec) = explode(' ', microtime());
$time3=(float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
echo 'guz:';
echo $time2-$time;
echo 'ms';
echo '----';
echo 'fgc:';
echo $time3-$time2;
echo 'ms';
    }
}
?>````

你可能感兴趣的:(php Guzzle,异步请求的重要性)