Laravel implements basic configuration and usage of task queue based on Redis

Source: Internet
Author: User
Tags http request php file redis valid email address

1. Overview
In Web development, we often encounter scenarios where tasks need to be processed in batches, such as sending emails and obtaining the seckilling qualification, putting these time-consuming or highly concurrent operations into the queue for asynchronous execution can effectively relieve system pressure and improve system response speed and load capabilities.

There are multiple ways to implement queues. Laravel also supports multiple queue implementation drivers, such as databases, Redis, Beanstalkd, IronMQ, and Amazon SQS. In addition, it also supports queue synchronization (default ), even if the queue driver is set to null, the queue is not used. Laravel provides a unified interface for these queue drivers, so that we can easily switch the driver without changing the business logic encoding and provide code reusability.

The following uses the Redis driver as an example to demonstrate how to create, push, and execute queues in Laravel.

2. Configuration file
We still start from the configuration file. First, we need to configure the default queue driver as Redis in the configuration file, and the queue configuration file is config/queue. php:

Return [

'Default' => env ('queue _ DRIVER ', 'sync '),

'Connections' => [
'Sync' => [
'Driver '=> 'sync ',
],
'Database' => [
'Driver '=> 'database ',
'Table' => 'jobs ',
'Queue '=> 'default ',
'Expire '=> 60,
],
'Beancalkd '=> [
'Driver '=> 'beancalkd ',
'Host' => 'localhost ',
'Queue '=> 'default ',
'Ttr' => 60,
],
'Sqs' => [
'Driver '=> 'sqs ',
'Key' => 'Your-public-key ',
'Secret' => 'Your-secret-key ',
'Queue '=> 'Your-queue-url ',
'Region' => 'US-east-1 ',
],
'Iron '=> [
'Driver '=> 'Iron ',
'Host' => 'mq-aws-us-east-1.iron.io ',
'Token' => 'Your-token ',
'Project' => 'Your-project-id ',
'Queue '=> 'Your-queue-name ',
'Enabled' => true,
],
'Redis '=> [
'Driver '=> 'redis ',
'Connection' => 'default ',
'Queue '=> 'default ',
'Expire '=> 60,
],
],

'Failed' => [
'Database' => 'mysql', 'table' => 'failed _ jobs ',
],
];
The first configuration item default in this configuration file is used to specify the default queue driver. Here we change its value to redis (actually modifying QUEUE_DRIVER in. env ).

The connections configuration item contains all the queue drivers supported by Laravel. We use the Redis driver, so we need to configure the redis item: connection corresponds to config/database. default configuration of redis in php; queue is the default queue name; expire is the queue task expiration time (seconds ). Here we can keep the default configuration unchanged.

The failed configuration item is used to configure the database and data table for storing failed queue tasks. Here we need to modify it according to our database configuration.

3. Compile a queue task
In this example, we will show an example of sending a new function reminder email to users.

First, use the following Artisan command to create a task class:

Php artisan make: job SendReminderEmail -- queued
The -- queued option indicates that the generated task class implements the ShouldQueue interface and will be pushed to the queue rather than synchronously executed.

After the program runs successfully, a SendReminderEmail. php file is generated in the app/Jobs directory. We modify the content as follows:

<? Php
Namespace App \ Jobs;

Use App \ Jobs \ Job;
Use Illuminate \ Queue \ SerializesModels;
Use Illuminate \ Queue \ InteractsWithQueue;
Use Illuminate \ Contracts \ Bus \ SelfHandling;
Use Illuminate \ Contracts \ Queue \ ShouldQueue;
Use App \ User;
Use Illuminate \ Contracts \ Mail \ Mailer;
Class SendReminderEmail extends Job implements SelfHandling, ShouldQueue
{

Use InteractsWithQueue, SerializesModels;
Protected $ user;
   
/**
* Create a new job instance.
     *
* @ Return void
*/

Public function _ construct (User $ user)
    {
$ This-> user = $ user;
    }

/**
* Execute the job.
     *
* @ Return void
*/
Public function handle (Mailer $ mailer)
    {
$ User = $ this-> user;
$ Mailer-> send ('emails. Reminder', ['user' => $ user], function ($ message) use ($ user ){
$ Message-> to ($ user-> email)-> subject ('New function release ');
});
    }
}
Here we use dependency injection to introduce User and Mailer instances. User is used to obtain User information, and Mailer is used to send emails. Here, the Mailer and the Mail facade used in the previous Mail sending have the same effect. They finally call methods in the same class, which is Illuminate \ Mail \ Mailer.

