laravel fastcgi_finish_request Middleware

fastcgi_finish_request()php-fpm提供的可提前結束連接響應數據並在後端繼續執行任務的函數,爲了執行耗時較長的任務或提高響應速度的時候,我們可以使用這個函數來簡單實現,當然,更好的方式是使用隊列。

在Laravel中,發送響應就會調用fastcgi_finish_request()(若存在),之後會調用terminate()方法,該方法會依次執行註冊的中間件中的terminate()方法。

文檔中使用 Terminable Middleware 是需要註冊全局中間件,但實際中,我們可能只需要對部分接口進行提前響應,然後處理後續邏輯(數據庫、日誌...)。但通過源碼 https://github.com/laravel/framework/blob/5.4/src/Illuminate/Foundation/Http/Kernel.php#L202 可以看到,Laravel的routeMiddleware實際上是支持 Terminable Middleware 的.

 

什麼是 Terminable 中間件
這裏引用其他地方的一句話:

有時候中間件需要在 HTTP 的響應已經發送到瀏覽器之後去做點事。比如在 Laravel 裏包含的 session 這個中間件,它會在響應發送到瀏覽器之後,把 session 數據寫入到存儲裏面。要實現這個功能,你可以把中間件定義成 terminable 。

原來是在響應之後再做的事情,保存 session 的步驟是一次性在最後進行,這就是 Laravel Session 保存的機制,以及 terminate 中間件的用法。

具體用法如下

namespace App\Http\Middleware;

use App\Models\PrizeLog;
use App\Services\DrawService;
use App\Services\PrizeLogService;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class SeedPrize

{
    public function handle($request, $next, ...$scopes)
    {
        return $next($request);
    }

 */
public function terminate($request, $response)
{
      //執行響應後邏輯
}

}

 

參考:

https://www.cnblogs.com/buff/p/laravel_terminate_middleware.html

https://learnku.com/laravel/t/3000/laravel-session-preservation-mechanism-and-terminate-middleware

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章