Readouble

Laravel 5.8 Laravel Horizon

イントロダクションIntroduction

Horizon(水平線、展望)は、Laravelで動作するRedisキューのための、美しいダッシュボードとコード駆動による設定を提供します。Horizonにより、ジョブのスループット、ランタイム、実行の失敗など、キューシステムのキーメトリックを簡単に監視できます。Horizon provides a beautiful dashboard and code-driven configuration for your Laravel powered Redis queues. Horizon allows you to easily monitor key metrics of your queue system such as job throughput, runtime, and job failures.

一つのシンプルな設定ファイルにすべてのワーカ設定を保存するため、チーム全体がコラボレート可能なソースコントロール下に、設定を保持できます。All of your worker configuration is stored in a single, simple configuration file, allowing your configuration to stay in source control where your entire team can collaborate.

インストールInstallation

Note: note queue設定ファイルで、redisをキューコネクションへ確実に指定してください。{note} You should ensure that your queue connection is set to redis in your queue configuration file.

Composerを使い、LaravelプロジェクトにHorizonをインストールします。You may use Composer to install Horizon into your Laravel project:

composer require laravel/horizon

Horizonをインストールしたら、horizon:install Artisanコマンドを使用し、アセットを公開します。After installing Horizon, publish its assets using the horizon:install Artisan command:

php artisan horizon:install

