備忘録

備忘録

LaravelでQueueを利用する方法

Ⅰ. はじめに

タイトルの通り「LaravelでQueueを利用する方法」です。

Ⅱ. やり方

1. .envを編集する
QUEUE_CONNECTION=database
2. テーブルを作成する
php artisan queue:table
php artisan migrate
3. Job用クラスを作成する
php artisan make:job TestJob 
4. ファイルを編集する

app/Jobs/TestJob.php

<?php
use Illuminate\Support\Facades\Log;

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

  protected $str;

  public function __construct($str)
  {
    $this->str = $str;
  }

  public function handle()
  {
    Log::debug($this->str);
  }
}
5. キューワーカを起動する
php artisan queue:work --tries=3
6. テスト用のプログラムを書く

routes/api.php

<?php
use App\Jobs\TestJob;

Route::get('/test', function (Request $request) {
  TestJob::dispatch('hello world');
});

実行結果

storage/logs/laravel.log
f:id:kagasu:20210207004109p:plain

その他

systemdを利用してキューワーカを常駐させる方法

/etc/systemd/system/LaravelQueueWorker.service

[Unit]
Description = LaravelQueueWorker
After = network-online.target, mysql.service

[Service]
User = www-data
Type = simple
WorkingDirectory=/var/www/html/MyProject
ExecStart = /usr/bin/php /var/www/html/MyProject/artisan queue:work --tries=3
Restart = on-failure
RestartSec=5s
RestartPreventExitStatus = 255

[Install]
WantedBy = multi-user.target
systemctl enable LaravelQueueWorker
systemctl start LaravelQueueWorker
systemctl status LaravelQueueWorker

留意点

app/Jobs/*.php に修正を加えた時は必ずキューワーカを再起動する事。
※再起動しないと反映されない