Laravel Queue Service provides a unified API for various background queues. This article mainly introduces you to the most basic operation tutorials about using Queue in Laravel. The article introduces it in great detail through sample code. I hope to be helpful.
Preface
The queue service in laravel is no different from other queue services. They are the simplest and most common ones that are most in line with human thinking. The process: There is a place to store queue information, a PHP process writes tasks when running, and another PHP daemon process polls the queue information, executes and deletes tasks that meet the execution requirements. Since PHP is a URL-driven synchronous language and inherently blocking, it is not surprising that Laravel provides a daemon tool to query and execute queue information.
It was the first time I came into contact with Laravel’s queue in the past two days, and it took a long time. . . After a lot of hard work, I still feel that I don’t know how to use Laravel. The documentation is relatively simple and summarized, and it is a bit difficult to read the source code (but slowly debugging and verifying it by looking at the source code is still the most reliable).
The following is a simple demo of mine, which only uses the most basic operations of the queue. More advanced operations require more time:)
Like me, there are some queues for getting started with Laravel. Students who are in difficulty can communicate with each other.
Configuration
Add Redis package
In composer.json Add "predis/predis": "~1.0" to the require section, and then composer up to update it.
database.php
Configure the redis database part in the database.php configuration file. There is a default connection by default. Just use this: )
According to the configuration items required in this default connection, edit the .env configuration file and fill in the REDIS_HOST, REDIS_PASSWORD, and REDIS_PORT with the corresponding values of Redis in your own server.
queue.php
First you need to configure QUEUE_DRIVER in .env. Because you plan to use Redis now, you configure it to redis.
Then configure the redis connection in the connections section of queue.php, where the value corresponding to connection is the default connection of redis in database.php.
Task class
The next step is to write the actual operation class. Laravel provides the artisan command to simplify the creation of task classes:
php artisan make:job Demo
The Jobs directory will be generated in the app directory, which already has the Demo.php task class.
Lumen does not have this artisan command, but it is very convenient. By default, there will be an ExampleJob.php already written, just copy it and change the name.
First write a simple log output test, in the handle method:
Log::info('Hello, queue');
Issuing tasks
Now write an entry function to push the task to the queue. Use the auxiliary function dispatch():
Use the following method in Laravel:
Demo::dispatch();
Use the following method in Lumen:
dispatch(new Demo);
Open the queue
If everything goes well, this is the last step. Execute in the command line:
php artisan queue:listen --queue=default
It will monitor the queue and output simple execution status, such as:
[2017-11-07 02:12:47] Processing: App\Jobs\Demo [2017-11-07 02:12:47] Processed: App\Jobs\Demo
If there are no problems, you can let this queue script execute in the background:
php artisan queue:work --daemon --quiet --queue=default 1>> /dev/null 2>&1
Advanced:)
When pushing to the queue, there is usually a need to pass parameters, so how to pass them here?
Parameter passing
Passing in
The method of passing parameters in the entry function is as follows:
Use the following method in Laravel:
$param = 'Stephen'; Demo::dispatch($param);
Use the following method in Lumen:
$param = 'Stephen'; dispatch(new Demo($param));
Receive
in the task The method of receiving parameters in the class is as follows:
protected $param; /** * Create a new job instance. * * @return void */ public function __construct($param) { $this->param = $param; } /** * Execute the job. * * @return void */ public function handle() { Log::info('Hello, ' . $this->param); }
This is the first attempt. There are many advanced usages, such as delayed distribution, error handling, priority, failure handling, etc. I will continue to write in the future:)
Multiple Queues
This is an issue that must be considered. It is impossible for me to put all tasks in a queue called default. , which makes it difficult to manage the queue.
To specify different queues, it is very simple. Just follow dispatch() and then follow the onQueue() method:
Demo::dispatch()->onQueue('emails');
No, I don’t seem to have defined this called emails. queue. Well, naturally we need to make some changes. The redis configuration queue in the queue.php configuration file is changed from default to {default}. The effect of this is that the name of the queue can be obtained dynamically from runtime instead of being hard-coded. .
If you use the Lumen framework, you will get an error if you write directly like this: Call to a member function onQueue() on string.
The reason is that Lumen's Job base class does not use the Illuminate\Foundation\Bus\Dispatchable trait, but directly uses the onQueue() method in Illuminate\Bus\Queueable.
So now it is clear that our Job class uses the Illuminate\Bus\Queueable trait, so we need to call this onQueue() method on the Job class.
$job = new XXXJob(); dispatch($job->onQueue('queue-name'));
When we open the queue:
php artisan queue:work --queue=emails
这里指定的队列名 emails 和 dispatch 时指定的队列名保持一致即可。
相关推荐:
The above is the detailed content of The use of Queue in Laravel. For more information, please follow other related articles on the PHP Chinese website!

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Chinese version
Chinese version, very easy to use

Atom editor mac version download
The most popular open source editor