Next we will create the Mail partial view resources/views/emails/reminder. blade. php:

Dear {$ user-> name}, Laravel College has released the XXX function. Try it now:
<A href = "http://laravelacademy.org"> go to school </a>
After compiling the task class, let's see how to push the task to the queue:

4. Push queue tasks
Manual task distribution

We can use the dispatch method provided by DispatchesJobs trait in the Controller (this trait is introduced in Controller base class Controller. php) to manually distribute tasks:

<? Php

Namespace App \ Http \ Controllers;

Use Illuminate \ Http \ Request;
Use App \ Http \ Requests;
Use App \ Http \ Controllers \ Controller;
Use Mail;
Use Storage;
Use App \ User;
Use App \ Jobs \ SendReminderEmail;

Class MailController extends Controller
{
// Other methods

// Send a reminder email
Public function sendReminderEmail (Request $ request, $ id ){
$ User = App \ User: findOrFail ($ id );
$ This-> dispatch (new SendReminderEmail ($ user ));
    }
}
Then define the route in routes. php:

Route: get ('mail/sendReminderEmail/{id} ', 'mailcontroller @ sendReminderEmail ');
Running queue listener

Access http://laravel.app in a browser: 8000/mail/sendReminderEmail/1, when the task is pushed to the Redis queue, we also need to run the Artisan command in the command line to execute the task in the queue. Laravel provides three Artisan commands:

Queue: by default, work executes only one queue request. It is terminated after the request is executed;
Queue: listen listens to queue requests. As long as the queue is running, the request will be accepted until it is manually terminated;
Queue: work -- daemon is the same as listen. As long as it runs, it can always accept requests. The difference is that in this running mode, when new requests arrive, instead of re-loading the entire framework, it is a direct fire action. As you can see, the queue: work-daemon is the highest level. It is generally recommended to process queue listening.
Note: When you use queue: work -- daemon to update the code, you must stop it and restart it to apply the modified code.
Therefore, run the following command in the command line:

Php artisan queue: work -- daemon
Then, you will receive a reminder email when you go to the mailbox:

Send emails using queues in Laravel

Note: to ensure that the task is successfully executed, make sure that the email address with the id of 1 in the users table is a valid email address.
Of course, you can use dispatch distribution tasks in other places than the controller, and use DispatchesJobs in this class before that.

Push a task to a specified queue

The above operation pushes the queue to the default queue, that is, the default in the configuration file. Of course, you can also push the task to the specified queue:

Public function sendReminderEmail (Request $ request, $ id ){
$ User = App \ User: findOrFail ($ id );
$ Job = (new SendReminderEmail ($ user)-> onQueue ('emails ');
$ This-> dispatch ($ job );
}
Delayed task execution

In addition, Laravel also supports delayed task execution time. Here we specify a delay of 1 minute to execute the task:

Public function sendReminderEmail (Request $ request, $ id ){
$ User = User: findOrFail ($ id );
$ Job = (new SendReminderEmail ($ user)-> delay (60 );
$ This-> dispatch ($ job );
}
Distribute tasks from requests

In addition, we can map an HTTP request instance to a task, and then obtain the constructor of the parameter filling task class from the request instance. If the request does not contain this parameter, you can even pass additional parameters, which can be achieved through the dispatchFrom method provided by DispatchesJobs trait:

Public function sendReminderEmail (Request $ request, $ id ){
$ This-> dispatchFrom ('app \ Jobs \ SendReminderEmail ', $ request, ['id' => $ id]);
}
Of course, we need to modify the constructor of the SendReminderEmail task class as follows:

Public function _ construct ($ id)
{
$ This-> user = User: find ($ id );
}
$ Id in the constructor is obtained from additional parameters.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.