laravel 队列使用
app/jobs/CacheHtmlManage.php
namespace App\Jobs; use App\Models\CronJob\HtmlCacheJob; use Exception; use Illuminate\Bus\Queueable; use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Foundation\Bus\Dispatchable; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\SerializesModels; class CacheHtmlManage implements ShouldQueue { use Dispatchable; use InteractsWithQueue; use Queueable; use SerializesModels; /** * 应该处理任务的队列连接. * * @var string */ //public $connection = 'redis'; /** * 任务可以尝试的最大次数。 * * @var int */ public $tries = 5; /** * 任务可以执行的最大秒数 (超时时间)。 * * @var int */ public $timeout = 120; protected $cache_html; /** * Create a new job instance. * @param $cache_html * $cache_html 为队列分发时传入的数据 */ public function __construct($cache_html) { $this->cache_html = $cache_html; } /** * Execute the job. */ public function handle() { // 具体的队列执行方法 //print_r($this->cache_html); $model = new HtmlCacheJob(); $model->deleteHtml($this->cache_html); } /** * 任务失败的处理过程. */ public function failed(Exception $exception) { // 给用户发送任务失败的通知,等等…… } }
在控制器中分发任务:
CacheHtmlManage::dispatch($data)->onConnection('redis')->onQueue('{cache_html}'); //指定了队列连接和队列名称
运行:
因为队列 worker 是长生命周期的进程,所以在重启之前,任何的代码更改都不会生效。因此,使用队列 worker 部署应用程序的最简单方法是在部署过程中重新启动 worker。你可以通过执行 queue:restart 命令来优雅地重新启动所有的 worker:该命令将指示所有队列 worker 在完成当前任务后优雅地 “死亡”,这样就不会丢失现有的任务。由于在执行 queue:restart 命令时,队列 worker 将被杀掉,因此你应该运行一个进程管理器 (如 Supervisor) 来自动重新启动队列 worker。
php artisan queue:restart // 重启队列 php artisan queue:work --queue="{cache_html}" // 启动队列,并指定执行的队列名称
队列配置文件:
conifg/queue.php
'connections' => [ 'sync' => [ 'driver' => 'sync', ], 'redis' => [ 'driver' => 'redis', 'connection' => 'default', 'queue' => env('REDIS_QUEUE', '{default}'), 'retry_after' => 90, 'block_for' => null, ], 'failed' => [ 'database' => env('DB_CONNECTION', 'queue'), //队列执行失败 存放的数据库 'table' => 'failed_jobs', //队列执行失败 存放的表 ], ],