Laravel 11でヘルスチェッㇰ機能が搭載されました!routesもControllersも不要なのがいいですね(≧∇≦)b
Laravel 11のインストール
Laravel 11はPHP8.2以上が必要です
composer create-project laravel/laravel:^11.0 example-app
cd example-app
php artisan serve
http://localhost:8000/up でヘルスチェックを実行します。
ヘルスチェッㇰの実行時間が94msと表示されています!
ヘルスチェックの処理追加
php artisan make:listener HealthCheck --event '\Illuminate\Foundation\Events\DiagnosingHealth'
Laravel 11では、EventServiceProviderにイベントを登録する必要はありません!!
2回に1回ヘルスチェッㇰが失敗するようにしてみましょう
app/Listeners/HealthCheck.php
<?php
namespace App\Listeners;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Events\DiagnosingHealth;
use Illuminate\Queue\InteractsWithQueue;
class HealthCheck
{
/**
* Create the event listener.
*/
public function __construct()
{
//
}
/**
* Handle the event.
*/
public function handle(DiagnosingHealth $event): void
{
// do health check
$healthCheckFailed = time() % 2;
if ($healthCheckFailed) abort(503);
}
}
クラスファイル作りたくない場合
bootメソッドに追記
app/Providers/AppServiceProvider.php
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*/
public function register(): void
{
//
}
/**
* Bootstrap any application services.
*/
public function boot(): void
{
\Illuminate\Support\Facades\Event::listen(function (\Illuminate\Foundation\Events\DiagnosingHealth $event) {
// do health check
$healthCheckFailed = time() % 2;
if ($healthCheckFailed) abort(503);
});
}
}
パラメータでヘルスチェックの処理を変更したい場合
http://localhost:8000/up?check_target=database にアクセスすると処理をカスタマイズできます。
app/Listeners/HealthCheck.php
<?php
namespace App\Listeners;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Events\DiagnosingHealth;
use Illuminate\Queue\InteractsWithQueue;
class HealthCheck
{
/**
* Create the event listener.
*/
public function __construct()
{
//
}
/**
* Handle the event.
*/
public function handle(DiagnosingHealth $event): void
{
if (request('check_target') === 'database') {
echo 'checking database';
// do health check
$healthCheckFailed = time() % 3;
if ($healthCheckFailed) abort(503);
} else {
// do health check
$healthCheckFailed = time() % 2;
if ($healthCheckFailed) abort(503);
}
}
}
JSONを返したい場合
app/Listeners/HealthCheck.php
<?php
namespace App\Listeners;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Events\DiagnosingHealth;
use Illuminate\Queue\InteractsWithQueue;
class HealthCheck
{
/**
* Create the event listener.
*/
public function __construct()
{
//
}
/**
* Handle the event.
*/
public function handle(DiagnosingHealth $event): void
{
abort(response()->json(['message' => 'error!'], 400));
}
}