Home > PHP Framework > Laravel > Laravel development: How to manage asynchronous tasks using Laravel Queues and Supervisor?

Laravel development: How to manage asynchronous tasks using Laravel Queues and Supervisor?

王林
Release: 2023-06-13 16:04:16
Original
918 people have browsed it

Laravel development: How to use Laravel Queues and Supervisor to manage asynchronous tasks?

In modern web applications, asynchronous tasks have become an integral part of daily business. Asynchronous tasks can improve application response time, optimize user experience, and enhance application scalability. Laravel Queues is a powerful tool provided by the Laravel framework for handling asynchronous tasks and message queues. This article will introduce the concept and usage of Laravel Queues, and combine it with Supervisor to manage asynchronous tasks.

What are Laravel Queues?

Laravel Queues is a method for handling asynchronous tasks and message queues. Laravel Queues allow you to put time-consuming tasks into a queue without affecting the response time of your web requests. For example, sending emails, processing videos, or generating PDFs are all time-consuming operations. Using a queue to place them into background processing can make your application more efficient and responsive.

Laravel Queues supports multiple backend technologies such as Database, Redis, Beanstalkd and Amazon SQS through some built-in queue drivers. This allows developers to use their preferred queuing technology to handle asynchronous tasks.

Using Laravel Queues

Below we will introduce step by step how to use Laravel Queues to handle asynchronous tasks.

Step One: Configure the Queue Driver

There is a file named queue.php in the Laravel configuration file that you can use to configure Queues and queue drivers. You can generate the queue.php file with the following command:

php artisan queue:table
php artisan queue:failed-table
php artisan migrate
Copy after login

This will generate the migration file and queue table. Run the migrate command to perform the migration.

In the queue.php file, you can choose to use a variety of queue drivers:

  • Database Driver - Store tasks in a database, which can As an entry-level queuing system.
  • Redis Driver - Uses Redis' built-in queue support.
  • Beanstalkd Driver - Uses the Beanstalkd message queue service.
  • Amazon SQS Driver - Uses Amazon Simple Queue Service (SQS).

For example, if you want to use the Redis queue driver, please configure the queue.php file as follows:

'default' => env('QUEUE_CONNECTION', 'redis'),
'connections' => [
    'redis' => [
        'driver' => 'redis',
        'connection' => 'default',
        'queue' => env('REDIS_QUEUE', 'default'),
        'retry_after' => 90,
        'block_for' => null,
    ],
]
Copy after login

Step 2: Create a queue task class

Next, you need to create a queue task class to handle asynchronous tasks. This class should be a simple PHP class that defines the logic of the task. For example, the following code is an asynchronous task class for sending emails:

class SendEmail implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $email;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($email)
    {
        $this->email = $email;
    }
    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        Mail::to($this->email)->send(new WelcomeEmail());
    }
}
Copy after login

This class implements the ShouldQueue interface, which is required to tell Laravel to convert this class into an asynchronous task class. The handle() method defines the specific logic of the task, so the tasks you need to handle asynchronously can be performed here.

Step 3: Push the task into the queue

Now that you have the queue task and queue driver ready, the next step is to put the task into the queue. Use the following code to call an Eloquent queue anywhere in your project:

use AppJobsSendEmail; 
use IlluminateSupportFacadesQueue;
...
Queue::push(new SendEmail('example@test.com'));
Copy after login

Or you can use the dispatch() method to put tasks into the queue, as shown below:

SendEmail::dispatch('example@test.com');
Copy after login

Step 4 :Execute queue task

Once you put the task into the queue, the task will be dispatched to the queue, waiting for execution. You can use the following code to run the queue:

php artisan queue:work
Copy after login

Running this command will start a listener and process the tasks in the queue.

Use Supervisor to manage asynchronous tasks

Since queue tasks need to run in the background, a process daemon needs to be set up on the server to ensure that tasks can continue to be executed. Supervisor is a commonly used process daemon that ensures that background processes do not terminate abnormally and restarts them when needed.

Step 1: Install Supervisor

In Ubuntu system, you can use the following command to install Supervisor:

sudo apt-get update
sudo apt-get install supervisor
Copy after login

Step 2: Create a Supervisor configuration file

Create a configuration file in the /etc/supervisor/conf.d directory, for example myqueue.conf:

nano /etc/supervisor/conf.d/myqueue.conf
Copy after login

Add the following content to the configuration file, making sure to change the path, command and username to Match your program:

[program:myqueue]
process_name=%(program_name)s_%(process_num)02d
command=/usr/bin/php /path/to/artisan queue:work --sleep=3 --tries=3 --daemon
autostart=true
autorestart=true
user=username
numprocs=1
redirect_stderr=true
stdout_logfile=/path/to/storage/logs/myqueue.log
Copy after login

Step 3: Reload Supervisor

After you change the Supervisor's configuration file, you need to notify the Supervisor to reload the configuration file. Use the following command to reload the Supervisor:

sudo supervisorctl reread

sudo supervisorctl update

sudo supervisorctl start all
Copy after login

Step 4: View the Supervisor log

You can view the output and error information of the asynchronous task in the Supervisor's log file. For example, you can view the Supervisor log by viewing the path and log file name specified in the configuration file:

tail -f /path/to/storage/logs/myqueue.log
Copy after login

Conclusion

This article introduces how to use Laravel Queues and Supervisor to manage asynchronous tasks, using Laravel Queues make it easy to queue time-consuming tasks and make applications more efficient and responsive. Use Supervisor to ensure that background tasks can continue to run and be automatically restarted when needed. I hope this article will be helpful to your development.

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

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