laravel 队列实例(一)

导语

之前在写事件/监听器的实例,数据都是直接入库的,实际这一步可以放到队列中去执行。laravel 队列有多种驱动可以选择,这里就使用 redis。

创建队列

  1. 使用 php artisan make:job BrowseLogQueue 即可创建队列文件,最终生成 Jobs/BrowseLogQueue.php 文件
  2. 功能只是数据入库,代码很简单。需要注意的是,可以在类中指定最大失败次数等配置,代码如下
<?php
/**
 * 浏览记录入库
 */

namespace App\Jobs;

use App\Events\NotifyAdmin;
use App\Models\BrowseLog;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Exception;

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

    // 最大失败次数
    public $tries = 5;

    // 超时
    public $timeout = 120;

    protected $ip_addr;
    protected $request_url;
    protected $city_name;
    protected $created_at;
    protected $updated_at;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($ip_addr, $request_url, $city_name, $now)
    {
        $this->ip_addr = $ip_addr;
        $this->request_url = $request_url;
        $this->city_name = $city_name;
        $this->created_at = $now;
        $this->updated_at = $now;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle(BrowseLog $browseLog)
    {
        $log = new $browseLog;

        $log->ip_addr = $this->ip_addr;
        $log->request_url = $this->request_url;
        $log->city_name = $this->city_name;
        $log->created_at = $this->created_at;
        $log->updated_at = $this->updated_at;

        $log->save();
    }

    /**
     * 任务失败
     * @param Exception $exception
     */
    public function failed(Exception $exception)
    {
        // 发送邮件,通知管理员
        event(new NotifyAdmin($exception->getMessage()));
    }
}
    

分发任务

将监听器 CreateBrowseLog.php 文件修改如下

/**
     * Handle the event.
     *
     * @param  UserBrowse $event
     * @return void
     */
    public function handle(UserBrowse $event)
    {
        // 本地访问不做记录
        $arr = ['127.0.0.1'];

        if (!in_array($event->ip_addr, $arr)) {
            /*$log = new \App\Models\BrowseLog();

            $log->ip_addr = $event->ip_addr;
            $log->request_url = $event->request_url;
            $log->city_name = $event->city_name;

            $log->save();*/
            BrowseLogQueue::dispatch($event->ip_addr, $event->request_url, $event->city_name, now());

            /*BrowseLogQueue::dispatch($event->ip_addr, $event->request_url, $event->city_name)->delay(now()->addMinute(1)); 延时添加
            */
        }
    }

运行队列

最后一步就是运行队列,执行 php artisan queue:work

《laravel 队列实例(一)》

运行没有问题,但是到此并没有结束,还需要使用 Supervisor 进程守护,下篇文章继续。

参考资料:队列

    原文作者:haoyq
    原文地址: https://segmentfault.com/a/1190000018850681
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