PHP网络编程:如何正确搭建HTTP服务

时间:2021-11-20 来源:未知网络 作者:996建站网

大部分的传统FPM项目性能瓶颈在于每次请求重新创建ZendVM的开销、IO 阻塞导致的上下文频繁切换。Swoole解决的就是这类问题。

这篇文章教大家如何让SwooleHTTP服务器性能达到最大。

压测脚本如下,机器的配置是单核、2G内存、50G硬盘:

<?php
use Swoole\Http\Request;
use Swoole\Http\Response;
$process = new Swoole\Process(function (Swoole\Process $process) {
    $server = new Swoole\Http\Server('127.0.0.1', 9501, SWOOLE_BASE);
    $server->set([
        'log_file' => '/dev/null',
        'log_level' => SWOOLE_LOG_INFO,
        'worker_num' => swoole_cpu_num() * 2,
        // 'hook_flags' => SWOOLE_HOOK_ALL,
    ]);
    $server->on('workerStart', function () use ($process, $server) {
        $process->write('1');
    });
    $server->on('request', function (Request $request, Response $response) use ($server) {
        try {
            $redis = new Redis;
            $redis->connect('127.0.0.1', 6379);
            $greeter = $redis->get('greeter');
            if (!$greeter) {
                throw new RedisException('get data failed');
            }
            $response->end("<h1>{$greeter}</h1>");
        } catch (\Throwable $th) {
            $response->status(500);
            $response->end();
        }
    });
    $server->start();
});
if ($process->start()) {
    register_shutdown_function(function () use ($process) {
        $process::kill($process->pid);
        $process::wait();
    });
    $process->read(1);
    System('ab -c 256 -n 10000 -k http://127.0.0.1:9501/ 2>&1');
}

PHP网络编程:如何正确搭建HTTP服务插图

微信扫一扫 关注公众号

微信扫一扫 使用小程序

百度扫一扫 使用小程序