swoole是事件驱动的,server.php一直监听端口,当客户端有数据流过去,则进行监听读取,并进处理。


安装环境


应该保证系统中安装了如下软件:

gcc-4.4+

make

autoconf


PECL安装

pecl install swoole


php.ini 配置

extension=swoole.so


查看是否安装成功

php -m | grep swoole

> swoole


swoole升级


查看当前版本

 

php --ri swoole | grep Version

#结果

> Version => 1.9.6


pecl升级

 

pecl upgrade swoole   

                                      

swoole进程初识


swoole 默认是多进程模式

Master进程 / Manager进程 / Worker进程 / Task进程

 


 

server实例代码


server-process.php


$serv = new swoole_server('127.0.0.1', 9501);

$serv->set([

    'worker_num' => 2,

    'task_worker_num' => 1,

]);

$serv->on('Connect', function ($serv, $fd) {

});

$serv->on('Receive', function ($serv, $fd, $fromId, $data) {

});

$serv->on('Close', function ($serv, $fd) {

});

$serv->on('Task', function ($serv, $taskId, $fromId, $data) {

});

$serv->on('Finish', function ($serv, $taskId, $data) {

});

 

$serv->start();


对实例代码 进行pstree进程关系

 

pstree的结果有5个进程,因为swoole的进程模型是(Master-Manager-Worker),5个进程 = master进程(1个) + manager进程(1个) + worker_num(2个) + task_worker_num(1个)


$ pstree | grep server-process

 

 | |   \-+= 02548 php server-process.php

 | |     \-+- 02549 php server-process.php

 | |       |--- 02550 php server-process.php

 | |       |--- 02551 php server-process.php

 | |       \--- 02552 php server-process.php

 |     \--- 02572 grep server-process


从结果可以看出:

02548 是Master进程,它处于“root”层级

02549 是Manager进程

Worker进程和Task进程就是 02550、02551和02552


设置进程名称备注,再进行pstree进程关系

 

Master进程:

    启动:onStart

    关闭:onShutdown


Manager进程:

    启动:onManagerStart

    关闭:onManagerStop


Worker进程:

    启动:onWorkerStart

    关闭:onWorkerStop


mac下不支持swoole_set_process_name函数,可以用centos进行测试


$serv->on("start", function ($serv){

    swoole_set_process_name('server-process: master');

});

// 以下回调发生在Manager进程

$serv->on('ManagerStart', function ($serv){

    swoole_set_process_name('server-process: manager');

});

$serv->on('WorkerStart', function ($serv, $workerId){

    if($workerId < $serv->setting['worker_num']) {

        // $workerId = 0~worker_num之间,则为worker进程

        swoole_set_process_name("server-process: worker");

    } else {

        // $workerId >= worker_num之间,则为task进程

        swoole_set_process_name("server-process: task");

    }

});

ps出来的结果


# ps aux | grep server-process

root     27546  xxx... server-process: master

root     27547  xxx... server-process: manager

root     27549  xxx... server-process: task worker

root     27550  xxx... server-process: worker

root     27551  xxx... server-process: worker

root     27570  xxx... grep --color=auto simple