这篇开始分析BaseServer的run方法,这里完成了server的真实启动。
//启动server,我们假定cmd为start,也就是分析initServer和start方法,其中extstart和extrestart是不注册zk的p2p模式,这里可以看到只是设置了属性,其他的流程和start一样的。
public function run($cmd = 'help')
{
switch ($cmd)
{
//start
case 'extstart':
case 'extrestart':
//开启p2p模式
$this->start_without_registry = true;
case 'start':
case 'restart':
$this->initServer();
$this->start();
break;
default:
echo 'Usage: app_admin.php start | stop | reload | restart | extstart | extrestart' . PHP_EOL;
break;
}
}
private function initServer()
{
//第一行和第二行,创建swoole_server对象,这里调用的是swoole的api信息
$swooleServerName = '\swoole_server';
$this->sw = new $swooleServerName($this->host, $this->port, $this->mode, $this->sockType);
//创建监控器,后续再分析
$monitor = new AppMonitor($this->processName, $this->config);
//设置appMonitor
$monitor->setServer($this->sw);
$this->sw->appMonitor = $monitor;
//创建overload monitor,超载监控
$this->overloadMonitor = new OverloadMonitor($this->processName);
//对整数进行容错处理
$this->setting['worker_num'] = intval($this->setting['worker_num']);
$this->setting['dispatch_mode'] = intval($this->setting['dispatch_mode']);
$this->setting['daemonize'] = intval($this->setting['daemonize']);
//设置swoole_server的属性信息
$this->sw->set($this->setting);
//设置swoole_server的回调函数信息
//master进程启动时的回调函数
$this->sw->on('Start', array($this, 'onMasterStart'));
//manager进程启动时的回调函数
$this->sw->on('ManagerStart', array($this, 'onManagerStart'));
//manager进程停止时的回调函数
$this->sw->on('ManagerStop', array($this, 'onManagerStop'));
//worker进程启动时的回调函数
$this->sw->on('WorkerStart', array($this, 'onWorkerStart'));
//网络连接建立时的回调函数
$this->sw->on('Connect', array($this, 'onConnect'));
//接收到数据时的回调函数
$this->sw->on('Receive', array($this, 'onReceive'));
//连接关闭时的回调函数
$this->sw->on('Close', array($this, 'onClose'));
//worker进程停止时的回调函数
$this->sw->on('WorkerStop', array($this, 'onWorkerStop'));
//task线程的逻辑,这里实际没用到
if (isset($this->setting['task_worker_num']))
{
$this->sw->on('Task', array($this, 'onTask'));
$this->sw->on('Finish', array($this, 'onFinish'));
}
//worker进程发生错误时的回调函数
$this->sw->on('WorkerError', array($this, 'onWorkerError'));
// add listener
if (is_array($this->listen))
{
foreach($this->listen as $v)
{
if (empty($v['host']) || empty($v['port']))
{
continue;
}
//设置server对应的IP和监听端口信息
$this->sw->addlistener($v['host'], $v['port'], $this->sockType);
}
}
$this->logger->info("server host:".$this->host.'|'.$this->port);
}
protected function start()
{
if ($this->checkServerIsRunning()) //判断master进程是否已经在运行中
{
$this->logger->warn($this->processName . ": master process file " . $this->masterPidFile . " has already exists!");
$this->logger->warn($this->processName . ": start [OK]");
return false;
}
$this->logger->info($this->processName . ": start [OK]");
$this->sw->start();//调用Swoole的api,真实启动swoole,也就是Provider。
}
|