bean.php
中添加一下配置
'processPool' => [
// 进程处理类,必填
'class' => \Swoft\Process\ProcessPool::class,
// 进程数,进程id从排序,必填
'workerNum' => 3,
// IPC类型,进程间通信类型,参数参考swoole,选填
'ipcType' => SWOOLE_IPC_NONE
// 是否开启协程,默认是开启,选填
'coroutine' => true
]
进程处理文件位于App/Process
必须继承ProcessInterface
使用注释@Process
标记
workerId=0
或workerId={1,2}
选择进程id,id从0开始,可以安排多个进程;workerId 如果不写默认情况,当前程序流程绑定到其它未绑定的进程
Worker1Process.php
示例
<?php declare(strict_types=1);
/**
* This file is part of Swoft.
*
* @link https://swoft.org
* @document https://swoft.org/docs
* @contact group@swoft.org
* @license https://github.com/swoft-cloud/swoft/blob/master/LICENSE
*/
namespace App\Process;
use Swoft\Amqp\Amqp;
use Swoft\Log\Helper\CLog;
use Swoft\Process\Annotation\Mapping\Process;
use Swoft\Process\Contract\ProcessInterface;
use Swoole\Coroutine;
use Swoole\Process\Pool;
/**
* Class Worker1Process
*
* @since 2.0
*
* @Process(workerId=0)
*/
class Worker1Process implements ProcessInterface
{
/**
* @param Pool $pool
* @param int $workerId
*/
public function run(Pool $pool, int $workerId): void
{
while (true) {
CLog::info('worker-' . $workerId);
CLog::info('run method: '.__METHOD__);
$channel = Amqp::channel('channel_1');
$channel->listen(function ($message){
//$message:数据结构(json_encode)之后
//{"body":"hey!-----9","body_size":10,"is_truncated":false,"content_encoding":null,"delivery_info":{"channel":{"callbacks":{"amq.ctag-epGZgfHej3YrjZk2FBvp0A":{}}},"delivery_tag":99,"redelivered":false,"exchange":"exchange_test","routing_key":"example-test-routing-key","consumer_tag":"amq.ctag-epGZgfHej3YrjZk2FBvp0A"}}
CLog::info('message:'. json_encode($message));
});
$name = 'steve';
vdump(context()->getResponse()->withContent('Hello' . ($name === '' ? '' : ", {$name}")));
Coroutine::sleep(3);
}
}
}
进程单独启动
// 启动
php bin/swoft process:start
// 后台
php bin/swoft process:start -d
// 重启,进程池全部重启
php bin/swoft process:reload
// 停止,进程池全部停止
php bin/swoft process:stop