Swoole 中使用 HTTP 异步服务器、HTTP 协程服务器

HTTP 异步风格服务器

# http_server.php

$http = new Swoole\Http\Server("0.0.0.0", 9501);

// 设置服务器运行参数
$serv->set(array(
    'daemonize'     => 1,  // 作为守护进程运行,需同时设置log_file
    'log_file'      => '/www/logs/swoole.log',  // 指定标准输出和错误日志文件
));

// HTTP 服务器只需要监听 onRequest 事件
$http->on('request', function ($request, $response) {
    // 响应 favicon.ico 请求
    if ($request->server['path_info'] == '/favicon.ico' || $request->server['request_uri'] == '/favicon.ico') {
        $response->end();
        return;
    }
    
    var_dump($request->get, $request->post);
    
    // URL路由器
    list($controller, $action) = explode('/', trim($request->server['request_uri'], '/'));
    if (empty($controller)) {
        $controller = 'IndexController';
    }
    if (empty($action)) {
        $action = 'index';
    }
    (new $controller)->$action($request, $response);
});

class IndexController {
    public function index($request, $response) {
        $rand = rand(1000, 9999);
        $response->header("Content-Type", "text/html; charset=utf-8");
        
        // 输出一段 HTML 内容
        $response->end("<h1>Hello Swoole. #{$rand}</h1>");
    }
}

// 启动 HTTP 服务器
$http->start();

运行并测试 HTTP 异步风格服务器

# 如果程序已经运行,先结束进程
kill -9 11591

# 在 cli 命令行环境运行服务端
php http_server.php

# 查看服务器监听的端口
netstat -an | grep 9501

# 访问 http://127.0.0.1:9501 查看程序的结果
curl http://127.0.0.1:9501

# 使用 Apache bench 工具进行压力测试
ab -c 200 -n 200000 -k http://127.0.0.1:9501/

使用 Nginx 作为代理

server {
    root /wwwroot/swoole_demo/;
    server_name local.swoole.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;
        }
    }
}

HTTP 协程风格服务器

Co\run(function () {
    $server = new Co\Http\Server("127.0.0.1", 9501, false);
    $server->handle('/', function ($request, $response) use ($server) {
        // URL路由器
        list($controller, $action) = explode('/', trim($request->server['request_uri'], '/'));
        if (empty($controller)) {
            $controller = 'IndexController';
        }
        if (empty($action)) {
            $action = 'index';
        }
        (new $controller)->$action($request, $response);
    });
    $server->start();
});

HTTP 协程客户端

官方建议使用 Saber

猜你喜欢

转载自www.cnblogs.com/danhuang/p/13195451.html
今日推荐