」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 如何監控 Guzzle Http 用戶端 – PHP 快速提示

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

發佈於2024-11-08
瀏覽:282

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

版本聲明 本文轉載於:https://dev.to/inspector/how-to-monitor-guzzle-http-client-php-fast-tips-4ijg?1如有侵犯,請聯絡[email protected]刪除
最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3