/** * 当Gateway启动的时候触发的回调函数 * @return void */ public function onWorkerStart() { // 分配一个内部通讯端口 $this->lanPort = function_exists('posix_getppid') ? $this->startPort - posix_getppid() + posix_getpid() : $this->startPort; if ($this->lanPort < 0 || $this->lanPort >= 65535) { $this->lanPort = rand($this->startPort, 65535); } // 如果有设置心跳,则定时执行 if ($this->pingInterval > 0) { $timer_interval = $this->pingNotResponseLimit > 0 ? $this->pingInterval / 2 : $this->pingInterval; Timer::add($timer_interval, array($this, 'ping')); } if (!class_exists('\\Protocols\\GatewayProtocol')) { class_alias('\\GatewayWorker\\Protocols\\GatewayProtocol', 'Protocols\\GatewayProtocol'); } // 初始化gateway内部的监听,用于监听worker的连接已经连接上发来的数据 $this->_innerTcpWorker = new Worker("GatewayProtocol://{$this->lanIp}:{$this->lanPort}"); $this->_innerTcpWorker->listen(); $this->_innerUdpWorker = new Worker("GatewayProtocol://{$this->lanIp}:{$this->lanPort}"); $this->_innerUdpWorker->transport = 'udp'; $this->_innerUdpWorker->listen(); // 重新设置自动加载根目录 Autoloader::setRootPath($this->_appInitPath); // 设置内部监听的相关回调 $this->_innerTcpWorker->onMessage = array($this, 'onWorkerMessage'); $this->_innerUdpWorker->onMessage = array($this, 'onWorkerMessage'); $this->_innerTcpWorker->onConnect = array($this, 'onWorkerConnect'); $this->_innerTcpWorker->onClose = array($this, 'onWorkerClose'); // 注册gateway的内部通讯地址,worker去连这个地址,以便gateway与worker之间建立起TCP长连接 if (!$this->registerAddress()) { $this->log('registerAddress fail and exit'); Worker::stopAll(); } if ($this->_onWorkerStart) { call_user_func($this->_onWorkerStart, $this); } }
/** * 业务超时回调 * @param int $signal * @throws Exception */ public function timeoutHandler($signal) { switch ($signal) { // 超时时钟 case SIGALRM: // 超时异常 $e = new \Exception("process_timeout", 506); $trace_str = $e->getTraceAsString(); // 去掉第一行timeoutHandler的调用栈 $trace_str = $e->getMessage() . ":\n" . substr($trace_str, strpos($trace_str, "\n") + 1) . "\n"; // 开发者没有设置超时处理函数,或者超时处理函数返回空则执行退出 if (!$this->processTimeoutHandler || !call_user_func($this->processTimeoutHandler, $trace_str, $e)) { Worker::stopAll(); } break; } }