使用 swoole 加速 Larave Restful API 接口(1)

PHP技术
435
0
0
2022-07-19
标签   Swoole
  • 修改 dnmp 的 .env 文件, php 配置 swoole 扩展
PHP_EXTENSIONS=swoole
  • 销毁容器
docker-compose down
  • 重新构建 php 容器
docker-compose build php
  • 启动
docker-compose up -d
  • 查看 安装的 swoole 扩展
php -m | grep swoole
  • laravel 安装 swooletw/laravel-swoole
composer require swooletw/laravel-swoole
php artisan vendor:publish --tag=laravel-swoole
  • laravel .env 配置
SWOOLE_HTTP_PORT=1215
SWOOLE_HTTP_HOST=0.0.0.0    # 避坑
SWOOLE_HTTP_WORKER_NUM=1
SWOOLE_HTTP_TASK_WORKER_NUM=1
  • 启动 swoole-http
php artisan swoole-http start
  • swoole_http_server对Http协议的支持并不完整,建议仅作为应用服务器。并且在前端增加Nginx作为代理
  • nginx 配置如下:
  • nginx 开放 8003 端口
  • root 配置项目目录
  • proxy_pass http://xxxxxx:1215$suffix; # 使用宿主机 IP,不要使用 127.0.0.1:1215
map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}

server {
    listen 8003;    
    server_name 127.0.0.1;
    root   /www/php/sw/public;
    index index.php;
    error_log  /var/log/nginx/nginx.sw1103.error.log  warn;
    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://192.168.1.120:1215$suffix;
    }

}
  • 安装压力测试 ab
apk add apache2-utils