Laravel queue - database driver (I just learned the queue today and took notes)

Keywords: PHP Database Laravel

Just learned the laravel queue, take notes.

1. First step configuration (. env)

QUEUE_CONNECTION=database

2.database drive settings

Step 1: generate jobs data migration table

php artisan queue:table

The effect is as follows:

Step 2: create the jobs table and execute the migration command

php artisan migrate

The effect is as follows:

3. Simulation data

Step 1: enter thinker

php artisan thinker

Step 2: create data (thinker command)

factory(App\User::class,10)->create();
// Create 10 users

Open the users table to see the 10 new users created

4. Create Jobs and write

Step 1: create

php artisan make:job Email

At this time, you can generate a Jobs folder and the Email.php file we created in the app directory

The effect is as follows:


Step 2: write Email.php

<?php

namespace App\Jobs;

use App\User;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Log;

class Email implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    //Definition
    public $user;
    /**
     * Create a new job instance.
     *
     *
     * @return void
     */
    public function __construct(User $user)
    {
        //assignment
        $this->user = $user;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        //Print diary
        Log::info('The message sent is:'.$this->user->email);
    }
}

6. Create controller and distribute tasks

Step 1: create a Usercontroller controller

php artisan make:controller UserController

Step 2: write Usercontroller

<?php

namespace App\Http\Controllers;

use App\Jobs\Email;
use App\Jobs\SendReminderEmail;
use App\User;

class UserController extends Controller
{
    //
    public function store()
    {
        $users = User::where('id','<',6)->get();

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

        return 'Done';
    }
}

7. Write route add queue

1.web.php

Route::get('/', 'UserController@store');

2. After accessing the route, the jobs table will generate qualified users
3. Perform tasks

php artisan queue:work

After executing the command, the data that jobs just added is gone
4. Open log file
As shown in the picture:

We will find the data printed under email.php handle

End

Posted by whizzykid on Sun, 10 Nov 2019 10:03:00 -0800