使用guzzleHttp组件并发请求多个接口

编程入门 行业动态 更新时间:2024-10-27 09:34:46

使用guzzleHttp组件并发请求<a href=https://www.elefans.com/category/jswz/34/1771377.html style=多个接口"/>

使用guzzleHttp组件并发请求多个接口

GuzzleHttp异步并发使用

use GuzzleHttp\Pool;use GuzzleHttp\Client;use GuzzleHttp\Psr7\Request;private function multi_req($reqs)
{$client = new Client();$requests = function ($reqs) use($client) {foreach ($reqs as $v){yield function() use($client, $v) {$options = ['verify' => false, 'headers' => $v['headers']];if (isset($v['form_params'])) {$options['form_params'] = $v['form_params'];}if (isset($v['body'])) {$options['body'] = $v['body'];}if (isset($v['query'])) {$options['query'] = $v['query'];}return $client->request($v['method'], $v['url'], $options);};}};$responses = [];$bad_responses = [];$pool = new Pool($client, $requests($reqs), ['concurrency' => 5,'fulfilled' => function ($response, $index) use(&$responses) {// this is delivered each successful response
//                echo "index={$index},response:".(string)$response->getBody()."<br/>";$responses[$index] = (string)$response->getBody();},'rejected' => function ($reason, $index) use ($bad_responses) {// this is delivered each failed request$bad_responses[$index] = '';},]);// Initiate the transfers and create a promise$promise = $pool->promise();// Force the pool of requests to complete.$promise->wait();//坏的结果返回处理foreach ($bad_responses as  $key=>$val){}return $responses;
}

调用multi_req方法 相关的代码

$reqs = [];
$reqs[] = $SignFlows->createControlAsync($this->appId, $stoken, $order, $this->createUrl, $this->templateId);
$reqs[] = $SignFlows->creatFlowAsync($this->appId, $stoken, $this->creataFlow);
$reqs[] = $SignFlows->staticAuthAsync($this->appId,$stoken, $accountId, $this->staticAuth);//staticAuthAsync()返回的数组格式形如
//return ['url'=>$executeUrl,'method'=>'POST','form_params'=>$data, 'headers'=>$this->makeHeader($appId, $stoken)];$responses = $this->multi_req($reqs);
$fileId = '';
$flowid = '';
//返回处理
foreach ($responses as  $key=>$val){echo 'index:'.$key.',response:'.$responses[$key].'<br/>';if ($key == 0) {$ret = (array)json_decode($val,true);$fileId = $ret['data']->fileId;} elseif ($key == 1) {$ret = (array)json_decode($val,true);$flowid = $ret['data']->flowId;}
}

post请求 参数使用 form_params

get请求参数 使用 query

put请求参数 使用 body

header头部分 使用 headers

SSL 证书验证 如果不验证  使用verify=>false

更多推荐

使用guzzleHttp组件并发请求多个接口

本文发布于:2023-12-05 05:16:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1663190.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   组件   接口   guzzleHttp

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!