hyperf框架熱重啟實現(xiàn)

1.為什么需要熱重啟

a.在開發(fā)過程中,尤其在功能調(diào)試期間,經(jīng)常會有微調(diào)整。每次如果都手動重啟,那肯定還是很抓狂的;
b.在生成部署時,一鍵熱重啟,實現(xiàn)服務持續(xù)可用;

2.實現(xiàn)代碼

注意:需要將服務設置成守護進程模式。(config/server.php => 'daemonize' => 1)

手動關(guān)閉和重啟命令:
php bin/hyberf.php stop/reload
代碼:
1.首先生成一個command文件;
2.handle的代碼:
          $config = $this->container->get(ConfigInterface::class);
          $serverConfig = $config->get('server');
         if (file_exists($serverConfig['settings']['pid_file'])) {
            $pid = (int)file_get_contents($serverConfig['settings']['pid_file']);
            posix_kill($pid, SIGTERM); // 手動關(guān)閉,重啟:posix_kill($pid, SIGUSR1);
            $this->line('stop server success!!!', 'info');
        } else {
            $this->line('file not exit, stop server fail!!!', 'error');
        }
自動重啟(僅支持linux系統(tǒng))
1.隨著server啟動,自動監(jiān)聽。通過自定義process來實現(xiàn)
2.核心代碼:
class HotReload extends AbstractProcess
{
    protected $pid;
    /**
     * @var resource
     */
    protected $inotify;

    protected $reloading = false;

    protected $afterNSeconds = 1;

    protected $watchFiles = array();

    protected $reloadFileTypes = array('.php' => true);

    protected $events;

    protected $rootDirs = array();

    public function handle(): void
    {
        $config = $this->container->get(ConfigInterface::class);
        $serverConfig = $config->get('server');
        if (file_exists($serverConfig['settings']['pid_file'])) {
            $this->pid = $serverPid =  (int)file_get_contents($serverConfig['settings']['pid_file']);
        } else {
            throw new ServerException('pid file not exit');
        }
        if (posix_kill($serverPid, 0) === false) {
            throw new ServerException("Process#$serverPid not found.");
        }
        $this->inotify = inotify_init();
        $this->events = IN_MODIFY | IN_DELETE | IN_CREATE | IN_MOVE;
        swoole_event_add((int) $this->inotify, function ($ifd) {
            $events = inotify_read($this->inotify);
            if (!$events) {
                return;
            }
            foreach ($events as $ev) {
                if ($ev['mask'] == IN_IGNORED) {
                    continue;
                } else if ($ev['mask'] == IN_CREATE or $ev['mask'] == IN_DELETE or $ev['mask'] == IN_MODIFY or $ev['mask'] == IN_MOVED_TO or $ev['mask'] == IN_MOVED_FROM) {
                    $fileType = strrchr($ev['name'], '.');
                    //非重啟類型
                    if (!isset($this->reloadFileTypes[$fileType])) {
                        continue;
                    }
                }
                //正在reload,不再接受任何事件,凍結(jié)10秒
                if (!$this->reloading) {
                    //有事件發(fā)生了,進行重啟
                    swoole_timer_after($this->afterNSeconds * 1000, array($this, 'reload'));
                    $this->reloading = true;
                }
            }
        });

        $this->watch(BASE_PATH . '/app');
        $this->watch(BASE_PATH . '/config');
        $this->addFileType('.php');
        $this->run();
    }

    /**
     * 測試環(huán)境自動重啟
     * @return bool
     */
    public function isEnable(): bool
    {
        $appEnv = env('APP_ENV', 'dev');
        if ($appEnv == 'dev') {
            if (!function_exists('inotify_init')) {
                return false;
            }
            return true;
        } else {
            return false;
        }
    }

    protected function watch($dir, $root = true)
    {
        //目錄不存在
        if (!is_dir($dir)) {
            throw new ServerException("[$dir] is not a directory.");
        }
        //避免重復監(jiān)聽
        if (isset($this->watchFiles[$dir])) {
            return false;
        }
        //根目錄
        if ($root) {
            $this->rootDirs[] = $dir;
        }
        $wd = inotify_add_watch($this->inotify, $dir, $this->events);
        $this->watchFiles[$dir] = $wd;
        $files = scandir($dir);
        foreach ($files as $f) {
            if ($f == '.' or $f == '..') {
                continue;
            }
            $path = $dir . '/' . $f;
            //遞歸目錄
            if (is_dir($path)) {
                $this->watch($path, false);
            }
            //檢測文件類型
            $fileType = strrchr($f, '.');
            if (isset($this->reloadFileTypes[$fileType])) {
                $wd = inotify_add_watch($this->inotify, $path, $this->events);
                $this->watchFiles[$path] = $wd;
            }
        }
        return true;
    }

}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容