Process\Pool::__construct
创建进程池。函数原型:
function Process\Pool::__construct(int $worker_num, int $ipc_type = 0, int $msgqueue_key = 0, bool $enable_coroutine = false);
参数
$worker_num
:指定工作进程的数量$ipc_type
进程间通信的模式,默认为0
表示不使用任何进程间通信特性- 设置为
0
时必须设置onWorkerStart
回调,并且必须在onWorkerStart
中实现循环逻辑,当onWorkerStart
函数退出时工作进程会立即退出 - 设置为
SWOOLE_IPC_MSGQUEUE
表示使用系统消息队列通信,可设置$msgqueue_key
指定消息队列的KEY
,未设置消息队列KEY
,将申请私有队列 - 设置为
SWOOLE_IPC_SOCKET
表示使用Socket
进行通信,需要使用listen
方法指定监听的地址和端口 - 使用非
0
设置时,必须设置onMessage
回调,onWorkerStart
变更为可选
- 设置为
$enable_coroutine
:启用协程,使用协程后将无法设置onMessage
回调,并且只能使用SWOOLE_IPC_UNIXSOCK
通信方式
协程模式
在4.4
版本中Process\Pool
模块增加了对协程的支持,可以配置第4
个参数为true
来启用。启用协程后底层会
- 禁止设置
onMessage
事件回调 - 在
onWorkerStart
时创建协程,在回调函数中可直接使用协程相关API
- 可使用
$pool->getProcess()->exportSocket()
导出管道句柄,实现Worker
进程间通信
$pool = new Swoole\Process\Pool(1, SWOOLE_IPC_NONE, 0, true);
$pool->on('workerStart', function (Swoole\Process\Pool $pool, int $workerId) {
while (true) {
Co::sleep(0.5);
echo "hello world\n";
}
});
$pool->start();
消息队列
在使用SWOOLE_IPC_MSGQUEUE
时可使用sysvmsg
扩展提供的消息队列API
向工作进程投递任务。
$q = msg_get_queue($key);
foreach (range(1, 100) as $i) {
$data = json_encode(['data' => base64_encode(random_bytes(1024)), 'id' => uniqid(), 'index' => $i,]);
msg_send($q, $i, $data, false);
}
- 必须传入
Pool
创建时使用的key
- 底层不支持
msg_send
的第二个参数mtype
,请传入任意非0
值