spring-boot-devtools熱部署原理解析

前言

在開發(fā)項目過程中,當(dāng)修改了某些代碼后需要本地驗證時,需要重啟本地服務(wù)進(jìn)行驗證,啟動這個項目,如果項目龐大的話還是需要較長時間的,spring開發(fā)團(tuán)隊為我們帶來了一個插件:spring-boot-devtools,很好的解決了本地驗證緩慢的問題。

簡單介紹

該原理其實很好說明,就是我們在編輯器上啟動項目,然后改動相關(guān)的代碼,然后編輯器自動觸發(fā)編譯替換掉歷史的.class文件后,項目檢測到有文件變更后會重啟srpring-boot項目。
可以看看官網(wǎng)的觸發(fā)描述:
As DevTools monitors classpath resources, the only way to trigger a restart is to update the classpath. The way in which you cause the classpath to be updated depends on the IDE that you are using. In Eclipse, saving a modified file causes the classpath to be updated and triggers a restart. In IntelliJ IDEA, building the project (Build +→+ Build Project) has the same effect.
可以看到,我們引入了插件后,插件會監(jiān)控我們classpath的資源變化,當(dāng)classpath有變化后,會觸發(fā)重啟。很多文章會介紹如何配置自動觸發(fā),本人覺得不是很喜歡這種配置,當(dāng)我們改動代碼時,并不是改動一下就改動完的,我還是喜歡自己點擊Build Project來觸發(fā)重啟。
The restart technology provided by Spring Boot works by using two classloaders. Classes that do not change (for example, those from third-party jars) are loaded into a base classloader. Classes that you are actively developing are loaded into a restart classloader. When the application is restarted, the restart classloader is thrown away and a new one is created. This approach means that application restarts are typically much faster than “cold starts”, since the base classloader is already available and populated.
這里提到了,該插件重啟快速的原因:這里對類加載采用了兩種類加載器,對于第三方j(luò)ar包采用base-classloader來加載,對于開發(fā)人員自己開發(fā)的代碼則使用restartClassLoader來進(jìn)行加載,這使得比停掉服務(wù)重啟要快的多,因為使用插件只是重啟開發(fā)人員編寫的代碼部分。
我這邊做個簡單的驗證:

@Component
@Slf4j
public class Devtools implements InitializingBean {


    @Override
    public void afterPropertiesSet() {
        log.info("guava-jar classLoader: " + BloomFilter.class.getClassLoader().toString());
        log.info("Devtools ClassLoader: " + this.getClass().getClassLoader().toString());
    }


}

這邊先去除spring-boot-devtools插件,跑下工程:

2020-01-21 22:26:27.182  INFO 16648 --- [           main] com.devtools.example.Devtools            : guava-jar classLoader: sun.misc.Launcher$AppClassLoader@18b4aac2
2020-01-21 22:26:27.182  INFO 16648 --- [           main] com.devtools.example.Devtools            : Devtools ClassLoader: sun.misc.Launcher$AppClassLoader@18b4aac2

可以看到,BloomFilter(第三方j(luò)ar包)和Devtools(自己編寫的類)使用的都是AppClassLoader加載的。
我們現(xiàn)在加上插件,然后執(zhí)行下代碼:

啟動服務(wù):
2020-01-22 10:05:37.575  INFO 20940 --- [  restartedMain] com.devtools.example.Devtools            : guava-jar classLoader:sun.misc.Launcher$AppClassLoader@18b4aac2
2020-01-22 10:05:37.575  INFO 20940 --- [  restartedMain] com.devtools.example.Devtools            : Devtools ClassLoader: org.springframework.boot.devtools.restart.classloader.RestartClassLoader@3540628f

修改了代碼插件自動重啟:
2020-01-22 10:07:06.394  INFO 20940 --- [  restartedMain] com.devtools.example.Devtools            : guava-jar classLoader: sun.misc.Launcher$AppClassLoader@18b4aac2
2020-01-22 10:07:06.394  INFO 20940 --- [  restartedMain] com.devtools.example.Devtools            : Devtools ClassLoader: org.springframework.boot.devtools.restart.classloader.RestartClassLoader@769a8133


發(fā)現(xiàn)第三方的jar包的類加載器確實是使用的系統(tǒng)的類加載器,而我們自己寫的代碼的類加載器為RestartClassLoader,并且每次重啟,類加載器的實例都會改變。

