”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 如何监控 Guzzle Http 客户端 – PHP 快速提示

如何监控 Guzzle Http 客户端 – PHP 快速提示

发布于2024-11-08
浏览:744

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]删除
最新教程 更多>
  • Java数组中元素位置查找技巧
    Java数组中元素位置查找技巧
    在Java数组中检索元素的位置 利用Java的反射API将数组转换为列表中,允许您使用indexof方法。 (primitives)(链接到Mishax的解决方案) 用于排序阵列的数组此方法此方法返回元素的索引,如果发现了元素的索引,或一个负值,指示应放置元素的插入点。
    编程 发布于2025-07-08
  • 如何使用Depimal.parse()中的指数表示法中的数字?
    如何使用Depimal.parse()中的指数表示法中的数字?
    在尝试使用Decimal.parse(“ 1.2345e-02”中的指数符号表示法表示的字符串时,您可能会遇到错误。这是因为默认解析方法无法识别指数符号。 成功解析这样的字符串,您需要明确指定它代表浮点数。您可以使用numbersTyles.Float样式进行此操作,如下所示:[&& && && ...
    编程 发布于2025-07-08
  • 如何实时捕获和流媒体以进行聊天机器人命令执行?
    如何实时捕获和流媒体以进行聊天机器人命令执行?
    在开发能够执行命令的chatbots的领域中,实时从命令执行实时捕获Stdout,一个常见的需求是能够检索和显示标准输出(stdout)在cath cath cant cant cant cant cant cant cant cant interfaces in Chate cant inter...
    编程 发布于2025-07-08
  • 为什么我的CSS背景图像出现?
    为什么我的CSS背景图像出现?
    故障排除:CSS背景图像未出现 ,您的背景图像尽管遵循教程说明,但您的背景图像仍未加载。图像和样式表位于相同的目录中,但背景仍然是空白的白色帆布。而不是不弃用的,您已经使用了CSS样式: bockent {背景:封闭图像文件名:背景图:url(nickcage.jpg); 如果您的html,css...
    编程 发布于2025-07-08
  • 如何使用Java.net.urlConnection和Multipart/form-data编码使用其他参数上传文件?
    如何使用Java.net.urlConnection和Multipart/form-data编码使用其他参数上传文件?
    使用http request 上传文件上传到http server,同时也提交其他参数,java.net.net.urlconnection and Multipart/form-data Encoding是普遍的。 Here's a breakdown of the process:Mu...
    编程 发布于2025-07-08
  • 如何使用node-mysql在单个查询中执行多个SQL语句?
    如何使用node-mysql在单个查询中执行多个SQL语句?
    Multi-Statement Query Support in Node-MySQLIn Node.js, the question arises when executing multiple SQL statements in a single query using the node-mys...
    编程 发布于2025-07-08
  • 解决Spring Security 4.1及以上版本CORS问题指南
    解决Spring Security 4.1及以上版本CORS问题指南
    弹簧安全性cors filter:故障排除常见问题 在将Spring Security集成到现有项目中时,您可能会遇到与CORS相关的错误,如果像“访问Control-allo-allow-Origin”之类的标头,则无法设置在响应中。为了解决此问题,您可以实现自定义过滤器,例如代码段中的MyFi...
    编程 发布于2025-07-08
  • 大批
    大批
    [2 数组是对象,因此它们在JS中也具有方法。 切片(开始):在新数组中提取部分数组,而无需突变原始数组。 令ARR = ['a','b','c','d','e']; // USECASE:提取直到索引作...
    编程 发布于2025-07-08
  • 如何使用FormData()处理多个文件上传?
    如何使用FormData()处理多个文件上传?
    )处理多个文件输入时,通常需要处理多个文件上传时,通常是必要的。 The fd.append("fileToUpload[]", files[x]); method can be used for this purpose, allowing you to send multi...
    编程 发布于2025-07-08
  • 为什么HTML无法打印页码及解决方案
    为什么HTML无法打印页码及解决方案
    无法在html页面上打印页码? @page规则在@Media内部和外部都无济于事。 HTML:Customization:@page { margin: 10%; @top-center { font-family: sans-serif; font-weight: bo...
    编程 发布于2025-07-08
  • 反射动态实现Go接口用于RPC方法探索
    反射动态实现Go接口用于RPC方法探索
    在GO 使用反射来实现定义RPC式方法的界面。例如,考虑一个接口,例如:键入myService接口{ 登录(用户名,密码字符串)(sessionId int,错误错误) helloworld(sessionid int)(hi String,错误错误) } 替代方案而不是依靠反射...
    编程 发布于2025-07-08
  • 如何在GO编译器中自定义编译优化?
    如何在GO编译器中自定义编译优化?
    在GO编译器中自定义编译优化 GO中的默认编译过程遵循特定的优化策略。 However, users may need to adjust these optimizations for specific requirements.Optimization Control in Go Compi...
    编程 发布于2025-07-08
  • FastAPI自定义404页面创建指南
    FastAPI自定义404页面创建指南
    response = await call_next(request) if response.status_code == 404: return RedirectResponse("https://fastapi.tiangolo.com") else: ...
    编程 发布于2025-07-08
  • 如何在鼠标单击时编程选择DIV中的所有文本?
    如何在鼠标单击时编程选择DIV中的所有文本?
    在鼠标上选择div文本单击带有文本内容,用户如何使用单个鼠标单击单击div中的整个文本?这允许用户轻松拖放所选的文本或直接复制它。 在单个鼠标上单击的div元素中选择文本,您可以使用以下Javascript函数: function selecttext(canduterid){ if(do...
    编程 发布于2025-07-08
  • 如何在无序集合中为元组实现通用哈希功能?
    如何在无序集合中为元组实现通用哈希功能?
    在未订购的集合中的元素要纠正此问题,一种方法是手动为特定元组类型定义哈希函数,例如: template template template 。 struct std :: hash { size_t operator()(std :: tuple const&tuple)const {...
    编程 发布于2025-07-08

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3