使用Laraveltw/laravel-swoole加速Laravel專案
Laravel 慢在哪裡?
- 初始化框架需要載入208+檔案被載入
- 每個檔案都需要被解析和編譯
- 每個請求結束後編譯結果會被銷燬
- 預設的
session
驅動也是基於檔案 - Laravel本身是一個全棧、元件框架
Laradock 安裝Swoole
本地環境是以Laradock
為例,需要在 laradock
目錄下的 .env
中將下面兩行配置值設定為 true
...
WORKSPACE_INSTALL_SWOOLE=true
...
PHP_FPM_INSTALL_SWOOLE=true
...
複製程式碼
然後執行 重新構建 Docker 容器
$ docker-compose build php-fpm workspace
複製程式碼
構建完成後重啟這兩個容器,進入 workspace
容器,執行 php -m
檢視 Swoole 是否安裝成功,如果擴充套件列表包含 swoole
則表示安裝成功。
$ php -m | grep swoole
swoole
複製程式碼
Tips: 額外提示
刪除映象
docker rmi $(docker images --filter "dangling=true" -q --no-trunc)
複製程式碼
刪除全部映象
docker image prune -a -f
複製程式碼
清除 Container,Image
docker system prune
複製程式碼
重新編譯映象
$ cd ~/laradock
$ docker-compose build php-fpm workspace mysql redis
複製程式碼
workspace 和 php-fpm 的區別
環境配置檔案 .env 裡包含相似的兩塊配置:workspace 和 php-fpm,它們對應兩個不同的容器,一個是 FPM,一個是 CLI。不管是安裝外掛還是修改配置,都要分開修改。
CentOS編譯安裝Swoole
在伺服器中,克隆原始碼
$ git clone https://gitee.com/swoole/swoole
複製程式碼
進入swoole
$ cd swoole
$ phpize
Configuring for:
PHP Api Version: 20170718
Zend Module Api No: 20170718
Zend Extension Api No: 320170718
$ ./configure
checking for grep that handles long lines and -e... /usr/bin/grep
checking for egrep... /usr/bin/grep -E
checking for a sed that does not truncate output... /usr/bin/sed
checking for cc... cc
checking whether the C compiler works... yes
checking for C compiler default output fi
...
configure: creating ./config.status
config.status: creating config.h
config.status: executing libtool commands
$ make && make install
...
Build complete.
Don't forget to run 'make test'.
Installing shared extensions: /usr/lib64/php/modules/
Installing header files: /usr/include/php/
複製程式碼
configure: error: in `/root/swoole': configure: error: C++ preprocessor "/lib/cpp" fails sanity check
遇到以上問題
$ yum install -y glibc-headers
$ yum install -y gcc-c++
複製程式碼
確認是否已經安裝了swoole
擴充套件
$ php -m|grep swoole
複製程式碼
如果沒有載入成功,修改php.ini
並新增擴充套件。使用php --ini
檢視php.ini
的檔案位置,找到擴充套件如何新增,比如在我的CentOS 7
中安裝擴充套件如下:
$ cd /etc/php.d
$ vi swoole.ini
; Enable zip extension module
extension=swoole.so
複製程式碼
重啟php-fpm
$ systemctl restart php-fpm
複製程式碼
再次檢視是否安裝成功
$ php -m | grep swoole
swoole
複製程式碼
對比Larave-S 與 LaravelTW擴充套件
- 兩者在Github的活躍/Star/fork方面不分伯仲
- laravel-s: 特性多,QQ群溝通快,更新活躍
- swooletw: 臺灣社群維護,支援socket.io
- laravel-s在處理異常時直接返回500並提示錯誤,不太適合JSON返回場景
- laravetw 在HTTP與WebSocket通過Route區分開來,更符合Laravel的規範
綜上述,推薦使用LaravelTW擴充套件。
安裝LaravelS
composer
安裝最新版本
composer require "hhxsv5/laravel-s:~3.5.0" -vvv
複製程式碼
釋出配置
php artisan laravels publish
複製程式碼
開啟HTTP服務
[root@iz8vbh3xuahhi5gqllg1u1z current]# php bin/laravels start
_ _ _____
| | | |/ ____|
| | __ _ _ __ __ ___ _____| | (___
| | / _` | '__/ _` \ \ / / _ \ |\___ \
| |___| (_| | | | (_| |\ V / __/ |____) |
|______\__,_|_| \__,_| \_/ \___|_|_____/
Speed up your Laravel/Lumen
>>> Components
+-------------------------+--------------+
| Component | Version |
+-------------------------+--------------+
| PHP | 7.2.22 |
| Swoole | 4.4.13-alpha |
| LaravelS | 3.5.14 |
| Laravel Framework [dev] | 6.4.1 |
+-------------------------+--------------+
>>> Protocols
+-----------+--------+-------------------+----------------+
| Protocol | Status | Handler | Listen At |
+-----------+--------+-------------------+----------------+
| Main HTTP | On | Laravel Framework | 127.0.0.1:5200 |
+-----------+--------+-------------------+----------------+
>>> Feedback: https://github.com/hhxsv5/laravel-s
[2019-11-13 09:14:52] [TRACE] Swoole is running,press Ctrl+C to quit.
複製程式碼
使用Supervisor管理程式
[program:develop-laravel-swoole-api]
command=/usr/bin/php /var/www/develop/zqz/api/current/bin/laravels start -i
numprocs=1
autostart=true
autorestart=true
startretries=3
redirect_stderr=true
stdout_logfile=/var/www/develop/zqz/api/current/storage/logs/supervisord-stdout.log
user=apache
複製程式碼
NGINX 配置
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
upstream swoole {
# 通過 IP:Port 連線
server 127.0.0.1:5200 weight=5 max_fails=3 fail_timeout=30s;
# 通過 UnixSocket Stream 連線,小訣竅:將socket檔案放在/dev/shm目錄下,可獲得更好的效能
#server unix:/xxxpath/laravel-s-test/storage/laravels.sock weight=5 max_fails=3 fail_timeout=30s;
#server 192.168.1.1:5200 weight=3 max_fails=3 fail_timeout=30s;
#server 192.168.1.2:5200 backup;
keepalive 16;
}
server {
listen 80;
server_name api-dev.zqz.com;
root /var/www/develop/zqz/api/current/public;
access_log /var/log/nginx/api-dev.zqz.com.access.log main;
gzip on;
gzip_comp_level 9;
gzip_buffers 4 32k;
gzip_min_length 1k;
gzip_types text/plain application/json application/x-javascript application/css application/xml application/xml+rss text/javascript application/x-httpd-php image/jpeg image/gif image/png image/x-ms-bmp;
gzip_vary on;
autoindex off;
index index.html index.htm;
# Nginx處理靜態資源(建議開啟gzip),LaravelS處理動態資源。
location / {
try_files $uri @laravels;
}
# Http和WebSocket共存,Nginx通過location區分
# Javascript: var ws = new WebSocket("ws://laravels.com/ws");
location =/ws {
proxy_http_version 1.1;
# proxy_connect_timeout 60s;
# proxy_send_timeout 60s;
# proxy_read_timeout:如果60秒內被代理的伺服器沒有響應資料給Nginx,那麼Nginx會關閉當前連線;同時,Swoole的心跳設定也會影響連線的關閉
# proxy_read_timeout 60s;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Real-PORT $remote_port;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header Scheme $scheme;
proxy_set_header Server-Protocol $server_protocol;
proxy_set_header Server-Name $server_name;
proxy_set_header Server-Addr $server_addr;
proxy_set_header Server-Port $server_port;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_pass http://swoole;
}
location @laravels {
proxy_http_version 1.1;
# proxy_connect_timeout 60s;
# proxy_send_timeout 60s;
# proxy_read_timeout 120s;
proxy_set_header Connection "";
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Real-PORT $remote_port;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header Scheme $scheme;
proxy_set_header Server-Protocol $server_protocol;
proxy_set_header Server-Name $server_name;
proxy_set_header Server-Addr $server_addr;
proxy_set_header Server-Port $server_port;
proxy_pass http://swoole;
}
}
複製程式碼
安裝laraveltw/laravel-swoole
composer
安裝最新版本
composer require swooletw/laravel-swoole -vvv
複製程式碼
釋出配置
php artisan vendor:publish --tag=laravel-swoole
複製程式碼
執行HTTP服務
[root@iz8vbh3xuahhi5gqllg1u1z current]# php artisan swoole:http infos
+-----------------+---------------------------------------------------------------------------------+
| Name | Value |
+-----------------+---------------------------------------------------------------------------------+
| PHP Version | 7.2.22 |
| Swoole Version | 4.4.13-alpha |
| Laravel Version | 6.4.1 |
| Listen IP | 127.0.0.1 |
| Listen Port | 1215 |
| Server Status | Offline |
| Reactor Num | 8 |
| Worker Num | 8 |
| Task Worker Num | 0 |
| Websocket Mode | Off |
| Master PID | None |
| Manager PID | None |
| Log Path | /var/www/develop/zqz/api/releases/05c0ab09/storage/logs/swoole_http.log |
+-----------------+---------------------------------------------------------------------------------+
複製程式碼
使用Supervisor管理程式
[program:develop-laravel-swoole-api]
command=/usr/bin/php /var/www/develop/zqz/api/current/artisan swoole:http start
numprocs=1
autostart=true
autorestart=true
startretries=3
user=apache
複製程式碼
NGINX配置
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
server {
listen 80;
server_name api-dev.zqz.com;
root /var/www/develop/zqz/api/current/public;
access_log /var/log/nginx/api-dev.zqz.com.access.log main;
gzip on;
gzip_comp_level 9;
gzip_buffers 4 32k;
gzip_min_length 1k;
gzip_types text/plain application/json application/x-javascript application/css application/xml application/xml+rss text/javascript application/x-httpd-php image/jpeg image/gif image/png image/x-ms-bmp;
gzip_vary on;
autoindex off;
index index.html index.htm;
location = /index.php {
# Ensure that there is no such file named "not_exists"
# in your "public" directory.
try_files /not_exists @swoole;
}
# any php files must not be accessed
#location ~* \.php$ {
# return 404;
#}
location / {
try_files $uri $uri/ @swoole;
}
location @swoole {
set $suffix "";
if ($uri = /index.php) {
set $suffix ?$query_string;
}
proxy_http_version 1.1;
proxy_set_header Host $http_host;
proxy_set_header Scheme $scheme;
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;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
# IF https
# proxy_set_header HTTPS "on";
proxy_pass http://127.0.0.1:1215$suffix;
}
}
複製程式碼
問題集錦
$ vi config/swoole_http.php
...
'providers' => [
Illuminate\Pagination\PaginationServiceProvider::class,//Solve the error:`Auth guard driver [api] is not defined.`
Laravel\Passport\PassportServiceProvider::class,],...
複製程式碼
wrk-HTTP基準測試
wrk是一種現代HTTP基準測試工具,當在單個多核CPU上執行時,能夠產生大量負載。它結合了多執行緒設計和可擴充套件的事件通知系統,例如epoll和kqueue。
命令列選項
-c,--connections: total number of HTTP connections to keep open with
each thread handling N = connections/threads
-d,--duration: duration of the test,e.g. 2s,2m,2h
-t,--threads: total number of threads to use
-s,--script: LuaJIT script,see SCRIPTING
-H,--header: HTTP header to add to request,e.g. "User-Agent: wrk"
--latency: print detailed latency statistics
--timeout: record a timeout if a response is not received within
this amount of time.
複製程式碼
wrk
壓測
- CentOS 7.X
- 8 CPU 16 G
# 使用10個執行緒建立100個連線請求
$ wrk -t10 -c100 http://api-dev.zqz.com
複製程式碼
使用NGINX
+ PHP-FPM
Running 10s test @ http://api-dev.zqz.com
10 threads and 100 connections
Thread Stats Avg Stdev Max +/- Stdev
Latency 364.10ms 347.89ms 2.00s 86.97%
Req/Sec 10.64 8.31 59.00 67.01%
746 requests in 10.10s,1.30MB read
Socket errors: connect 0,read 0,write 0,timeout 86
Non-2xx or 3xx responses: 746
Requests/sec: 73.86
Transfer/sec: 132.15KB
複製程式碼
使用 NGINX
+ Swoole(laraveltw)
Running 10s test @ http://api-dev.zqz.com
10 threads and 100 connections
Thread Stats Avg Stdev Max +/- Stdev
Latency 234.30ms 275.83ms 1.37s 81.79%
Req/Sec 39.66 29.85 200.00 78.56%
3816 requests in 10.10s,1.18MB read
Socket errors: connect 0,timeout 77
Non-2xx or 3xx responses: 3816
Requests/sec: 377.69
Transfer/sec: 119.50KB
複製程式碼
Speed Up Laravel on Top of Swoole
在 laradock 環境中使用 laravel-swoole 加速你的 laravel 應用