Guzzle
Guzzle HTTP 客户端全解析及 PHP 使用与优化
一、介绍
Guzzle 是 PHP 世界中最流行的 HTTP 客户端库之一,用于发送 HTTP/HTTPS 请求并处理响应。
它支持:
同步和异步请求
HTTP/2
中间件机制(类似 Laravel / Hyperf 的管道)
并发请求
请求重试、超时、连接池
Guzzle 常被用于调用第三方 API、微服务接口或爬取网页数据。
官方文档:https://docs.guzzlephp.org
二 、安装
1composer require guzzlehttp/guzzle
三、基本使用
3.1 同步 GET 请求
1use GuzzleHttp\Client;
2
3$client = new Client([
4 'base_uri' => 'https://api.example.com',
5 'timeout' => 5.0, // 超时时间
6]);
7
8$response = $client->get('/users/1');
9
10echo $response->getStatusCode(); // 200
11echo $response->getBody(); // JSON 或 HTML
3.2 POST 请求与 JSON 数据
1$response = $client->post('/users', [
2 'json' => [
3 'name' => 'John',
4 'email' => 'john@example.com',
5 ],
6]);
7
8$data = json_decode($response->getBody(), true);
9print_r($data);
3.3 添加请求头
1$response = $client->get('/users', [
2 'headers' => [
3 'Authorization' => 'Bearer ' . $token,
4 'Accept' => 'application/json',
5 ],
6]);
四、异步请求与并发
Guzzle 支持异步请求,通过 Promises 机制提高并发性能。
1use GuzzleHttp\Promise;
2
3$promises = [
4 $client->getAsync('/users/1'),
5 $client->getAsync('/users/2'),
6 $client->getAsync('/users/3'),
7];
8
9$results = Promise\Utils::unwrap($promises);
10
11foreach ($results as $response) {
12 echo $response->getBody() . PHP_EOL;
13}
异步请求适合批量调用接口或爬虫场景。
unwrap() 会等待所有请求完成。
五、Guzzle 中间件
Guzzle 的 HandlerStack 支持中间件,用于统一处理日志、重试、限流等。
1use GuzzleHttp\HandlerStack;
2use GuzzleHttp\Middleware;
3use Monolog\Logger;
4use Monolog\Handler\StreamHandler;
5
6$stack = HandlerStack::create();
7$logger = new Logger('guzzle');
8$logger->pushHandler(new StreamHandler(__DIR__ . '/guzzle.log'));
9
10$stack->push(Middleware::log($logger, new \GuzzleHttp\MessageFormatter('{uri} - {code}')));
11
12$client = new Client(['handler' => $stack]);
六、Guzzle 使用优化
6.1 使用连接池
1$client = new Client([
2 'base_uri' => 'https://api.example.com',
3 'connect_timeout' => 2,
4 'timeout' => 5,
5 'http_errors' => false, // 避免抛异常
6]);
connect_timeout:建立 TCP 连接超时timeout:整个请求超时http_errors=false:避免 HTTP 错误抛异常,提高稳定性
6.2 重试机制
1use GuzzleHttp\RetryMiddleware;
2
3$retryMiddleware = Middleware::retry(function ($retries, $request, $response = null, $exception = null) {
4 return $retries < 3 && ($exception || $response->getStatusCode() >= 500);
5}, function ($retries) {
6 return 1000 * $retries; // 毫秒延迟
7});
8
9$stack = HandlerStack::create();
10$stack->push($retryMiddleware);
11
12$client = new Client(['handler' => $stack]);
6.3 并发请求优化
限制并发量:避免同时请求过多接口
异步请求 + Promise Pool:
1use GuzzleHttp\Promise\Utils;
2
3$pool = Utils::each_limit($promises, 5); // 同时最多 5 个请求
4$pool->wait();
发表评论