barbushin/swoole-blackfire

Swoole web-server上运行的PHP应用的Blackfire分析器

2.1.2 2019-03-21 12:48 UTC

This package is auto-updated.

Last update: 2024-08-29 05:06:37 UTC


README

此库通过Swoole web-server和Blackfire实现对PHP应用的性能分析。

特性

  • 透明请求分析
  • 选择性子系统分析
  • 自定义启动/停止分析调用
  • 集成Blackfire Companion

安装

此库作为开发依赖项通过Composer安装

composer require upscale/swoole-blackfire --dev

用法

请求分析

启动分析的最简单方法是全局激活所有请求的分析,从开始到结束。这种设计方法对服务器上运行的应用程序完全透明。不需要更改代码,只需编辑服务器入口点的几行代码。

使用以下方法之一激活所有请求的分析

  • 将服务器中间件包装在分析器装饰器中
    $profiler = new \Upscale\Swoole\Blackfire\Profiler();
    
    $server->on('request', $profiler->wrap(function ($request, $response) {
        $response->header('Content-Type', 'text/plain');
        $response->end(
            'CRC32: ' . hash_file('crc32b', __FILE__) . "\n" .
            'MD5:   ' . md5_file(__FILE__) . "\n" .
            'SHA1:  ' . sha1_file(__FILE__) . "\n"
        );    
    }));
  • 或者,事后安装分析器工具
    $server->on('request', function ($request, $response) {
        $response->header('Content-Type', 'text/plain');
        $response->end(
            'CRC32: ' . hash_file('crc32b', __FILE__) . "\n" .
            'MD5:   ' . md5_file(__FILE__) . "\n" .
            'SHA1:  ' . sha1_file(__FILE__) . "\n"
        );
    });
    
    $profiler = new \Upscale\Swoole\Blackfire\Profiler();
    $profiler->instrument($server);

选择性分析

可以通过将感兴趣代码包装在分析器调用中,来限制分析的范畴。

将需要分析的代码包装在分析器调用中

$profiler = new \Upscale\Swoole\Blackfire\Profiler();

$server->on('request', function ($request, $response) use ($profiler) {
    $response->header('Content-Type', 'text/plain');

    $profiler->inspect($request, $response, function ($request, $response) {
        $response->write('CRC32: ' . hash_file('crc32b', __FILE__) . "\n");    
    });
    
    $response->write('MD5:   ' . md5_file(__FILE__) . "\n");
    $response->write('SHA1:  ' . sha1_file(__FILE__) . "\n");
});

当前,每个请求仅允许一个分析器检查调用。

手动分析

根据应用程序设计和复杂度,可能难以精确地将代码包装在分析器调用中。可以在不同的调用堆栈级别手动放置分析器开始/停止调用,以进一步缩小检查范围。使用这种方法,开发者必须保证调用对称性,并考虑响应填充工作流程。在将响应主体发送到客户端之前,必须停止分析,以便在响应头中发送结果。

将需要分析的代码包围在分析器开始/停止调用中

$profiler = new \Upscale\Swoole\Blackfire\Profiler();

$server->on('request', function ($request, $response) use ($profiler) {
    $response->header('Content-Type', 'text/plain');
    
    $output = 'CRC32: ' . hash_file('crc32b', __FILE__) . "\n";
    
    $profiler->start($request);
    $output .= 'MD5:   ' . md5_file(__FILE__) . "\n";
    $profiler->stop($request, $response);
    
    $output .= 'SHA1:  ' . sha1_file(__FILE__) . "\n"
    
    $response->end($output);
});

当前,每个请求仅允许一对分析器开始/停止调用。

限制

分析在发送响应主体之前隐式停止,并将结果添加到响应头中。目前,每个请求只支持一个由inspect()start/stop()调用启动的分析会话。

贡献

欢迎提交修复和改进的拉取请求!

许可证

版权所有 © Upscale Software。保留所有权利。

根据Apache许可证2.0版许可。