封装的方法
<?php
namespace App\Common;
use GuzzleHttp\Client;
use GuzzleHttp\Promise;
use Illuminate\Support\Facades\Log;
class GuzzleAsyncClient
{
protected $promises;
protected $client;
public function __construct($baseUri = '')
{
$this->promises = [];
$this->client = new Client($baseUri ? ['base_uri' => $baseUri] : []);
}
/**
* @return Client
*/
public function getClient(): Client
{
return $this->client;
}
/**
* @return mixed
*/
public function getPromises()
{
return $this->promises;
}
/**
* @param string $url
* @param string $key
* @param array $requestParams
*/
public function addPostPromise(string $url, string $key, array $requestParams): void
{
$info = [
'url' => $url,
'requestParams' => $requestParams
];
ApiLog::third(['remark' => '异步请求', 'index' => $key, 'request' => $info]);
$this->promises[$key] = $this->getClient()->postAsync($url, $requestParams);
}
public function run()
{
set_time_limit(-1);
ini_set('memory_limit', -1);
$promises = $this->getPromises();
return Promise\settle($promises)->wait();
}
/**
* 获取错误返回信息--数组
* @remark 只针对于多个循环的请求进行处理
* @param $prefixKey
* @return array
*/
public function getErrorsToArray($prefixKey): array
{
$promises = $this->getPromises();
$results = $this->run();
/*并发完成后获取结果*/
$total = count($promises);
$apiError = [];
for ($start = 0; $start < $total; $start++) {
if (isset($results[$prefixKey . $start]['value'])) {
$response = $results[$prefixKey . $start]['value'];
$apiError[] = [
'index' => $start,
'code' => $response->getStatusCode(),
'isSuccess' => $this->isSuccess($response),
'body' => $response->getBody()->getContents()
];
continue;
}
$apiError[] = [
'index' => $start,
'isSuccess' => false,
'body' => json_encode($results[$prefixKey . $start], 320)
];
}
ApiLog::third(['remark' => '异步请求', 'response' => $apiError]);
return $apiError;
}
/**
* 获取错误返回信息--字符
* @remark 只针对于多个循环的请求进行处理
* @param $prefixKey
* @return string
*/
public function getErrorsToString($prefixKey): string
{
$errors = $this->getErrorsToArray($prefixKey);
$apiError = '';
foreach ($errors as $error) {
$isSuccess = $error['isSuccess'];
$body = $error['body'];
$start = $error['index'];
if (!$isSuccess) {
$apiError .= '第' . ($start + 1) . '条数据录入失败:' . '服务器错误' . json_encode($error, 320) . PHP_EOL;
continue;
}
$body = json_decode($body, true);
if (!isset($body['code']) || (isset($body['code']) && $body['code'] != 0)) {
$apiError .= '第' . ($start + 1) . '条数据录入失败:' . ($body['msg'] ?? '接口响应格式错误') . json_encode($error, 320) . PHP_EOL;
}
}
return $apiError;
}
protected function isSuccess($response): bool
{
if ($response->getStatusCode() >= 200 && $response->getStatusCode() < 300) {
return true;
}
return false;
}
}
调取接口
#异步请求
protected function promise($makeParams, $detail): string
{
/*批量发送信息*/
if (!$detail['addApiUrl'] || !$detail['editApiUrl']) {
return false;
}
$companyId = 1;
//TODO
$promise = new GuzzleAsyncClient($url);
$adminId = UserRole::getAdminUserId($companyId);
$prefix = 'add';
foreach ($makeParams as $key => $param) {
$userId = 1;
$token = XXXX;
$request = [
'headers' => ['authorization' => $token],
'form_params' => $param
];
$url = $detail['addApiUrl'];
if (isset($param['id']) && $param['id'] != 0) {
$url = $detail['editApiUrl'];
}
if (isset($param['contract_id']) && $param['contract_id'] != 0) {
$url = $detail['editApiUrl'];
}
$promise->addPostPromise($url, $prefix . $key, $request);
}
return $promise->getErrorsToString($prefix);
}