GuzzleHttp
目录
【注意】
基于协程的 GuzzleHttp
客户端的使用。
使用详情请阅:GuzzleHttp文档
安装依赖
composer require hyperf/guzzle
封装工具类
<?php
declare(strict_types=1);
namespace App\Lib\GuzzleHttp;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use Hyperf\Guzzle\PoolHandler;
use Hyperf\Guzzle\RetryMiddleware;
use function Hyperf\Support\make;
class GuzzleFactory
{
/**
* 获取带有连接池的协程的guzzle客户端.
* @explain make 从di中获取单例.
* @see https://docs.guzzlephp.org/en/stable/
* @param array $options 选项
* @return Client 客户端
*/
public static function getCoroutineGuzzleClient(array $options = []): Client
{
[$handler, $retry, $config] = [
make(PoolHandler::class, ['option' => ['max_connections' => 50]]),
make(RetryMiddleware::class, ['retries' => 1, 'delay' => 10]),
[],
];
$stack = HandlerStack::create($handler);
$stack->push($retry->getMiddleware(), 'retry');
$config['handler'] = $options['handler'] ?? $stack;
$config = array_merge($config, $options);
return make(Client::class, ['config' => $config]);
}
}