前言
介紹如何使用 PHP 中的 Guzzle HTTP 客戶端來處理大量 HTTP 請求,透過使用 Pool 功能提升整體請求效能,並說明 Pool 的概念、實際使用方法,以及如何搭配 Custom Key 更有效地管理請求
Guzzle HTTP 簡介
Guzzle 是 PHP 常用的 HTTP 請求函式庫,提供了簡單且易於使用的方式來處理各種 HTTP 請求,特別適合用來串接 API 或爬取網頁資料。
安裝與基本用法
使用 composer 安裝 Guzzle:
1
| composer require guzzlehttp/guzzle
|
簡單的 HTTP 請求範例(同步請求):
1 2 3 4 5 6 7 8
| use GuzzleHttp\Client;
$client = new Client(); $response = $client->request('GET', 'https://api.example.com/data');
echo $response->getStatusCode(); echo $response->getBody();
|
什麼是 Pool
Pool 是一種能同時處理多個 HTTP 請求的方式,能大幅縮短等待時間並提升整體請求效率。此外,透過 Pool 可以更有效地管理系統資源,避免過多的資源消耗。
Pool 使用方法
以下是 Pool 併發處理多個 HTTP 請求的範例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| use GuzzleHttp\Client; use GuzzleHttp\Pool; use GuzzleHttp\Psr7\Request;
$client = new Client(); $urls = [ 'https://jsonplaceholder.typicode.com/users/1', 'https://jsonplaceholder.typicode.com/users/2', ];
$requests = function ($urls) { foreach ($urls as $url) { yield new Request('GET', $url); } };
$pool = new Pool($client, $requests($urls), [ 'concurrency' => 5, 'fulfilled' => function ($response, $index) { echo "第 {$index} 個請求完成,狀態碼:" . $response->getStatusCode() . "\n"; }, 'rejected' => function ($reason, $index) { echo "第 {$index} 個請求失敗,原因:" . $reason . "\n"; }, ]);
$promise = $pool->promise(); $promise->wait();
|
Custom Key 的用法
使用自訂索引鍵(custom key)能有效管理不同的請求並方便追蹤每個請求狀態:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| use GuzzleHttp\Client; use GuzzleHttp\Pool; use GuzzleHttp\Psr7\Request;
$client = new Client(); $requests = function () { yield 'user1' => new Request('GET', 'https://jsonplaceholder.typicode.com/users/1'); yield 'user2' => new Request('GET', 'https://jsonplaceholder.typicode.com/users/2'); };
$pool = new Pool($client, $requests(), [ 'concurrency' => 5, 'fulfilled' => function ($response, $key) { echo "請求成功({$key}):" . $response->getBody() . "\n"; }, 'rejected' => function ($reason, $key) { echo "請求失敗({$key}):" . $reason . "\n"; }, ]);
$promise = $pool->promise(); $promise->wait();
|
總結
使用 Pool 時可依伺服器的限制調整併發數量,並配合 Custom Key 更方便地追蹤與管理各個請求。這樣可以讓開發人員更有效率地處理大量的請求任務。
Reference