首頁  >  文章  >  後端開發  >  如何監控 Guzzle Http 用戶端 – PHP 快速提示

如何監控 Guzzle Http 用戶端 – PHP 快速提示

王林
王林原創
2024-08-17 06:39:08484瀏覽

Guzzle 是一款受歡迎的 PHP HTTP 用戶端,可以輕鬆發送 HTTP 請求和建立 Web 服務庫。最受歡迎的 PHP 框架提供了內部 Http Client 服務,它們只是 Guzzle Http Client 的客製化實作:

  • Laravel Http 客戶端
  • Symfony Http 客戶端
  • Laminas(以前的 Zend Framework)Http 客戶端

Guzzle 被廣泛使用有兩個主要原因:

1) 客製化和靈活性

對於設計模式的愛好者來說,Guzzle 是開放的擴充。意味著您可以透過擴展其核心元件(Http Client、Request、Response、Milddeware 等)輕鬆地在 Guzzle 中實現新功能。

2)對中介軟體的支持

Guzzle 中間件系統允許開發人員在發送請求之前與請求進行交互,並在處理回應之前與回應進行交互。它可以啟用日誌記錄、身份驗證和錯誤處理等高級功能。

Guzzle HTTP 用戶端簡介

在本教程中,我將引導您完成建立自訂 Guzzle Http 用戶端的過程,以便輕鬆監控應用程式針對外部服務發出的每個請求。

我還將向您展示如何將此實作注入到 IoC 容器(或服務容器)中,以使此實作在您的整個應用程式中可用。

我們將介紹基礎知識、自訂選項,並提供真實的程式碼範例。

安裝Guzzle

確保您已安裝 Guzzle。如果沒有,請使用 Composer 安裝:

composer require guzzlehttp/guzzle

基本客製化

讓我們先建立一個基本的自訂 Guzzle Http 客戶端:

namespace App\Extensions\Guzzle;

use GuzzleHttp\Client;

class CustomGuzzleClient extends Client 
{
    public function __construct(array $config = []) 
    {
        $config['headers']['Custom-Header'] = 'Custom-Value';
        parent::__construct($config);
    }
}

在此範例中,我們擴展了 Guzzle Http Client 類別並自訂建構函數,以向該客戶端發出的所有請求新增自訂標頭。

監控 Guzzle Http 請求

Guzzle 提供了執行 Http 請求的快速方法:

$client->get('/endpoint');
$client->post('/endpoint');
$client->put('/endpoint');

所有這些方法都使用內部的通用請求方法。下面的截圖取自 Guzzle 客戶端程式碼:

How to monitor Guzzle Http Client – PHP Fast tips

您可以重寫請求方法來自訂應用程式對外部服務進行的 HTTP 呼叫的管理。

namespace App\Extensions\Guzzle;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;


class CustomGuzzleClient extends Client 
{
    public function request($method, $uri, array $options = []) 
    {
        return inspector()->addSegment(function () use ($method, $uri, $options) {

            return parent::request($method, $uri, $options);

        }, "http", "{$method} {$uri}");
    }
}

在此範例中,我只是在每個請求的事務時間軸中新增一個項目。現在您可以在監控視圖中看到 Guzzle 進行的 API 呼叫:

How to monitor Guzzle Http Client – PHP Fast tips

如果您是 Inspector 新手,您可以按照本教學了解如何入門:

https://inspector.dev/laravel-real-time-performance-monitoring-using-inspector-part-1/

您也可以在回呼中註入 Segment 參數來與項目互動或添加更多資訊:

namespace App\Extensions\Guzzle;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Inspector\Models\Segment;

class CustomGuzzleClient extends Client 
{
    public function request($method, $uri, array $options = []) 
    {
        return inspector()->addSegment(function (Segment $segment) use ($method, $uri, $options) {

            $response = parent::request($method, $uri, $options);
            $segment->label = "{$response->getStatusCode()} {$method} {$uri}";
            return $response;

        }, "http");
    }
}

使用自訂 Http 客戶端

現在,您可以在應用程式中使用自訂客戶端。由於該擴充功能不會對標準 Guzzle Http 用戶端的行為進行任何更改,因此您可以建立自訂類別的實例並照常使用它:

// Create an instance of the custom client
$client = new CustomGuzzleClient(['base_uri' => 'https://api.example.com']);

// Make an API request. It will be automatically monitored by Inspector.
$response = $client->get('/endpoint');

將 Guzzle Http Client 綁定到容器中

在這個範例中我將使用 Laravel,但基本概念與本文開頭提到的最受歡迎的 PHP 框架相同。它們都與服務容器一起使用。

我們為 Guzzle Http Client 類別建立一個綁定到容器中的單例。因此,每個請求此類的服務都會收到一個支援即時監控的自訂客戶端實例。

use GuzzleHttp\Client;
use App\Extensions\Guzzle\CustomGuzzleClient;
use Illuminate\Contracts\Foundation\Application;

$this->app->singleton(Client::class, function (Application $app) {
    return new CustomGuzzleClient();
});

現在您可以嘗試在 Artisan Command 中註入 Guzzle Http Client 類別並執行 Http 呼叫以進行測試:

namespace App\Console\Commands;


use Illuminate\Console\Command;
use GuzzleHttp\Client;

class TryCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'try';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Test Guzzle Http Client monitoring.';

    /**
     * Inject the Guzzle Http Client class into the constructor.
     * The CustomGuzzleClient will be the concrete class.
     */
    public function __construct(protected Client $client)
    {
        parent::__construct();
    }

    /**
     * Handle the command execution.
     */
    public function handle()
    {
        $this->line($this->description);

        $this->line("Concrete class: ".get_class($this->client));

        $this->client->get('https://google.com');

        return Command::SUCCESS;
    }
}

執行指令來驗證 Http 呼叫是否在交易時間軸中可見:

php artisan try

督察新人?免費監控您的應用程式

Inspector是一款專為軟體開發人員設計的程式碼執行監控工具。您無需在雲端基礎架構或伺服器中安裝任何內容,只需安裝 Composer 套件即可開始使用。

與其他複雜的一體化平台不同,Inspector 非常簡單,並且對 PHP 友善。您可以嘗試我們的 Laravel 或 Symfony 套件。

如果您正在尋找有效的自動化、深入的見解以及將警報和通知轉發到訊息傳遞環境的能力,請免費嘗試 Inspector。註冊您的帳戶。

或在網站上了解更多:https://inspector.dev

How to monitor Guzzle Http Client – PHP Fast tips

以上是如何監控 Guzzle Http 用戶端 – PHP 快速提示的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn