Laravel中GuzzleHttp异步请求

封装的方法

<?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);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值