【问题标题】:How to add execution time taken for an API to respond in Lumen framework in the JSON response如何在 JSON 响应中添加 API 在 Lumen 框架中响应所需的执行时间
【发布时间】:2016-04-19 02:53:36
【问题描述】:

我想在响应 JSON 中添加 API 响应所需的时间。目前正在使用 Lumen 框架开发 API。

如果有人可以用最好的方法来指导。不确定我是否必须使用框架提供的任何 Hook,或者只是在路由文件中计算它们。以及如何将其推送到所有 API 响应。

PS:还在学习 Laravel/Lumen 框架。

谢谢, 天美

【问题讨论】:

    标签: laravel lumen


    【解决方案1】:

    在您的 public/index.php 文件中,添加一个常量:

    <?php
    
    /*
    |--------------------------------------------------------------------------
    | Create The Application
    |--------------------------------------------------------------------------
    |
    | First we need to get an application instance. This creates an instance
    | of the application / container and bootstraps the application so it
    | is ready to receive HTTP / Console requests from the environment.
    |
    */
    
    // To calculate your app execution time
    define('LUMEN_START', microtime(true));
    
    $app = require __DIR__.'/../bootstrap/app.php';
    
    /*
    |--------------------------------------------------------------------------
    | Run The Application
    |--------------------------------------------------------------------------
    |
    | Once we have the application, we can handle the incoming request
    | through the kernel, and send the associated response back to
    | the client's browser allowing them to enjoy the creative
    | and wonderful application we have prepared for them.
    |
    */
    
    $app->run();
    

    下一步是创建一个中间件并启用它,以便我们可以操纵我们的响应。在app/Http/Middleware 中创建一个名为MeasureExecutionTime.php 的中间件。

    <?php
    
    namespace App\Http\Middleware;
    
    use Closure;
    
    class MeasureExecutionTime
    {
        /**
         * Handle an incoming request.
         *
         * @param  \Illuminate\Http\Request $request
         * @param  \Closure                 $next
         *
         * @return mixed
         */
        public function handle($request, Closure $next)
        {
            // Get the response
            $response = $next($request);
    
            // Calculate execution time
            $executionTime = microtime() - LUMEN_START;
    
            // I assume you're using valid json in your responses
            // Then I manipulate them below
            $content = json_decode($response->getContent(), true) + [
                'execution_time' => $executionTime,
            ];
    
            // Change the content of your response
            $response->setContent($content);
    
            // Return the response
            return $response;
        }
    }
    

    要在您的应用程序中启用此中间件,请添加:

    $app->middleware([
       App\Http\Middleware\MeasureExecutionTime::class
    ]);
    

    在您的bootstrap/app.php 文件中。所以它会是这样的:

    <?php
    
    require_once __DIR__.'/../vendor/autoload.php';
    
    try {
        (new Dotenv\Dotenv(__DIR__.'/../'))->load();
    } catch (Dotenv\Exception\InvalidPathException $e) {
        // n00p
    }
    
    /*
    |--------------------------------------------------------------------------
    | Create The Application
    |--------------------------------------------------------------------------
    |
    | Here we will load the environment and create the application instance
    | that serves as the central piece of this framework. We'll use this
    | application as an "IoC" container and router for this framework.
    |
    */
    
    $app = new Laravel\Lumen\Application(
        realpath(__DIR__.'/../')
    );
    
    // $app->withFacades();
    
    // $app->withEloquent();
    
    /*
    |--------------------------------------------------------------------------
    | Register Container Bindings
    |--------------------------------------------------------------------------
    |
    | Now we will register a few bindings in the service container. We will
    | register the exception handler and the console kernel. You may add
    | your own bindings here if you like or you can make another file.
    |
    */
    
    $app->singleton(
        Illuminate\Contracts\Debug\ExceptionHandler::class,
        App\Exceptions\Handler::class
    );
    
    $app->singleton(
        Illuminate\Contracts\Console\Kernel::class,
        App\Console\Kernel::class
    );
    
    /*
    |--------------------------------------------------------------------------
    | Register Middleware
    |--------------------------------------------------------------------------
    |
    | Next, we will register the middleware with the application. These can
    | be global middleware that run before and after each request into a
    | route or middleware that'll be assigned to some specific routes.
    |
    */
    
    $app->middleware([
       App\Http\Middleware\MeasureExecutionTime::class
    ]);
    
    // $app->middleware([
    //    App\Http\Middleware\ExampleMiddleware::class
    // ]);
    
    // $app->routeMiddleware([
    //     'auth' => App\Http\Middleware\Authenticate::class,
    // ]);
    
    /*
    |--------------------------------------------------------------------------
    | Register Service Providers
    |--------------------------------------------------------------------------
    |
    | Here we will register all of the application's service providers which
    | are used to bind services into the container. Service providers are
    | totally optional, so you are not required to uncomment this line.
    |
    */
    
    // $app->register(App\Providers\AppServiceProvider::class);
    // $app->register(App\Providers\AuthServiceProvider::class);
    // $app->register(App\Providers\EventServiceProvider::class);
    
    /*
    |--------------------------------------------------------------------------
    | Load The Application Routes
    |--------------------------------------------------------------------------
    |
    | Next we will include the routes file so that they can all be added to
    | the application. This will provide all of the URLs the application
    | can respond to, as well as the controllers that may handle them.
    |
    */
    
    $app->group(['namespace' => 'App\Http\Controllers'], function ($app) {
        require __DIR__.'/../app/Http/routes.php';
    });
    
    return $app;
    

    注意如果您的应用程序中还有其他中间件,您可以在任何其他中间件的END 处添加MeasureExecutionTime 中间件。

    为了进一步研究,我给你一个文档链接:

    1. Middleware
    2. Responses

    更新

    如果您不想在响应正文中添加经过时间,可以将其添加到标题中:

    <?php
    
    namespace App\Http\Middleware;
    
    use Closure;
    
    class MeasureExecutionTime
    {
        /**
         * Handle an incoming request.
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  \Closure  $next
         * @return mixed
         */
        public function handle($request, Closure $next)
        {
            $response = $next($request);
    
            $response->headers->set('X-Elapsed-Time', microtime(true) - LUMEN_START);
    
            return $response;
        }
    }
    

    【讨论】:

    • 感谢您的详细解释。
    • 请注意:您应该将响应时间添加为像 X-Response-Time 这样的标头。这样,您无需对响应进行解码和编码,从而节省时间。它也适用于其他类型的内容:图像、html 等
    【解决方案2】:

    在目录public 中有文件index.php。在那里创建一个变量:

    define('LUMEN_START', microtime());
    

    现在在您的控制器中,您可以只传递一个参数:

    return [
        'response_time' => microtime() - LUMEN_START
    ];
    

    它将测量从开始(public/index.php 是服务器运行的第一个文件)到响应的时间。

    【讨论】:

    • 我们应该在每个响应/控制器中添加'response_time' =&gt; microtime() - LUMEN_START。我更喜欢使用Middleware 作为全局解决方案。请在下面阅读我的回答。
    • 为简单起见,这很好,但可能会与中间件解决方案一起使用,因此我不必为每个响应单独添加。
    【解决方案3】:

    我使用 Lumen 5.3 并想返回 JsonResponse。因此,我不得不稍微修改一下 Alfa 的中间件解决方案:

    代替

    // Change the content of your response
    $response->setContent($content);
    

    我用

    // Change the content of your response
    $response->setData($content);
    

    不确定这是否与 JsonResponse 或 Laravel/Lumen 版本有关,但它对我有用。

    【讨论】:

      猜你喜欢
      • 2014-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-29
      • 1970-01-01
      • 1970-01-01
      • 2018-05-24
      • 1970-01-01
      相关资源
      最近更新 更多