Laravelが失敗したキュー済みのジョブ:を保存するために使用する、failed_jobsを生成することもできます。You should also create the failed_jobs table which Laravel will use to store any failed queue jobs[/docs/{{version}}/queues#dealing-with-failed-jobs]:

php artisan queue:failed-table

php artisan migrate

HorizonのアップグレードUpgrading Horizon

Horizonの新しいメジャーバージョンへアップグレードする場合は、アップグレードガイドを注意深く読み込むことが重要です。When upgrading to a new major version of Horizon, it's important that you carefully review the upgrade guide[https://github.com/laravel/horizon/blob/master/UPGRADE.md].

付け加えて、Horizonのアセットを再公開も必要です。In addition, you should re-publish Horizon's assets:

php artisan horizon:assets

設定Configuration

Horizonのアセットを公開すると、config/horizon.phpに一番重要な設定ファイルが設置されます。この設定ファイルにより、ワーカのオプションを設置します。各オプションにはその目的が説明されていますので、ファイル全体をしっかりと確認してください。After publishing Horizon's assets, its primary configuration file will be located at config/horizon.php. This configuration file allows you to configure your worker options and each configuration option includes a description of its purpose, so be sure to thoroughly explore this file.

Note: note Horizonを実行する予定の環境ごとのエントリーをhorizon設定ファイルのenvironments部分へ確実に含めてください。{note} You should ensure that the environments portion of your horizon configuration file contains an entry for each environment on which you plan to run Horizon.

バランスオプションBalance Options

Horizonでは3つのバランシング戦略が選択できます。simpleautofalseです。simple戦略は設定ファイルのデフォルトで、投入されたジョブをプロセス間に均等に割り当てます。Horizon allows you to choose from three balancing strategies: simple, auto, and false. The simple strategy, which is the configuration file's default, splits incoming jobs evenly between processes:

'balance' => 'simple',

auto戦略は、現在のキュー負荷に基づき、それぞれのキューへ割り当てるワーカプロセス数を調整します。たとえば、notificationsキューに1,000ジョブが溜まっており、一方でrenderキューが空の場合、Horizonは空になるまでnotificationsキューにより多くのワーカを割り当てます。balanceオプションへfalseを設定すると、設定にリストした順番でキューが処理される、Laravelデフォルトの振る舞いが使われます。The auto strategy adjusts the number of worker processes per queue based on the current workload of the queue. For example, if your notifications queue has 1,000 waiting jobs while your render queue is empty, Horizon will allocate more workers to your notifications queue until it is empty. When the balance option is set to false, the default Laravel behavior will be used, which processes queues in the order they are listed in your configuration.

auto戦略を使う場合、Horizonがスケールアップ/ダウンで使用すべきプロセス数の最小値と最大値をコントロールするために、minProcessesmaxProcesses設定オプションを定義してください。When using the auto strategy, you may define the minProcesses and maxProcesses configuration options to control the minimum and maximum number of processes Horizon should scale up and down to:

'environments' => [
    'production' => [
        'supervisor-1' => [
            'connection' => 'redis',
            'queue' => ['default'],
            'balance' => 'auto',
            'minProcesses' => 1,
            'maxProcesses' => 10,
            'tries' => 3,
        ],
    ],
],

ジョブの整理Job Trimming

horizon設定ファイルで、現在がどのくらいの長さなのか、それと失敗したジョブをどのくらい保持しているかを分数で設定できます。デフォルトでは、現在のジョブは1時間、失敗したジョブは1週間保持されます。The horizon configuration file allows you to configure how long recent and failed jobs should be persisted (in minutes). By default, recent jobs are kept for one hour while failed jobs are kept for a week:

'trim' => [
    'recent' => 60,
    'failed' => 10080,
],

ダッシュボードの認可Dashboard Authorization

Horizonは、/horizonでダッシュボードを表示します。デフォルトではlocal環境でのみ、このダッシュボードへアクセスできます。app/Providers/HorizonServiceProvider.phpファイルの中に、gateメソッドが存在しています。この認可ゲートはlocal以外の環境における、Horizonへのアクセスをコントロールします。Horizonへのアクセスを必要に応じ制限するために、自由に変更してください。Horizon exposes a dashboard at /horizon. By default, you will only be able to access this dashboard in the local environment. Within your app/Providers/HorizonServiceProvider.php file, there is a gate method. This authorization gate controls access to Horizon in non-local environments. You are free to modify this gate as needed to restrict access to your Horizon installation:

/**
 * Horizonゲートの登録
 *
 * このゲートはlocal以外の環境で、誰がHorizonへアクセスできるか決定している。
 *
 * @return void
 */
protected function gate()
{
    Gate::define('viewHorizon', function ($user) {
        return in_array($user->email, [
            'taylor@laravel.com',
        ]);
    });
}

Note: note LaravelはGateへ自動的に認証済みユーザーを依存注入します。IP制限のような別のHorizonセキュリティ方法をアプリケーションで提供する場合は、Horizonユーザーは「ログイン」している必要はいらないでしょう。そのため、上記のfunction ($user)function ($user = null)へ変更し、Laravelに認証は必要ないと強制的に知らせてください。{note} Remember that Laravel injects the authenticated user to the Gate automatically. If your app is providing Horizon security via another method, such as IP restrictions, then your Horizon users may not need to "login". Therefore, you will need to change function ($user) above to function ($user = null) to force Laravel to not require authentication.

Horizonの実行Running Horizon

config/horizon.php設定ファイルでワーカの設定を済ませたら、horizon Artisanコマンドを使用し、Horizonを使用開始します。このコマンド一つで、設定済みのワーカ全部を起動できます。Once you have configured your workers in the config/horizon.php configuration file, you may start Horizon using the horizon Artisan command. This single command will start all of your configured workers:

php artisan horizon

Horizonプロセスをhorizon:pause Artisanコマンドで一時停止したり、horizon:continueコマンドで処理を続行したりできます。You may pause the Horizon process and instruct it to continue processing jobs using the horizon:pause and horizon:continue Artisan commands:

php artisan horizon:pause

php artisan horizon:continue

マシン上のマスタHorizonプロセスを穏やかに終了させたい場合は、horizon:terminate Artisanコマンドを使用します。現在処理中のジョブが完了した後に、Horizonは停止します。You may gracefully terminate the master Horizon process on your machine using the horizon:terminate Artisan command. Any jobs that Horizon is currently processing will be completed and then Horizon will exit:

php artisan horizon:terminate

HorizonのデプロイDeploying Horizon

Horizonを実働サーバにデプロイする場合、php artisan horizonコマンドをプロセスモニタで監視し、予期せず終了した場合には再起動をかけるように設定する必要があります。サーバに新しいコードをデプロイしたときに、Horizonプロセスを停止指示する必要があります。その結果、プロセスモニタにより再起動され、コードの変更が反映されます。If you are deploying Horizon to a live server, you should configure a process monitor to monitor the php artisan horizon command and restart it if it quits unexpectedly. When deploying fresh code to your server, you will need to instruct the master Horizon process to terminate so it can be restarted by your process monitor and receive your code changes.

Supervisor設定Supervisor Configuration

horizonプロセスを管理するため、Supervisorプロセスモニタを使用する場合は、以下の設定ファイルが利用できるでしょう。If you are using the Supervisor process monitor to manage your horizon process, the following configuration file should suffice:

[program:horizon]
process_name=%(program_name)s
command=php /home/forge/app.com/artisan horizon
autostart=true
autorestart=true
user=forge
redirect_stderr=true
stdout_logfile=/home/forge/app.com/horizon.log

lightbulb">Tip!! サーバ管理に自信がない場合は、Laravel Forgeの利用を検討してください。ForgeはHorizonと共に、モダンで堅牢なLaravelアプリケーションに必要なすべてをPHP7以上のサーバにプロビションします。{tip} If you are uncomfortable managing your own servers, consider using Laravel Forge[https://forge.laravel.com]. Forge provisions PHP 7 servers with everything you need to run modern, robust Laravel applications with Horizon.

タグTags

Horizonでは、mailableやイベントブロードキャスト、通知、キューイベントリスナなどを含むジョブに「タグ」を割り付けられます。実際、ジョブに割り付けられたEloquentモデルに基づいて、ほとんどのジョブでは賢く自動的にHorizonがタグ付けします。例として、以下のジョブをご覧ください。Horizon allows you to assign “tags” to jobs, including mailables, event broadcasts, notifications, and queued event listeners. In fact, Horizon will intelligently and automatically tag most jobs depending on the Eloquent models that are attached to the job. For example, take a look at the following job:

<?php

namespace App\Jobs;

use App\Video;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

class RenderVideo implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * ビデオインスタンス
     *
     * @var \App\Video
     */
    public $video;

    /**
     * 新しいジョブインスタンスの生成
     *
     * @param  \App\Video  $video
     * @return void
     */
    public function __construct(Video $video)
    {
        $this->video = $video;
    }

    /**
     * ジョブの実行
     *
     * @return void
     */
    public function handle()
    {
        //
    }
}

