


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

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

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











Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

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.

Want to learn the Laravel framework, but suffer from no resources or economic pressure? This article provides you with free learning of Laravel, teaching you how to use resources such as online platforms, documents and community forums to lay a solid foundation for your PHP development journey from getting started to master.

Laravel provides a comprehensive Auth framework for implementing user login functions, including: Defining user models (Eloquent model), creating login forms (Blade template engine), writing login controllers (inheriting Auth\LoginController), verifying login requests (Auth::attempt) Redirecting after login is successful (redirect) considering security factors: hash passwords, anti-CSRF protection, rate limiting and security headers. In addition, the Auth framework also provides functions such as resetting passwords, registering and verifying emails. For details, please refer to the Laravel documentation: https://laravel.com/doc

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

The Laravel framework has built-in methods to easily view its version number to meet the different needs of developers. This article will explore these methods, including using the Composer command line tool, accessing .env files, or obtaining version information through PHP code. These methods are essential for maintaining and managing versioning of Laravel applications.

In the Laravel framework version selection guide for beginners, this article dives into the version differences of Laravel, designed to assist beginners in making informed choices among many versions. We will focus on the key features of each release, compare their pros and cons, and provide useful advice to help beginners choose the most suitable version of Laravel based on their skill level and project requirements. For beginners, choosing a suitable version of Laravel is crucial because it can significantly impact their learning curve and overall development experience.

Laravel and ThinkPHP are both popular PHP frameworks and have their own advantages and disadvantages in development. This article will compare the two in depth, highlighting their architecture, features, and performance differences to help developers make informed choices based on their specific project needs.
