在使用swoole的項(xiàng)目中, 在開(kāi)發(fā)時(shí), 會(huì)經(jīng)常改動(dòng)代碼并查看效果, 由于swoole項(xiàng)目是常駐內(nèi)存的, 代碼改動(dòng)后并不會(huì)影響已經(jīng)在運(yùn)行中并加載過(guò)該代碼的程序, 所以需要重啟項(xiàng)目. 為了在改動(dòng)代碼之后可以自動(dòng)重啟項(xiàng)目, 寫(xiě)了如下腳本(需要inotify拓展)
// watcher.php
// 我這里用的laravoole開(kāi)發(fā)laravel項(xiàng)目,所以只需要reload,并不需要把master進(jìn)程也重啟
<?php
new Watcher(__DIR__, function () {
echo 'modified' . PHP_EOL;
passthru('php artisan laravoole reload');
echo date('H:i:s') . ' 已執(zhí)行 php artisan laravoole reload' . PHP_EOL;
}, ['/storage']);
class Watcher
{
protected $cb; // 回調(diào)函數(shù), 重啟邏輯在回調(diào)里面定義
protected $modified = false; // 是否有代碼更新
protected $minTime = 2000; // 最小觸發(fā)重啟間隔, 防止密集更新代碼導(dǎo)致頻繁重啟項(xiàng)目
protected $ignored = []; // 忽略的目錄, 用phpstorm開(kāi)發(fā)的話最好把 .idea目錄加進(jìn)來(lái), 不然會(huì)頻繁重啟.如果重啟有記錄日志, 把日志也加進(jìn)來(lái), 不然會(huì)導(dǎo)致無(wú)限重啟(因?yàn)槟阋恢貑⒕蜁?huì)檢測(cè)到文件改動(dòng), 繼續(xù)重啟)
public function __construct($dir, $cb, $ignore = [])
{
$this->cb = $cb;
foreach ($ignore as $item) {
$this->ignored[] = $dir . $item;
}
$this->watch($dir);
}
protected function watch($directory)
{
//創(chuàng)建一個(gè)inotify句柄
$fd = inotify_init();
//監(jiān)聽(tīng)文件,僅監(jiān)聽(tīng)修改操作缕探,如果想要監(jiān)聽(tīng)所有事件可以使用IN_ALL_EVENTS
inotify_add_watch($fd, __DIR__, IN_MODIFY);
foreach ($this->getAllDirs($directory) as $dir) {
inotify_add_watch($fd, $dir, IN_MODIFY);
}
echo 'watch start' . PHP_EOL;
//加入到swoole的事件循環(huán)中
swoole_event_add($fd, function ($fd) {
$events = inotify_read($fd);
if ($events) {
$this->modified = true;
}
});
每 2 秒檢測(cè)一下modified變量是否為真
swoole_timer_tick(2000, function () {
if ($this->modified) {
($this->cb)();
$this->modified = false;
}
});
}
// 使用迭代器遍歷目錄
protected function getAllDirs($base)
{
$files = scandir($base);
foreach ($files as $file) {
if ($file == '.' || $file == '..') continue;
$filename = $base . DIRECTORY_SEPARATOR . $file;
if (in_array($filename, $this->ignored)) continue;
if (is_dir($filename)) {
yield $filename;
yield from $this->getAllDirs($filename);
}
}
}
}