Backend Development
PHP Tutorial
Analysis on the method of using message queue and asynchronous queue in PHP's Laravel framework
Analysis on the method of using message queue and asynchronous queue in PHP's Laravel framework
This article mainly introduces the method of using message queue queue and asynchronous queue in PHP's Laravel framework. For versions after Laravel 5.0, the example environment is the Linux system. Friends who need it can refer to it
queue configuration
First explain how to use queue in my previous project.
Our current projects all use symfony, older projects use symfony1.4, and newer projects use symfony2. The overall feeling of using symfony is very pleasant, especially symfony2, which generally uses a lot of design ideas from Java frameworks. But it does not support queue. In symfony, we have also gone through several processes using queue. I first used Zhang Yan’s httpsqs. This one is simple to use, but has a single point. After all, our project is still officially serving the outside world, so we studied ActiveMQ, an open source project under Apache, and found that there is a newer MQ under Apache, which is Apollo. In the end we decided to use Apollo.
The main application scenario of queue in our project is to asynchronously process some time-consuming functions, such as synchronizing third-party data, synchronously notifying our third-party data users of data changes, etc. Our general idea is this. If asynchronous processing is needed in each controller, we will encode a json object and stuff it into Apollo. Write another work Command, parse the json object in this Command, and call different methods based on the actions and parameters inside. Running Command as a daemon process on different machines at the same time according to business needs can also be considered as a solution to implement asynchronous multi-tasking applications. I kept using it until I discovered laravel. Plan to research it. It's not impossible to replace it if possible. hehe.
Since I just started learning, of course I went straight to laravel5. Routes, controllers, and views are basically the same as symfony, so it’s not difficult to get started. Finally, study the queue.
1. Installing laravle and using composer is very simple.
composer global require "laravel/installer=~1.1" vi ~/.bash_profile
Add ~/.composer/vendor/bin to the environment variables.
source ~/.bash_profile
You can use laravel directly from the command line. try it.
laravel -V
If you can see the following, it means success.
Laravel Installer version 1.2.1
2. Create a project.
laravel new guagua
3. Configure redis and queue.
4. Create a controller,
php artisan make:controller DefaultController
Push 100 queue tasks in the action of the controller.
for($i = 0; $i < 100; $i ++) {
Queue::push(new SendEmail("ssss".$i));
}5. Command to create queue
php artisan make:command SendEmail --queued
Modify app/Commands/SendEmail.php and add a private variable.
protected $msg;
Also modify the constructor.
public function __construct($msg)
{
$this->msg = $msg;
}Modified handle method
public function handle() {
sleep(4);
echo $this->msg."\t".date("Y-m-d H:i:s")."\n";
$this->delete();
}6. Modify routes
Route::get('/', [ 'as' => 'index', 'uses' => 'DefaultController@index' ]);
7. Monitor queue
php artisan queue:listen
To verify multitasking, we open three windows at the same time and run the same command.
8. Use laravel’s built-in server to start the service
php artisan serve --port 8080
Open the browser and visit http:// localhost:8080/page. Of course, you can also use nginx, apache, etc. However, various configurations are required, and the built-in ones are easy to use.
You can see the execution status of each queue in the console, as shown below. You can see that 100 tasks are divided equally among three jobs.

