Laravel horizon что это
Horizon предоставляет прекрасную панель мониторинга и управляемую кодом конфигурацию для ваших очередей Redis с питанием от Laravel. Horizon позволяет вам легко отслеживать ключевые показатели вашей системы очередей, такие как пропускная способность, время выполнения и сбои заданий.
Вся ваша рабочая конфигурация хранится в одном простом файле конфигурации, что позволяет вашей конфигурации оставаться в системе контроля версий, где вся ваша команда может сотрудничать.
Метрика
Horizon включает панель показателей, которая предоставляет информацию о вашей работе, времени ожидания и пропускной способности очереди. Чтобы заполнить эту панель, вы должны настроить snapshot команду Horizon Artisan для запуска каждые пять минут через планировщиквашего приложения :
Notifications
When configuring Horizon to send Slack or SMS notifications, you should review the prerequisites for the relevant notification channel.
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 the boot method of your application's App\Providers\HorizonServiceProvider :
Configuring Notification Wait Time Thresholds
You may configure how many seconds are considered a "long wait" within your application's 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:
Installation
Due to its usage of async process signals, Horizon requires PHP 7.1+. Secondly, you should ensure that your queue driver is set to redis in your queue configuration file.
You may use Composer to install Horizon into your Laravel project:
After installing Horizon, publish its assets using the vendor:publish Artisan command:
Configuration
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.
Balance Options
Horizon allows you to choose from three balancing strategies: simple , auto , and false . The simple strategy, which is the default, splits incoming jobs evenly between processes:
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.
Dashboard Authentication
Horizon exposes a dashboard at /horizon . By default, you will only be able to access this dashboard in the local environment. To define a more specific access policy for the dashboard, you should use the Horizon::auth method. The auth method accepts a callback which should return true or false , indicating whether the user should have access to the Horizon dashboard. Typically, you should call Horizon::auth in the boot method of your AppServiceProvider :
Running 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:
You may pause the Horizon process and instruct it to continue processing jobs using the horizon:pause and horizon:continue Artisan commands:
You may check the current status of the Horizon process using the horizon:status Artisan command:
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:
Deploying 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.
Installing Supervisor
Supervisor is a process monitor for the Linux operating system, and will automatically restart your horizon process if it fails. To install Supervisor on Ubuntu, you may use the following command:
If configuring Supervisor yourself sounds overwhelming, consider using Laravel Forge, which will automatically install and configure Supervisor for your Laravel projects.
Supervisor Configuration
Supervisor configuration files are typically stored in the /etc/supervisor/conf.d directory. Within this directory, you may create any number of configuration files that instruct supervisor how your processes should be monitored. For example, let's create a horizon.conf file that starts and monitors a horizon process:
You should ensure that the value of stopwaitsecs is greater than the number of seconds consumed by your longest running job. Otherwise, Supervisor may kill the job before it is finished processing.
Starting Supervisor
Once the configuration file has been created, you may update the Supervisor configuration and start the processes using the following commands:
For more information on Supervisor, consult the Supervisor documentation.
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:
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:
Manually Tagging
If you would like to manually define the tags for one of your queueable objects, you may define a tags method on the class:
Deleting Failed Jobs
If you would like to delete a failed job, you may use the horizon:forget command. The horizon:forget command accepts the ID or UUID of the failed job as its only argument:
Laravel 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.
Notifications
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 AppServiceProvider :
Configuring Notification Wait Time Thresholds
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:
Metrics
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:
Бегущий Horizon
После того, как вы сконфигурировали своих работников в файле конфигурации, вы можете запустить Horizon с помощью команды Artisan. Эта единственная команда запустит всех ваших настроенных рабочих: config/horizon.php horizon
Вы можете приостановить процесс Horizon и дать ему команду продолжить обработку заданий, используя команды и Artisan: horizon:pause horizon:continue
Вы можете корректно завершить основной процесс Horizon на своем компьютере с помощью команды Artisan. Все задания, которые в данный момент обрабатывает Horizon, будут завершены, а затем Horizon завершит работу: horizon:terminate
Развертывание Horizon
Если вы развертываете Horizon на работающем сервере, вы должны настроить монитор процесса для мониторинга php artisan horizon команды и перезапустить ее, если она неожиданно завершит работу. При развертывании свежего кода на вашем сервере вам нужно будет дать команду основному процессу Horizon завершить его, чтобы он мог быть перезапущен вашим монитором процесса и получить изменения кода.
Конфигурация супервизора
Если вы используете монитор процессов Supervisor для управления вашим horizon процессом, вам может подойти следующий файл конфигурации:
Если вам неудобно управлять своими серверами, подумайте об использовании Laravel Forge . Forge предоставляет серверы PHP 7+ со всем необходимым для запуска современных надежных приложений Laravel с Horizon.
Если это задание поставлено в очередь с экземпляром, имеющим о , оно автоматически получит тег . Это связано с тем, что Horizon проверит свойства задания для любых моделей Eloquent. Если найдены модели Eloquent, Horizon интеллектуально пометит задание, используя имя класса модели и первичный ключ: App\Video id 1 App\Video:1
Маркировка вручную
Если вы хотите вручную определить теги для одного из объектов в очереди, вы можете определить tags метод для класса:
Metrics
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:
Laravel 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.
Upgrading Horizon
When upgrading to a new major version of Horizon, it's important that you carefully review the upgrade guide. In addition, when upgrading to any new Horizon version, you should re-publish Horizon's assets:
To keep the assets up-to-date and avoid issues in future updates, you may add the horizon:publish command to the post-update-cmd scripts in your application's composer.json file:
Clearing Jobs From Queues
If you would like to delete all jobs from your application's default queue, you may do so using the horizon:clear Artisan command:
Монтаж
Вы должны убедиться, что ваш драйвер очереди установлен redis в вашем queue файле конфигурации.
Вы можете использовать Composer для установки Horizon в ваш проект Laravel:
После установки Horizon опубликуйте его ресурсы с помощью команды Artisan: horizon:install
Вам также следует создать failed_jobs таблицу, которую Laravel будет использовать для хранения любых неудачных заданий очереди :
Обновление Horizon
При обновлении до новой основной версии Horizon важно внимательно изучить руководство по обновлению .
Кроме того, вы должны повторно опубликовать активы Horizon:
Конфигурация
После публикации ресурсов Horizon его основной файл конфигурации будет находиться по адресу . Этот файл конфигурации позволяет вам сконфигурировать ваши рабочие параметры, и каждый параметр конфигурации содержит описание его назначения, поэтому обязательно внимательно изучите этот файл. config/horizon.php
Вы должны убедиться, что environments часть вашего horizon файла конфигурации содержит запись для каждой среды, в которой вы планируете запускать Horizon.
Варианты баланса
Horizon позволяет выбрать один из трех уравновешивающих стратегий: simple , auto , и false . simple Стратегия, которая по умолчанию файла конфигурации, расщепляет поступающие задания равномерно между процессами:
auto Стратегия регулирует количество рабочих процессов в очередь на основе текущей рабочей нагрузки очереди. Например, если в вашей notifications очереди 1000 ожидающих заданий, а ваша render очередь пуста, Horizon будет выделять больше рабочих в вашу notifications очередь, пока она не станет пустой. Если для этого balance параметра установлено значение false , будет использоваться поведение Laravel по умолчанию, которое обрабатывает очереди в порядке, указанном в вашей конфигурации.
Обрезка работы
horizon Файл конфигурации позволяет настроить , как долго в последнее время и не рабочие места должны быть сохранены (в минутах). По умолчанию последние задания сохраняются в течение одного часа, а невыполненные задания - в течение недели:
Авторизация панели инструментов
Горизонт выставляет приборную панель в /horizon . По умолчанию вы сможете получить доступ к этой панели только в этой local среде. В вашем файле есть метод. Этот шлюз авторизации контролирует доступ к Horizon в нелокальных средах. Вы можете изменять эти ворота по мере необходимости, чтобы ограничить доступ к вашей установке Horizon: app/Providers/HorizonServiceProvider.php gate
Installation
Laravel Horizon requires that you use Redis to power your queue. Therefore, you should ensure that your queue connection is set to redis in your application's config/queue.php configuration file.
You may install Horizon into your project using the Composer package manager:
After installing Horizon, publish its assets using the horizon:install Artisan command:
Configuration
After publishing Horizon's assets, its primary configuration file will be located at config/horizon.php . This configuration file allows you to configure the queue worker options for your application. Each configuration option includes a description of its purpose, so be sure to thoroughly explore this file.
Environments
After installation, the primary Horizon configuration option that you should familiarize yourself with is the environments configuration option. This configuration option is an array of environments that your application runs on and defines the worker process options for each environment. By default, this entry contains a production and local environment. However, you are free to add more environments as needed:
When you start Horizon, it will use the worker process configuration options for the environment that your application is running on. Typically, the environment is determined by the value of the APP_ENV environment variable. For example, the default local Horizon environment is configured to start three worker processes and automatically balance the number of worker processes assigned to each queue. The default production environment is configured to start a maximum of 10 worker processes and automatically balance the number of worker processes assigned to each queue.
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.
Supervisors
As you can see in Horizon's default configuration file. Each environment can contain one or more "supervisors". By default, the configuration file defines this supervisor as supervisor-1 ; however, you are free to name your supervisors whatever you want. Each supervisor is essentially responsible for "supervising" a group of worker processes and takes care of balancing worker processes across queues.
You may add additional supervisors to a given environment if you would like to define a new group of worker processes that should run in that environment. You may choose to do this if you would like to define a different balancing strategy or worker process count for a given queue used by your application.
Default Values
Within Horizon's default configuration file, you will notice a defaults configuration option. This configuration option specifies the default values for your application's supervisors. The supervisor's default configuration values will be merged into the supervisor's configuration for each environment, allowing you to avoid unnecessary repetition when defining your supervisors.
Balancing Strategies
Unlike Laravel's default queue system, Horizon allows you to choose from three worker balancing strategies: simple , auto , and false . The simple strategy, which is the configuration file's default, splits incoming jobs evenly between worker processes:
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 pending jobs while your render queue is empty, Horizon will allocate more workers to your notifications queue until the queue is empty.
When using the auto strategy, you may define the minProcesses and maxProcesses configuration options to control the minimum and the maximum number of worker processes Horizon should scale up and down to:
The balanceMaxShift and balanceCooldown configuration values to determine how quickly Horizon will scale to meet worker demand. In the example above, a maximum of one new process will be created or destroyed every three seconds. You are free to tweak these values as necessary based on your application's needs.
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.
Dashboard Authorization
Horizon exposes a dashboard at the /horizon URI. By default, you will only be able to access this dashboard in the local environment. However, within your app/Providers/HorizonServiceProvider.php file, there is an authorization gate definition. 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:
Alternative Authentication Strategies
Remember that Laravel automatically injects the authenticated user into the gate closure. If your application 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) closure signature above to function ($user = null) in order to force Laravel to not require authentication.
Installation
You should ensure that your queue connection is set to redis in your queue configuration file.
You may use Composer to install Horizon into your Laravel project:
After installing Horizon, publish its assets using the horizon:install Artisan command:
Configuration
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.
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 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:
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.
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. The minProcesses value specifies the minimum number of processes per queue, while the maxProcesses value specifies the maximum number of processes across all queues:
Job Trimming
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:
Dashboard Authorization
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:
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.
Laravel Horizon
Before digging into Laravel Horizon, you should familiarize yourself with Laravel's base queue services. Horizon augments Laravel's queue with additional features that may be confusing if you are not already familiar with the basic queue features offered by Laravel.
Laravel 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.
When using Horizon, all of your queue worker configuration is stored in a single, simple configuration file. By defining your application's worker configuration in a version controlled file, you may easily scale or modify your application's queue workers when deploying your application.
Notifications
Note: When configuring Horizon to send Slack or SMS notifications, you should review the prerequisites for the relevant notification driver.
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 :
Configuring Notification Wait Time Thresholds
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:
Уведомления
Примечание. При настройке Horizon для отправки уведомлений Slack или SMS необходимо проверить предварительные условия для соответствующего драйвера уведомлений .
Если вы хотите получать уведомления , когда один из ваших очередей имеют длительное время ожидания, вы можете использовать , и методу. Вы можете вызвать эти методы из вашего приложения : Horizon::routeMailNotificationsTo Horizon::routeSlackNotificationsTo Horizon::routeSmsNotificationsTo HorizonServiceProvider
Настройка порогов времени ожидания уведомлений
Вы можете настроить, сколько секунд считаются «долгим ожиданием» в вашем файле конфигурации. Параметр конфигурации в этом файле позволяет вам контролировать порог длительного ожидания для каждой комбинации подключения / очереди: config/horizon.php waits
Running Horizon
Once you have configured your supervisors and workers in your application's config/horizon.php configuration file, you may start Horizon using the horizon Artisan command. This single command will start all of the configured worker processes for the current environment:
You may pause the Horizon process and instruct it to continue processing jobs using the horizon:pause and horizon:continue Artisan commands:
You may also pause and continue specific Horizon supervisors using the horizon:pause-supervisor and horizon:continue-supervisor Artisan commands:
You may check the current status of the Horizon process using the horizon:status Artisan command:
You may gracefully terminate the Horizon process using the horizon:terminate Artisan command. Any jobs that are currently being processed by will be completed and then Horizon will stop executing:
Deploying Horizon
When you're ready to deploy Horizon to your application's actual server, you should configure a process monitor to monitor the php artisan horizon command and restart it if it exits unexpectedly. Don't worry, we'll discuss how to install a process monitor below.
During your application's deployment process, you should instruct the Horizon process to terminate so that it will be restarted by your process monitor and receive your code changes:
Installing Supervisor
Supervisor is a process monitor for the Linux operating system and will automatically restart your horizon process if it stops executing. To install Supervisor on Ubuntu, you may use the following command. If you are not using Ubuntu, you can likely install Supervisor using your operating system's package manager:
If configuring Supervisor yourself sounds overwhelming, consider using Laravel Forge, which will automatically install and configure Supervisor for your Laravel projects.
Supervisor Configuration
Supervisor configuration files are typically stored within your server's /etc/supervisor/conf.d directory. Within this directory, you may create any number of configuration files that instruct supervisor how your processes should be monitored. For example, let's create a horizon.conf file that starts and monitors a horizon process:
You should ensure that the value of stopwaitsecs is greater than the number of seconds consumed by your longest running job. Otherwise, Supervisor may kill the job before it is finished processing.
Starting Supervisor
Once the configuration file has been created, you may update the Supervisor configuration and start the monitored processes using the following commands:
Horizon allows you to assign “tags” to jobs, including mailables, broadcast events, 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:
If this job is queued with an App\Models\Video instance that has an id attribute of 1 , it will automatically receive the tag App\Models\Video:1 . This is because Horizon will search 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:
Manually Tagging Jobs
If you would like to manually define the tags for one of your queueable objects, you may define a tags method on the class:
Metrics
Horizon includes a metrics dashboard which provides information regarding 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:
Upgrading Horizon
When upgrading to a new major version of Horizon, it's important that you carefully review the upgrade guide.
In addition, you should re-publish Horizon's assets:
Running 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:
You may pause the Horizon process and instruct it to continue processing jobs using the horizon:pause and horizon:continue Artisan commands:
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:
Deploying 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 Configuration
If you are using the Supervisor process monitor to manage your horizon process, the following configuration file should suffice:
If you are uncomfortable managing your own servers, consider using Laravel Forge. Forge provisions PHP 7+ servers with everything you need to run modern, robust Laravel applications with 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:
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:
Manually Tagging
If you would like to manually define the tags for one of your queueable objects, you may define a tags method on the class:
Читайте также: