性能怪兽swoole,碾压传统web运行方式

性能怪兽swoole,碾压传统web运行方式

性能怪兽<a href='/tag/swoole.html'>swoole</a>,碾压传统web运行方式

传统的php运行方式是nginx+apache/php-fpm,这种方式比较消耗资源,一段php脚本在执行前要经过nginx处理、apache处理、文件io读取、语法解析、创建数据库连接等一系列的过程,消耗了太多的资源,在php请求脚本运行完后,这些资源又全部释放,好处就是内存不会泄露,坏处就是资源重新加载失败,浪费资源,在高并发下会出现力不从心。

那么swoole扩展是c语言编写的一个php扩展,实现了udp、tcp、websocket等协议,内置了这些协议的服务器,完全摆脱apache及php-fpm,在phpcli模式下运行,一旦运行,所有的文件都会被加载进内存,所有的数据库缓存连接创建后会一直存在,不会回收,大大的提升了并发量,降低了资源的消耗。

我们看看数据对比,直接是apache和php-fpm的7倍

运行方式

Swoole EventTCP

Swoole SelectTCP

Swoole BlockTCP

Apache/Prefork

单进程

571.70 [#/sec]

174.916 [ms]

1.749 [ms]

659.01 [#/sec]

151.743 [ms]

1.517 [ms]

561.24 [#/sec]

178.178 [ms]

1.782

80.57

1241.083 [ms]

12.411 [ms]

4进程

1153.63 [#/sec]

86.683 [ms]

0.867 [ms]

1010.08 [#/sec]

99.002 [ms]

0.990 [ms]

1094.58 [#/sec]

91.359 [ms]

0.914 [ms]

那么如何安装swoole

我们以centos为例,执行下面的命令

pecl install swoole

swoole实现了http、tcp、udp等协议,直接使用

http服务器

<?php
$http = new swoole_http_server("127.0.0.1", 9501);

$http->on("start", function ($server) {
    echo "Swoole http server is started at http://127.0.0.1:9501\n";
});

$http->on("request", function ($request, $response) {
    $response->header("Content-Type", "text/plain");
    $response->end("Hello World\n");
});

$http->start();
?>

websocket服务器

<?php
$server = new swoole_websocket_server("127.0.0.1", 9502);

$server->on('open', function($server, $req) {
    echo "connection open: {$req->fd}\n";
});

$server->on('message', function($server, $frame) {
    echo "received message: {$frame->data}\n";
    $server->push($frame->fd, json_encode(["hello", "world"]));
});

$server->on('close', function($server, $fd) {
    echo "connection close: {$fd}\n";
});

?>

tcp 服务

<?php
$server = new swoole_server("127.0.0.1", 9503);
$server->on('connect', function ($server, $fd){
    echo "connection open: {$fd}\n";
});
$server->on('receive', function ($server, $fd, $reactor_id, $data) {
    $server->send($fd, "Swoole: {$data}");
    $server->close($fd);
});
$server->on('close', function ($server, $fd) {
    echo "connection close: {$fd}\n";
});
$server->start();
?>

tcp客户端

<?php
$client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC);
$client->on("connect", function($cli) {
    $cli->send("hello world\n");
});
$client->on("receive", function($cli, $data){
    echo "received: {$data}\n";
});
$client->on("error", function($cli){
    echo "connect failed\n";
});
$client->on("close", function($cli){
    echo "connection close\n";
});
$client->connect("127.0.0.1", 9501, 0.5);
?>

是不是很强悍

{{collectdata}}

网友评论0