#At this point, I have basically achieved the effect I wanted. It is verified that laravel can easily implement queue and can handle multi-tasking.
use App\Commands\Command in the code generated by make command, but when running, it prompts that there is no such file. The solution is to change it to use Illuminate\Console\Command; I don’t know why this low-level problem occurs. Is it a problem with my mac system or a problem with my character.
When pushing the queue in the controller's action, there is no asynchronous execution, and it is still executed in the action script. It was found that it was a configuration problem. It turned out that not only queue.php in config must be modified, but also related configurations in .evn must be modified. Although the problem has been solved, I still feel pain in my balls and cannot understand it. Still need to learn laravel.
How to use asynchronous queue
1. Configuration
The definition of the queue will not be introduced here. . There are two keys to using asynchronous queues:
(1)存储队列的地方
(2)执行任务的服务
打开 config/queue.php ,这是Laravel5关于队列的配置文件。首先我们可以通过 default 参数指定默认队列驱动,默认配置是 sync , 这是同步队列,我们要做异步队列首先就要改变这里。假设我们用 database 作为驱动,队列任务将会存放在数据库中,而我们后面会另外启动一个后台服务来处理队列任务,这就是异步方式了。
'default' => 'database'
修改完配置后,我们需要创建一个表来存放队列任务,Laravel5已经在自带artisan命令中内置了一个指令用来生成数据迁移,只需要两条命令即可,当然你得实现配置好数据库连接。
php artisan queue:table php artisan migrate
这样就自动在数据库中创建了 jobs 表。
2.启动队列监听服务
通过下面这条指令启动队列监听服务,它会自动处理 jobs 表中的队列任务:
php artisan queue:listen
在linux中,如果想让它在后台执行,可以这样:
nohup php artisan queue:listen &
3.添加队列任务
关于队列任务的添加,手册里说的比较详细,这里就简单举个例子吧。
首先,通过artisan创建一个队列命令:
php artisan make:command SendEmail --queued
这样会生成 app/Commands/SendEmail.php 这个类文件,这个类会被标识为队列命令,你可以在 handle 方法中写自己的业务逻辑。
在控制器中,可以简单通过 Bus::dispatch 分发任务:
Bus::dispatch(new \App\Commands\SendEmail());
你会发现任务不会立即执行,而是被放到 jobs 表中,由队列监听服务处理。
以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!
相关推荐:
The above is the detailed content of Analysis on the method of using message queue and asynchronous queue in PHP's Laravel framework. For more information, please follow other related articles on the PHP Chinese website!
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
AI Hentai Generator
Generate AI Hentai for free.
Hot Article
Hot Tools
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
1384
52
What is Cross-Site Request Forgery (CSRF) and how do you implement CSRF protection in PHP?
Apr 07, 2025 am 12:02 AM
In PHP, you can effectively prevent CSRF attacks by using unpredictable tokens. Specific methods include: 1. Generate and embed CSRF tokens in the form; 2. Verify the validity of the token when processing the request.
Explain strict types (declare(strict_types=1);) in PHP.
Apr 07, 2025 am 12:05 AM
Strict types in PHP are enabled by adding declare(strict_types=1); at the top of the file. 1) It forces type checking of function parameters and return values to prevent implicit type conversion. 2) Using strict types can improve the reliability and predictability of the code, reduce bugs, and improve maintainability and readability.
How can you prevent a class from being extended or a method from being overridden in PHP? (final keyword)
Apr 08, 2025 am 12:03 AM
In PHP, the final keyword is used to prevent classes from being inherited and methods being overwritten. 1) When marking the class as final, the class cannot be inherited. 2) When marking the method as final, the method cannot be rewritten by the subclass. Using final keywords ensures the stability and security of your code.
Laravel Eloquent ORM in Bangla partial model search)
Apr 08, 2025 pm 02:06 PM
LaravelEloquent Model Retrieval: Easily obtaining database data EloquentORM provides a concise and easy-to-understand way to operate the database. This article will introduce various Eloquent model search techniques in detail to help you obtain data from the database efficiently. 1. Get all records. Use the all() method to get all records in the database table: useApp\Models\Post;$posts=Post::all(); This will return a collection. You can access data using foreach loop or other collection methods: foreach($postsas$post){echo$post->
The Future of PHP: Adaptations and Innovations
Apr 11, 2025 am 12:01 AM
The future of PHP will be achieved by adapting to new technology trends and introducing innovative features: 1) Adapting to cloud computing, containerization and microservice architectures, supporting Docker and Kubernetes; 2) introducing JIT compilers and enumeration types to improve performance and data processing efficiency; 3) Continuously optimize performance and promote best practices.
Laravel's geospatial: Optimization of interactive maps and large amounts of data
Apr 08, 2025 pm 12:24 PM
Efficiently process 7 million records and create interactive maps with geospatial technology. This article explores how to efficiently process over 7 million records using Laravel and MySQL and convert them into interactive map visualizations. Initial challenge project requirements: Extract valuable insights using 7 million records in MySQL database. Many people first consider programming languages, but ignore the database itself: Can it meet the needs? Is data migration or structural adjustment required? Can MySQL withstand such a large data load? Preliminary analysis: Key filters and properties need to be identified. After analysis, it was found that only a few attributes were related to the solution. We verified the feasibility of the filter and set some restrictions to optimize the search. Map search based on city
PHP and Python: Comparing Two Popular Programming Languages
Apr 14, 2025 am 12:13 AM
PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.
PHP vs. Python: Understanding the Differences
Apr 11, 2025 am 12:15 AM
PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.