修改代碼前.png
修改代碼后.png

上圖為代碼修改前后類文件的變更。

代碼解析

對于springboot的插件,都是從其插件中的spring.factories的配置文件開始的。想探尋其原理,可以看看這篇文章:SpringFactoriesLoader原理解析

devtools-spring.factories.png

順便推薦下:這個字體為最新的idea公司自己定制的字體,據(jù)說對程序員非常友好,使用了下,確實很香:https://www.jetbrains.com/lp/mono/
這里直接到要害,本地開發(fā)工具的配置類為:
org.springframework.boot.devtools.autoconfigure.LocalDevToolsAutoConfiguration


    /**
     * Local Restart Configuration.
     */
    @Configuration
    @ConditionalOnProperty(prefix = "spring.devtools.restart", name = "enabled", matchIfMissing = true)
    static class RestartConfiguration {

        @Autowired
        private DevToolsProperties properties;

        @EventListener
        public void onClassPathChanged(ClassPathChangedEvent event) {
            if (event.isRestartRequired()) {
                Restarter.getInstance().restart(
                        new FileWatchingFailureHandler(fileSystemWatcherFactory()));
            }
        }

        @Bean
        @ConditionalOnMissingBean
        public ClassPathFileSystemWatcher classPathFileSystemWatcher() {
            URL[] urls = Restarter.getInstance().getInitialUrls();
            ClassPathFileSystemWatcher watcher = new ClassPathFileSystemWatcher(
                    fileSystemWatcherFactory(), classPathRestartStrategy(), urls);
            watcher.setStopWatcherOnRestart(true);
            return watcher;
        }

        @Bean
        @ConditionalOnMissingBean
        public ClassPathRestartStrategy classPathRestartStrategy() {
            return new PatternClassPathRestartStrategy(
                    this.properties.getRestart().getAllExclude());
        }

        @Bean
        public HateoasObjenesisCacheDisabler hateoasObjenesisCacheDisabler() {
            return new HateoasObjenesisCacheDisabler();
        }

        @Bean
        public FileSystemWatcherFactory fileSystemWatcherFactory() {
            return new FileSystemWatcherFactory() {

                @Override
                public FileSystemWatcher getFileSystemWatcher() {
                    return newFileSystemWatcher();
                }

            };
        }

        private FileSystemWatcher newFileSystemWatcher() {
            Restart restartProperties = this.properties.getRestart();
            FileSystemWatcher watcher = new FileSystemWatcher(true,
                    restartProperties.getPollInterval(),
                    restartProperties.getQuietPeriod());
            String triggerFile = restartProperties.getTriggerFile();
            if (StringUtils.hasLength(triggerFile)) {
                watcher.setTriggerFilter(new TriggerFileFilter(triggerFile));
            }
            List<File> additionalPaths = restartProperties.getAdditionalPaths();
            for (File path : additionalPaths) {
                watcher.addSourceFolder(path.getAbsoluteFile());
            }
            return watcher;
        }

    }

其中,

@EventListener
        public void onClassPathChanged(ClassPathChangedEvent event) {
            if (event.isRestartRequired()) {
                Restarter.getInstance().restart(
                        new FileWatchingFailureHandler(fileSystemWatcherFactory()));
            }
        }

該類為監(jiān)聽到classpath的classpath的文件變更后,會觸發(fā)ClassPathChangedEvent 事件,并會觸發(fā)springboot的重啟,其內(nèi)部原理為使用了spring的事件監(jiān)聽機(jī)制,如果想補(bǔ)補(bǔ)這方面的內(nèi)容可以看看我自己 寫的這篇文章:Spring觀察者模式原理解析

文件監(jiān)聽機(jī)制

下面看看其文件是如何被監(jiān)聽的

@Bean
        @ConditionalOnMissingBean
        public ClassPathFileSystemWatcher classPathFileSystemWatcher() {
            URL[] urls = Restarter.getInstance().getInitialUrls();
            ClassPathFileSystemWatcher watcher = new ClassPathFileSystemWatcher(
                    fileSystemWatcherFactory(), classPathRestartStrategy(), urls);
            watcher.setStopWatcherOnRestart(true);
            return watcher;
        }

核心為該配置類,該類中包含了重啟觸發(fā)策略ClassPathRestartStrategy,以及監(jiān)聽的路徑url和真正監(jiān)聽的實體類FileSystemWatcher。

