近期在写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'; } }?>````
作者:阿哇哥哥
链接:https://www.jianshu.com/p/116711c741eb
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