使用 swoole 加速 Larave Restful API 介面(1)

auth_openid發表於2021-11-06
  • 修改 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
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章