Home > Article > Backend Development > Detailed introduction of swoole running mode to accelerate laravel application
This article brings you a detailed introduction to the swoole running mode to accelerate laravel applications. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
1. Swoole
Swoole claims to have redefined PHP. It is a PHP extension that allows PHP to be executed asynchronously, just like node. , and can also use sockets, providing PHP with a series of asynchronous IO, event-driven, and parallel data structure functions.
Swoole4 supports a complete coroutine programming model and can use fully synchronous code to implement asynchronous programs. There is no need to add any additional keywords to the PHP code. The bottom layer automatically performs coroutine scheduling to implement asynchronous IO.
Almost all swoole that nodejs can implement can be realized, and the performance is higher than that of nodejs. After all, nodejs is single-threaded and cannot fully utilize the CPU performance, while swoole is multi-threaded and can fully utilize the CPU performance.
What is the difference between Swoole's efficiency and traditional web development? In addition to the traditional LAMP/LNMP synchronous development model, what is Swoole's asynchronous development model and how to maintain efficiency?
2. Traditional web development model
The method used in PHP web development is the LAMP/LNMP architecture, namely Linux, Nginx, Mysql and PHP. Here is nginx as an example. The general structure is:
When the request comes in, the web server transfers the request to PHP-FPM. PHP-FPM is A FastCGI service with a process pool architecture and a built-in PHP interpreter. FPM is responsible for interpreting and executing PHP files to generate responses, which are ultimately returned to the web server and displayed to the front end. Many business logics are implemented in PHP files, including Mysql and Nosql access, calling third-party applications, etc.
Such a structure, the cooperation between php-fpm and nginx has run well enough, but because php-fpm itself is a synchronous blocking process model, all resources (including a series of objects created by the framework initialization) are released after the request is completed. This causes the PHP process to "idle" (create destroy create) and consume a large amount of CPU resources, resulting in limited throughput capacity of a single machine.
Each request processing process means unnecessary time-consuming operations such as PHP file parsing and environment settings. The PHP process is destroyed after processing. It is impossible to use connection pooling and other technologies in PHP programs to achieve performance optimization.
3. Swoole operating mode
In view of the problems of traditional architecture, swoole starts from the PHP extension and solves the above problems. We have already understood the process model of swoole.
Compared with the traditional architecture, the biggest feature of the Swoole process model is its multi-threaded Reactor mode to process network requests, allowing it to easily handle a large number of connections.
In addition, other advantages include:
Fully asynchronous and non-blocking, small resource consumption, and high program execution efficiency
The program only parses and loads the PHP file once. Avoid repeated loading for each request
The process is resident, making it possible to implement connection pooling and information transfer between requests
4.Why run Laravel on Swoole?
The Laravel framework needs to load a lot of files when it is started. In addition, it is famous for its good ecological environment, so during the development process we will find that there are a lot of already built wheels, which means This makes the disk IO of Laravel's startup extremely high (that is, many files need to be loaded)
The laravel life cycle needs to be executed every time a request is made. Because the environment created by a single request will be destroyed immediately after the request execution is completed.
In other words, in the traditional PHP life cycle, a lot of time is wasted creating and destroying resources for script execution. Imagine a framework like Laravel, how many files need to be loaded in each request? It also wastes a lot of I/O operations.
So what if we use Swoole to build an application-level server, and all script files can be saved in memory after being loaded once? This is why we need to try running Laravel on Swoole. Swoole can provide powerful performance while Laravel can provide elegant code structure usage. These two are really a perfect combination!
5.Use Swoole to improve the performance of Laravel
Among the existing wheels, I feel that the following two are still very good, you can choose by yourself
swooletw/laravel-swoole
garveen/laravoole
I chose the first one To test
Install using composer:
composer require swooletw/laravel-swoole
If you are using laravel, then add
SwooleTW\Http\LaravelServiceProvider::class,
to the providers array in config/app.php. If you are using lumen, Then add the following code to bootstrap/app.php
$app->register(SwooleTW\Http\LumenServiceProvider::class);
Export the configuration file to the config directory
php artisan vendor:publish --provider="SwooleTW\Http\HttpServiceProvider"
Then you can go to config/swoole_http.php to configure the information
'server' => [ 'host' => env('SWOOLE_HTTP_HOST', '0.0.0.0'),//监听任意ip 'port' => env('SWOOLE_HTTP_PORT', '1215'), 'options' => [ 'pid_file' => env('SWOOLE_HTTP_PID_FILE', base_path('storage/logs/swoole_http.pid')), 'log_file' => env('SWOOLE_HTTP_LOG_FILE', base_path('storage/logs/swoole_http.log')), 'daemonize' => env('SWOOLE_HTTP_DAEMONIZE', 1),//1-程序将转入后台作为守护进程运行 ], ],
swoole_http.php also provides an array of configuration providers.
'providers' => [ // App\Providers\AuthServiceProvider::class, ]
Because after using swoole as http, these providers will be stored in memory, so what is configured here is to re-register and restart every request. providers.
Now, you can execute the following command to start the Swoole HTTP service.
$ php artisan swoole:http start
然后你可以看到以下信息:
Starting swoole http server... Swoole http server started: <http:></http:>
现在可以通过访问 http://127.0.0.1:1215 来进入 Laravel 应用。
注意:该拓展是不支持热启动的,所以每次有代码更新都要重启服务 php artisan swoole:http restart
六、性能测试
使用Apache的ab测试工具
ab -n 1000 -c 10 http://127.0.0.1:1215/
参数说明:-n 1000个请求 -c 10个并发数
图一是使用swoole作为应用服务器,图二是apache服务器
测试环境在虚拟机中,电脑配置也较差,性能没有完全发挥出来,可以看到apache只完成197次请求就扛不住压力了,swoole HTTP服务 完成了压测,性功完全碾压apache服务器。
七、使用Nginx代理
swoole在官网也提到过:swoole_http_server对Http协议的支持并不完整,建议仅作为应用服务器。并且在前端增加Nginx作为代理。
那么,我们就增加需要配置nginx.conf里的server:
server { listen 80; server_name your.domain.com; root /path/to/laravel/public; index index.php; location = /index.php { # Ensure that there is no such file named "not_exists" # in your "public" directory. try_files /not_exists @swoole; } location / { try_files $uri $uri/ @swoole; } location @swoole { set $suffix ""; if ($uri = /index.php) { set $suffix "/"; } proxy_set_header Host $host; proxy_set_header SERVER_PORT $server_port; proxy_set_header REMOTE_ADDR $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # IF https # proxy_set_header HTTPS "on"; proxy_pass http://127.0.0.1:1215$suffix; } }
配置可参考swoole方文档官 Nginx/Apache配置
至此,大功告成,你可以像平常一样访问你的网站了。
八、使用swoole和传统php开发的缺点
本文主要介绍了使用swoole作为laravel的应服务器,最后说下使用swoole和传统php开发的缺点。
1、更难上手。这要求开发人员对于多进程的运行模式有更清晰的认识
2、更容易内存泄露。在处理全局变量,静态变量的时候一定要小心,这种不会被GC清理的变量会存在整个生命周期中,如果没有正确的处理,很容易消耗完所有的内存。在php-fpm下,php代码执行完内存就会被完全释放。
The above is the detailed content of Detailed introduction of swoole running mode to accelerate laravel application. For more information, please follow other related articles on the PHP Chinese website!