public ClassPathFileSystemWatcher(FileSystemWatcherFactory fileSystemWatcherFactory,
            ClassPathRestartStrategy restartStrategy, URL[] urls) {
        Assert.notNull(fileSystemWatcherFactory,
                "FileSystemWatcherFactory must not be null");
        Assert.notNull(urls, "Urls must not be null");
        this.fileSystemWatcher = fileSystemWatcherFactory.getFileSystemWatcher();
        this.restartStrategy = restartStrategy;
        this.fileSystemWatcher.addSourceFolders(new ClassPathFolders(urls));
    }

打斷點進(jìn)去發(fā)現(xiàn):


調(diào)試.png

其傳入的urls即為IDE編譯代碼的路徑,已經(jīng)其觸發(fā)重啟策略中已剔除掉配置項和一些測試的二進(jìn)制文件。
該類ClassPathFileSystemWatcher實例化之后會調(diào)用其afterPropertiesSet方法(實現(xiàn)了InitializingBean)

@Override
    public void afterPropertiesSet() throws Exception {
        if (this.restartStrategy != null) {
            FileSystemWatcher watcherToStop = null;
            if (this.stopWatcherOnRestart) {
                watcherToStop = this.fileSystemWatcher;
            }
            this.fileSystemWatcher.addListener(new ClassPathFileChangeListener(
                    this.applicationContext, this.restartStrategy, watcherToStop));
        }
        this.fileSystemWatcher.start();
    }

可以看到其加入了個ClassPathFileChangeListener對象,后續(xù)該對象是觸發(fā)ClassPathChangedEvent事件的實現(xiàn)者。

ClassPathFileChangeListener(ApplicationEventPublisher eventPublisher,
            ClassPathRestartStrategy restartStrategy,
            FileSystemWatcher fileSystemWatcherToStop) {
        Assert.notNull(eventPublisher, "EventPublisher must not be null");
        Assert.notNull(restartStrategy, "RestartStrategy must not be null");
        this.eventPublisher = eventPublisher;
        this.restartStrategy = restartStrategy;
        this.fileSystemWatcherToStop = fileSystemWatcherToStop;
    }   
    @Override
    public void onChange(Set<ChangedFiles> changeSet) {
        boolean restart = isRestartRequired(changeSet);
        publishEvent(new ClassPathChangedEvent(this, changeSet, restart));
    }

    private void publishEvent(ClassPathChangedEvent event) {
        this.eventPublisher.publishEvent(event);
        if (event.isRestartRequired() && this.fileSystemWatcherToStop != null) {
            this.fileSystemWatcherToStop.stop();
        }
    }

接著上述代碼分析,this.fileSystemWatcher.start(),該代碼為監(jiān)聽文件變化的核心,看看其源碼

/**
     * Start monitoring the source folder for changes.
     */
    public void start() {
        synchronized (this.monitor) {
            saveInitialSnapshots();
            if (this.watchThread == null) {
                Map<File, FolderSnapshot> localFolders = new HashMap<File, FolderSnapshot>();
                localFolders.putAll(this.folders);
                this.watchThread = new Thread(new Watcher(this.remainingScans,
                        new ArrayList<FileChangeListener>(this.listeners),
                        this.triggerFilter, this.pollInterval, this.quietPeriod,
                        localFolders));
                this.watchThread.setName("File Watcher");
                this.watchThread.setDaemon(this.daemon);
                this.watchThread.start();
            }
        }
    }

首先,先保存urls路徑下文件及文件夾的快照信息,包括文件的長度以及其最后修改時間,該信息以FolderSnapshot、FileSnapshot類中進(jìn)行保存。文件的快照信息在該屬性中保存:fileSystemWatcher中的private final Map<File, FolderSnapshot> folders = new HashMap<File, FolderSnapshot>();
往下分析,創(chuàng)建了一個File Watcher的線程,將文件快照信息和listeners(觸發(fā)文件變更事件)當(dāng)做屬性以Watcher對象(實現(xiàn)了Runnable接口)傳入線程中,并啟動線程。

private static final class Watcher implements Runnable {
private Watcher(AtomicInteger remainingScans, List<FileChangeListener> listeners,
                FileFilter triggerFilter, long pollInterval, long quietPeriod,
                Map<File, FolderSnapshot> folders) {
            this.remainingScans = remainingScans;
            this.listeners = listeners;
            this.triggerFilter = triggerFilter;
            this.pollInterval = pollInterval;
            this.quietPeriod = quietPeriod;
            this.folders = folders;
        }

