


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!

workerman 对比 swoole 实际开发项目中,你会选择哪个?对于新手学哪个较好,有什么建议吗?

在现代的应用开发中,异步编程在高并发场景下变得越来越重要。Swoole和Go是两个非常流行的异步编程框架,它们都具有高效的异步能力,但是很多人在选择使用哪个框架时会陷入困境。本文将探讨如何选择Swoole和Go,以及它们的优缺点。

你学会 Swoole 需要多久呢?这个问题其实非常难回答,因为它涉及到很多因素,比如你的编程基础、学习动力、时间安排等等。不过,在这篇文章中,我将分享一些我自己学习 Swoole 的经验和建议,希望能够对你有所帮助。

Swoole是一个基于PHP的开源高性能网络通信框架,它提供了TCP/UDP服务器和客户端的实现,以及多种异步IO、协程等高级特性。随着Swoole日益流行,许多人开始关心Web服务器使用Swoole的问题。为什么当前的Web服务器(如Apache、Nginx、OpenLiteSpeed等)不使用Swoole呢?让我们探讨一下这个问题。

以下为大家整理了php异步通信框架Swoole的视频教程,不需要从迅雷、百度云之类的第三方平台下载,全部在线免费观看。教程由浅入深,有php基础的人就能学习,从安装到案例讲解,全面详细,帮助你更快更好的掌握Swoole框架!

怎么在docker中搭建swoole环境?下面本篇文章给大家介绍一下用docker搭建swoole环境的方法,希望对大家有所帮助!

php让Swoole|Pool进程池实现Redis持久连接进程池,基于Swoole\Server的Manager管理进程模块实现。可管理多个工作进程,相比Process实现多进程,Process\Pool更加简单,封装层次更高,开发者无需编写过多代码即可实现进程管理功能,配合Co\Server可以创建纯协程风格的,能利用多核CPU的服务端程序。Swoole进程池实现redis数据读取如下案例,通过WorkerStart启动Redis进程池,并持久读取Redis列表数据;当WorkerStop断开

Swoole是一种基于PHP语言的网络通信框架,它能够提供异步、并发、高性能的HTTP、WebSocket以及TCP/UDP协议服务器和客户端,在开发Web服务以及网络通信应用时都有很大的用途,广泛应用于一些互联网公司。本文将介绍如何使用Swoole调用。


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

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Mac version
God-level code editing software (SublimeText3)

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Notepad++7.3.1
Easy-to-use and free code editor

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.
