Process\Pool

进程池,基于ServerManager模块实现。可管理多个工作进程。该模块的核心功能为进程管理,相比Process实现多进程,Process\Pool更加简单,封装层次更高,开发者无需编写过多代码即可实现进程管理功能。

此特性需要2.1.2或更高版本

常量定义

  • SWOOLE_IPC_MSGQUEUE :系统消息队列通信
  • SWOOLE_IPC_SOCKETSOCKET通信

异步支持

  • 可在onWorkerStart中使用Swoole提供的异步或协程API,工作进程即可实现异步
  • 底层自带的消息队列和SOCKET通信均为同步阻塞IO

  • Ma.Alex

    $workerNum = 10; $pool = new Swoole\Process\Pool($workerNum);

    $pool->on("WorkerStart", function ($pool, $workerId) { echo "Worker#{$workerId} is started\n"; $redis = new Redis(); $redis->pconnect('127.0.0.1', 6379); $key = "key1"; while (true) { $msgs = $redis->brpop($key, 2); if ( $msgs == null) continue; var_dump($msgs); } });

    $pool->on("WorkerStop", function ($pool, $workerId) { echo "Worker#{$workerId} is stopped\n"; });

    $pool->start();

  • Ma.Alex

    $workerNum = 10;
    $pool = new Swoole\Process\Pool($workerNum);
    
    $pool->on("WorkerStart", function ($pool, $workerId) {
        echo "Worker#{$workerId} is started\n";
        $redis = new Redis();
        $redis->pconnect('127.0.0.1', 6379);
        $key = "key1";
        while (true) {
             $msgs = $redis->brpop($key, 2);
             if ( $msgs == null) continue;
             var_dump($msgs);
         }
    });
    
    $pool->on("WorkerStop", function ($pool, $workerId) {
        echo "Worker#{$workerId} is stopped\n";
    });
    
    $pool->start();