        @Override
        public void run() {
            int remainingScans = this.remainingScans.get();//-1(AtomicInteger)
            while (remainingScans > 0 || remainingScans == -1) {
                try {
                    if (remainingScans > 0) {
                        this.remainingScans.decrementAndGet();
                    }
                    scan();
                }
                catch (InterruptedException ex) {
                    Thread.currentThread().interrupt();
                }
                remainingScans = this.remainingScans.get();
            }
        };

        private void scan() throws InterruptedException {
            Thread.sleep(this.pollInterval - this.quietPeriod);
            Map<File, FolderSnapshot> previous;
            Map<File, FolderSnapshot> current = this.folders;
            do {
                previous = current;
                current = getCurrentSnapshots();
                Thread.sleep(this.quietPeriod);
            }
            while (isDifferent(previous, current));
            if (isDifferent(this.folders, current)) {
                updateSnapshots(current.values());
            }
        }

        private boolean isDifferent(Map<File, FolderSnapshot> previous,
                Map<File, FolderSnapshot> current) {
            if (!previous.keySet().equals(current.keySet())) {
                return true;
            }
            for (Map.Entry<File, FolderSnapshot> entry : previous.entrySet()) {
                FolderSnapshot previousFolder = entry.getValue();
                FolderSnapshot currentFolder = current.get(entry.getKey());
                if (!previousFolder.equals(currentFolder, this.triggerFilter)) {
                    return true;
                }
            }
            return false;
        }

        private Map<File, FolderSnapshot> getCurrentSnapshots() {
            Map<File, FolderSnapshot> snapshots = new LinkedHashMap<File, FolderSnapshot>();
            for (File folder : this.folders.keySet()) {
                snapshots.put(folder, new FolderSnapshot(folder));
            }
            return snapshots;
        }

        private void updateSnapshots(Collection<FolderSnapshot> snapshots) {
            Map<File, FolderSnapshot> updated = new LinkedHashMap<File, FolderSnapshot>();
            Set<ChangedFiles> changeSet = new LinkedHashSet<ChangedFiles>();
            for (FolderSnapshot snapshot : snapshots) {
                FolderSnapshot previous = this.folders.get(snapshot.getFolder());
                updated.put(snapshot.getFolder(), snapshot);
                ChangedFiles changedFiles = previous.getChangedFiles(snapshot,
                        this.triggerFilter);
                if (!changedFiles.getFiles().isEmpty()) {
                    changeSet.add(changedFiles);
                }
            }
            if (!changeSet.isEmpty()) {
                fireListeners(Collections.unmodifiableSet(changeSet));
            }
            this.folders = updated;
        }

        private void fireListeners(Set<ChangedFiles> changeSet) {
            for (FileChangeListener listener : this.listeners) {
                listener.onChange(changeSet);
            }
        }

    }

可以看到,線程在scan中不斷的做文件的掃描判斷,看看當(dāng)前的文件快照和前一個文件的快照是否有變化(毫秒級),若有變化則會執(zhí)行updateSnapshots方法,并觸發(fā)listener.onChange(changeSet)方法,發(fā)布ClassPathChangedEvent事件,引發(fā)重啟。


File-Watcher
"File Watcher" #51 daemon prio=5 os_prio=0 tid=0x0000000017276000 nid=0x3c04 waiting on condition [0x000000001a66f000]
   java.lang.Thread.State: TIMED_WAITING (sleeping)
        at java.lang.Thread.sleep(Native Method)
        at org.springframework.boot.devtools.filewatch.FileSystemWatcher$Watcher.scan(FileSystemWatcher.java:250)
        at org.springframework.boot.devtools.filewatch.FileSystemWatcher$Watcher.run(FileSystemWatcher.java:240)
        at java.lang.Thread.run(Thread.java:748)

   Locked ownable synchronizers:
        - None

可以看到,后臺確實是啟動了一個線程不斷的在做文件快照的檢查工作。
這里,文件檢測并觸發(fā)的邏輯已經(jīng)介紹完畢,后續(xù)接著介紹服務(wù)重啟的詳細(xì)流程。

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

相關(guān)閱讀更多精彩內(nèi)容

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