id1App\Videoインスタンスを持つジョブがキューされると、自動的にApp\Video:1タグが付けられます。HorizonはジョブのプロパティがEloquentモデルであるかを確認するからです。Eloquentモデルが見つかると、Horizonはモデルのクラス名と主キーを使用し、賢くタグ付けします。If this job is queued with an App\Video instance that has an id of 1, it will automatically receive the tag App\Video:1. This is because Horizon will examine the job's properties for any Eloquent models. If Eloquent models are found, Horizon will intelligently tag the job using the model's class name and primary key:

$video = App\Video::find(1);

App\Jobs\RenderVideo::dispatch($video);

手動のタグ付けManually Tagging

queueableオブジェクトのタグを任意に定義したい場合は、そのクラスでtagsメソッドを定義してください。If you would like to manually define the tags for one of your queueable objects, you may define a tags method on the class:

class RenderVideo implements ShouldQueue
{
    /**
     * ジョブに割り付けるタグの取得
     *
     * @return array
     */
    public function tags()
    {
        return ['render', 'video:'.$this->video->id];
    }
}

通知Notifications

Note: Horizonから、SlackかSMS通知を送る設定を行う場合は、対応するドライバの動作要件についても、確認する必要があります。Note: When configuring Horizon to send Slack or SMS notifications, you should review the prerequisites for the relevant notification driver[/docs/{{version}}/notifications].

あるキューが長時間waitしている時に、通知を受け取りたい場合は、Horizon::routeSlackNotificationsToや、Horizon::routeSlackNotificationsToHorizon::routeSmsNotificationsToメソッドを利用してください。これらのメソッドは、HorizonServiceProviderから呼び出すのが良いでしょう。If you would like to be notified when one of your queues has a long wait time, you may use the Horizon::routeMailNotificationsTo, Horizon::routeSlackNotificationsTo, and Horizon::routeSmsNotificationsTo methods. You may call these methods from your application's HorizonServiceProvider:

Horizon::routeMailNotificationsTo('example@example.com');
Horizon::routeSlackNotificationsTo('slack-webhook-url', '#channel');
Horizon::routeSmsNotificationsTo('15556667777');

通知wait時間のシュレッドホールド設定Configuring Notification Wait Time Thresholds

何秒を「長時間」と考えるかは、config/horizon.php設定ファイルで指定できます。このファイルのwaits設定オプションで、接続/キューの組み合わせごとに、長時間と判定するシュレッドホールドをコントロールできます。You may configure how many seconds are considered a "long wait" within your config/horizon.php configuration file. The waits configuration option within this file allows you to control the long wait threshold for each connection / queue combination:

'waits' => [
    'redis:default' => 60,
],

メトリックスMetrics

Horizonはジョブとキューの待ち時間とスループットの情報をダッシュボードに表示します。このダッシュボードを表示するために、アプリケーションのスケジューラで、5分毎にsnapshot Artisanコマンドを実行する設定を行う必要があります。Horizon includes a metrics dashboard which provides information on your job and queue wait times and throughput. In order to populate this dashboard, you should configure Horizon's snapshot Artisan command to run every five minutes via your application's scheduler[/docs/{{version}}/scheduling]:

/**
 * アプリケーションのコマンドスケジュールの定義
 *
 * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
 * @return void
 */
protected function schedule(Schedule $schedule)
{
    $schedule->command('horizon:snapshot')->everyFiveMinutes();
}

章選択

設定

明暗テーマ
light_mode
dark_mode
brightness_auto システム設定に合わせる
テーマ選択
photo_size_select_actual デフォルト
photo_size_select_actual モノクローム(白黒)
photo_size_select_actual Solarized風
photo_size_select_actual GitHub風(青ベース)
photo_size_select_actual Viva(黄緑ベース)
photo_size_select_actual Happy(紫ベース)
photo_size_select_actual Mint(緑ベース)
コードハイライトテーマ選択

明暗テーマごとに、コードハイライトのテーマを指定できます。

テーマ配色確認
スクリーン表示幅
640px
80%
90%
100%

768px以上の幅があるときのドキュメント部分表示幅です。

インデント
無し
1rem
2rem
3rem
原文確認
原文を全行表示
原文を一行ずつ表示
使用しない

※ 段落末のEボタンへカーソルオンで原文をPopupします。

Diff表示形式
色分けのみで区別
行頭の±で区別
削除線と追記で区別

※ [tl!…]形式の挿入削除行の表示形式です。

Pagination和文
ペジネーション
ペギネーション
ページネーション
ページ付け
Scaffold和文
スカフォールド
スキャフォールド
型枠生成
本文フォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

コードフォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

保存内容リセット

localStrageに保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作