多个接口"/>
使用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组件并发请求多个接口
发布评论