First, the choice of drive

Using database drivers

Advantage: need not install other inside of miscellaneous things, use directly

Disadvantages: Database migration is required to generate working data tables

Env file to set the queue driver to the database
php artisan queue:table
Copy the code
The data table used to create the queue
php artisan queue:table
Copy the code
Perform migrate
# create database/migrations/{timestamp}_create_jobs_table.php
php artisan migrate
Copy the code
Example. Env file
BROADCAST_DRIVER=logCACHE_DRIVER=file SESSION_DRIVER=file QUEUE_DRIVER=database REDIS_HOST=127.0.0.1 REDIS_PASSWORD=null REDIS_PORT=6379 MAIL_DRIVER= SMTP MAIL_HOST=smtp.exmail.qq.com // QQ enterprise mailbox MAIL_PORT=25 // use port 25 [email protected] // sender's mailbox MAIL_PASSWORD=*** // Password or authorization code MAIL_ENCRYPTION= TLSCopy the code

Use redis driver

Install redis
Under Windows

Windows download address, download to run the installation.

C:\redis
redis-server.exe redis.windows.conf

Linux under
# see if there is a password
/etc/redis.conf port6379
Copy the code
Use Composer to install dependencies in the project
composer require "predis/predis:~1.0" 
Copy the code
Example. Env file
DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=honeybot
DB_USERNAME=root
DB_PASSWORD=root

BROADCAST_DRIVER=logCACHE_DRIVER=file SESSION_DRIVER=file QUEUE_DRIVER=redis REDIS_HOST=127.0.0.1 REDIS_PASSWORD=null REDIS_PORT=6379 MAIL_DRIVER= SMTP MAIL_HOST=smtp.exmail.qq.com MAIL_PORT=465 // using port 465 [email protected] MAIL_PASSWORD=*** MAIL_ENCRYPTION= SSL // Use port 465Copy the code

Two, failed task record (optional, see you want to record)

Sometimes the tasks in the queue fail. Laravel has a convenient way built in to specify the maximum number of task retries. When the task exceeds this number of retries, it is inserted into the failed_JOBS table. We can use the queue:failed-table command to create a migration file for the failed_JOBS table

# create database/migrations/{timestamp}_create_failed_jobs_table.php
 php artisan queue:failed-table
Copy the code

Then use the Migrate Artisan command to generate the failed_jobs table:

php artisan migrate
Copy the code

Create a task

Create a task = make a producer = (essentially write the business logic you want to execute in a queue), name it whatever you want, but follow the naming convention.

The generated file is split into two parts: the __construct() constructor; The second is the handle queue execution method.

Use the following Artisan command to generate a new queue task:

This command will generate a new class in the app/Jobs directory
php artisan make:job SendReminderEmail
Copy the code

Newly generated classes: pp/Jobs/SendReminderEmail. PHP


      

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use App\Util\L;
use Mail;

class SendReminderEmail implements ShouldQueue
{
   use Dispatchable.InteractsWithQueue.Queueable.SerializesModels;

   protected $orderInfo;
   protected $email;

   /**
    * Create a new job instance.
    *
    * @return void
    */
   public function __construct($orderInfo, $email)
   {
       $this->orderInfo = $orderInfo;
       $this->email = $email;
   }

   /**
    * Execute the job.
    *
    * @return void
    */
   public function handle(a)
   {
       // The return value of Mail::send() is null, so you can use other methods to determine
       Mail::send('emails.new_order_mail'['order_number'= >$this->orderInfo['order_number'].'goods_name'= >$this->orderInfo['goods_name'].'goods_color'= >$this->orderInfo['goods_color'].'goods_num'= >$this->orderInfo['goods_num']],function ($message) {
               $to = $this->email;
               $message->to($to)->subject([New order Notice of XX Mall]);
           });
       // Returns an array of errors that can be used to determine whether the message was sent successfully
       if (count(Mail::failures()) >= 1) {
           L::email("Order:" . $this->orderInfo['order_number']."The" . $this->email . "Failed to send email notification"); }}}Copy the code

Task distribution

The producer is called using the Dispatch method within the controller

      

namespace App\Api\Controllers\Mail;
use App\Api\Controllers\BaseController;
use App\Repositories\Order\OrderRepository;

class MailController extends BaseController
{
   public function __construct(OrderRepository $order)
   {
       $this->order = $order;
   }

   public function send(a)
   {
       $header_id = 3691;
       $this->order->sendMail($header_id); }}Copy the code
Define classes that send mail and distribute tasks
/**
    * @param $header_id
    * @returnMixed * Send message queue */ publicfunction sendMail($header_id) {try {// Message content$orderInfo = OrderDetail::select('order_number'.'order_lines.*')
               ->leftJoin('order_headers'.'order_headers.uid'.'='.'header_id') - >where('header_id'.$header_id)
               ->first();
           $order['order_number'] = $orderInfo->order_number;
           $order['goods_name'] = 'xi xi' . $orderInfo->combo;
           $order['goods_color'] = $orderInfo->color;
           $order['goods_num'] = $orderInfo->quantity;
           L::email("Order:" . $orderInfo->order_number); // List of email addresses$emailList = ["[email protected]"."[email protected]"]; // Test the email address // push the task to the queue$emailList as $email) {
               dispatch(new SendReminderEmail($order.$email));
           }
       } catch (\Exception $e) {}}Copy the code
Create an email sending template
// /resource/views/emailsnew_order_mail.blade.php<div> Hello, applet Mall received a new order. < / div > < div > shipping address: {{$address}} < / div > < div > order number: {{$order_number}} < / div > < div > name of commodity: {{$goods_name}} < / div > < div > commodity color: {{$goods_color}} < / div > < div > quantity: {{$goods_num}} < / div >Copy the code

Four, start the test

To start, we need to start the queue system at the command line, and the queue will go into the listening state once it has started

php artisan queue:listen
Copy the code

5. Run queue processes

php artisan queue:work
Copy the code

6. Configure the Supervisor

When the test is complete and the email is sent successfully, you have succeeded

But, if it is in the production environment, it is not possible to start the queue and send it once, but must have certain monitoring and triggering mechanism, so Supervisor comes on stage.

The container is designed for process management, and the permanent process is designed for handling the container. The container is designed for viewing, loading, and other commands

For details, see Configuring Supervisor. In Linux, queue processes manage the server