Home > PHP Framework > Laravel > Laravel development: How to use Laravel Queues to handle asynchronous tasks?

Laravel development: How to use Laravel Queues to handle asynchronous tasks?

WBOY
Release: 2023-06-13 14:23:36
Original
1322 people have browsed it

Laravel development: How to use Laravel Queues to handle asynchronous tasks?

Laravel is a popular PHP framework whose powerful features make it the best choice for web application development. Using Laravel, you can create complex web applications quickly and easily. In this article, we will discuss the use of Laravel Queues, a feature that helps in handling asynchronous tasks.

The concept of asynchronous tasks

When a user performs a task in a web application, he or she needs to wait for the task to complete before obtaining the result. This is the synchronization task. But what if we want to process it without the user having to wait for the task to complete? This is an asynchronous task!

Asynchronous tasks will not affect the user's real-time response performance because they do not wait for the task to complete before returning results. Instead, these tasks are put into a queue and processed one by one in the background. For example, a user uploads a file to the server. If an upload takes too long because the file is too large, users may become impatient and cancel the upload. At this point, using asynchronous tasks will help avoid user churn.

Laravel Queues are part of the Laravel framework which helps in handling asynchronous tasks.

Building Laravel Queues

The first step in using queues in Laravel is to let the computer know which queue should be processed. In the Queue.php file you can define the queue and specify which driver the queue uses. Drivers can be local drivers, database drivers, Redis drivers, Beanstalk drivers, etc. Here is an example:

'connection' => env('QUEUE_DRIVER', 'sync'),

'driver' => env('QUEUE_DRIVER', 'sync'),

'queue' => [

    'default' => [

        'connection' => 'default',

        'queue' => 'default',

        'retry_after' => 90,

        'backoff' => [

            'strategy' => 'exponential',

            'max_attempts' => 3,

            'delay' => 1000,

        ],

    ],

],
Copy after login

The code example above shows that the queue uses the 'sync' driver by default. However, you can define different drivers in the .env file.

Add Queue

Now that we have defined the queue and its driver, we need to add tasks to the queue for processing. In the Laravel framework, tasks are added to the queue using the dispatch() method. For example, we use the following code to add a task to the queue:

ProcessPodcasts::dispatch($podcast);
Copy after login

In the above code, ProcessPodcasts is the task we want to execute, and $podcast is the parameter passed to the task.

Create Task

Now, let us create an asynchronous task using Laravel. To do this, we will create a new Job.php file in the app/Jobs directory. The following is sample code:

<?php

namespace AppJobs;

use AppMailSendWelcomeEmail;
use AppUser;
use IlluminateBusQueueable;
use IlluminateContractsQueueShouldQueue;
use IlluminateFoundationBusDispatchable;
use IlluminateQueueInteractsWithQueue;
use IlluminateQueueSerializesModels;
use IlluminateSupportFacadesMail;

class SendWelcomeEmailJob implements ShouldQueue
{
    // Traits used by the class
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $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()
    {
        Mail::to($this->user->email)->send(new SendWelcomeEmail($this->user));
    }
}
Copy after login

The above code creates an asynchronous task named SendWelcomeEmailJob. This task sends an email to a new user. Because the task is in the queue, the user does not have to wait for the email to be sent to complete.

Execution Queue

Through the above operations, we have created a task and added it to the queue. However, we need to execute the tasks in the queue. There are several ways to execute a queue, here is the sample code:

php artisan queue:work 
Copy after login

In the above code, we execute the queue using the queue:work command in Laravel CLI. This command will continue executing until there are no more tasks to process.

There are other ways to execute queues, such as executing queues with the help of supervisor. Supervisor is a process management tool that allows us to manage Laravel applications in the background. To execute a queue with the help of a supervisor, follow these steps:

  1. Install supervisor (please refer to the use of supervisor).
  2. Create a new file queue-worker.conf located in the /etc/supervisor/conf.d directory.
  3. Enter the following code:
[program:queue-worker]

process_name=%(program_name)s_%(process_num)02d

command=php /path/to/artisan queue:work 

autostart=true

autorestart=true

user=user

numprocs=1

redirect_stderr=true

stdout_logfile=/path/to/your/logs/queue-worker.log
Copy after login

The above code creates a queue worker for the supervisor. When the supervisor starts, this program will start processing the queue and execute in the background.

Conclusion

In this article, we learned how to use Laravel Queues for asynchronous task processing. We learned about the concept of Queue and defined new queues and drivers. We also created an asynchronous task and saw how to execute it using Laravel Queues. Overall, Laravel Queues are a very useful component in Laravel development, which can help us handle asynchronous tasks easily.

The above is the detailed content of Laravel development: How to use Laravel Queues to handle asynchronous tasks?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template