标签归档:swoole

使用Swoole作为服务解决PHP加载耗内存问题

采用swoole主要满足部分程序需要常驻内存和高性能的要求。

代码

<?php
require_once('function.php');

$http = new swoole_http_server("0.0.0.0", 9501);
$http->on('request', function ($request, $response) {
    $time = microtime(true);
    $error_code = 0;
    $error_msg = '';
    $result = [];
    try {
        switch ($request->server['request_uri']) {
            case '/test/':
                $result = get($request);
                break;
            default:
                $error_code = 1;
                $error_msg = '请求url不正确';
                break;

        }
    } catch (Exception $e) {
        $error_code = 1;
        $error_msg = $e->getMessage();
    }

    $time_new = microtime(true);
    $response->header("Content-Type", "text/html; charset=utf-8");
    $response->end(json_encode(
        [
            'code' => $error_code,
            'msg' => $error_msg,
            'time' => $time_new - $time,
            'data' => $result,
        ]
        , JSON_UNESCAPED_UNICODE));
});

$http->set(array(
    'worker_num' => 4,
    'reactor_num' => 4,
    'daemonize' => true,
    'pid_file' => __DIR__ . '/server.pid',
));

$http->start();

部署介绍

因为需要用到PHP的swoole扩展,所以运行脚本需要单独配置

php-service.ini

; 配置swoole 安装说明:https://wiki.swoole.com/wiki/page/6.html
[swoole]
extension=swoole.so

启动脚本

cd php-service
php -c /usr/local/etc/php-service.ini server.php

平滑重启

kill -USR2  `cat server.pid`

通过pid杀死服务

kill `cat server.pid`

nginx配置

server {
    root /data/wwwroot/;
    server_name webservice.liebiao.com;

    location / {
        proxy_http_version 1.1;
        proxy_set_header Connection "keep-alive";
        proxy_set_header X-Real-IP $remote_addr;
        if (!-e $request_filename) {
             proxy_pass http://127.0.0.1:9501;
        }
    }
}