解析Laravel5.5之事件监听、任务调度、队列

2021-06-20,

下面由laravel教程栏目给大家介绍Laravel5.5之事件监听、任务调度、队列,希望对需要的朋友有所帮助!

Laravel5.5之事件监听、任务调度、队列

一、事件监听

流程:

/2021/06/d8bcc06c.png" /2021/06/d8bcc06c.png" alt="4141bcef64d4082ec180485995e0945.png

1.1 创建event

php artisan make:event UserLogin

LoginController.php

    /**
     * The user has been authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  mixed  $user
     * @return mixed
     */
    protected function authenticated(Request $request, $user)
    {
        event(new UserLogin($user));
    }

1.2 创建listener

1.2.1 方式一:手动创建

php artisan make:listener EmailAdminUserLogin --event=UserLogin

1.2.2 方式二:推荐如下方式:自动生成事件和监听

//应用程序的事件监听器映射

class EventServiceProvider extends ServiceProvider
{
    /**
     * The event listener mappings for the application.
     *
     * @var array
     */
    protected $listen = [
        'App\Events\UserLogin' => [
            'App\Listeners\UserLogin\EmailAdminUserLogin',
            'App\Listeners\UserLogin\TraceUser',
            'App\Listeners\UserLogin\AddUserLoginCounter',
        ],
        'App\Events\UserLogout' => [
            'App\Listeners\UserLogout\EmailAdminUserLogout',
            'App\Listeners\UserLogout\TraceUser',
        ],
    ];

    /**
     * Register any events for your application.
     *
     * @return void
     */
    public function boot()
    {
        parent::boot();

        Event::listen('event.*', function ($eventName, array $data) {
            //
        });
    }
}

生成事件 & 监听器:php artisan event:generate

二、Laravel 的任务调度(计划任务)功能 Task Scheduling

2.1 call方式

protected function schedule(Schedule $schedule)
    {
        $schedule->call(function (){
            \Log::info('我是call方法实现的定时任务');
        })->everyMinute();
    }

执行:php artisan schedule:run

2.2 crontab方式

/2021/06/78427a27.png" /2021/06/78427a27.png" alt="ec30296e321315018d2f94a3ae33b63.png

2.2 command方式

生成命令:php artisan make:command SayHello

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;

class SayHello extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'message:hi';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //书写处理逻辑
        \Log::info('早上好,用户');
    }
}

Kernel.php

protected function schedule(Schedule $schedule)
{
    $schedule->command('message:hi')
             ->everyMinute();
}

执行:php artisan schedule:run

三、队列任务

3.1 驱动的必要设置

QUEUE_DRIVER=database

如:数据库驱动

php artisan queue:table

php artisan migrate

3.2 创建任务

生成任务类:

php artisan make:job SendReminderEmail
class SendReminderEmail implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    public $user;

    /**
     * Create a new job instance.
     *
     * @param User $user
     */
    public function __construct(User $user)
    {
        $this->user = $user;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        \Log::info('send reminder email to user' . $this->user->email);
    }
}

3.3 分发任务

你写好任务类后,就能通过 dispatch 辅助函数来分发它了。唯一需要传递给 dispatch 的参数是这个任务类的实例:
利用模型工厂生成30个用户:

/2021/06/bc78a4e0.png" /2021/06/bc78a4e0.png" alt="6edf3c3bbe5853de183197f9060088d.png

    public function store(Request $request)
    {
        $users = User::where('id','>',24)->get();

        foreach ($users as $user){
            $this->dispatch(new SendReminderEmail($user));
        }

        return 'Done';
    }
Route::get('/job', 'UserController@store');

数据库表jobs生成5个队列任务:

/2021/06/1834c91e.png" /2021/06/1834c91e.png" alt="c7d38a7878f8e3989002265ee886da0.png

3.4 运行队列处理器

php artisan queue:work

Tips:要注意,一旦 queue:work 命令开始,它将一直运行,直到你手动停止或者你关闭控制台

处理单一任务:你可以使用 --once 选项来指定仅对队列中的单一任务进行处理

php artisan queue:work --once

/2021/06/d72537fb.png" /2021/06/d72537fb.png" alt="624bc834907fb31be40228e8f0752b9.png

拓展:使用 Beanstalkd 管理队列,Supervisor 则是用来监听队列的任务,并在队列存在任务的情况下自动帮我们去执行,免去手动敲 php artisan 的命令,保证自己的队列可以正确执行

《相关推荐:最新的五个Laravel视频教程》

以上就是解析Laravel5.5之事件监听、任务调度、队列的详细内容,更多请关注北冥有鱼其它相关文章!

本文转载自【PHP中文网】,希望能给您带来帮助,苟日新、日日新、又日新,生命不息,学习不止。

《解析Laravel5.5之事件监听、任务调度、队列.doc》

下载本文的Word格式文档,以方便收藏与打印。