Spring Boot启动速度优化

一、启动时间分析

IDEA 自带集成了 async-profile 工具,所以我们可以通过火焰图来更直观的看到一些启动过程中的问题,比如下图例子当中,通过火焰图来看大量的耗时在 Bean 加载和初始化当中。

git clone https://github.com/jvm-profiling-tools/async-profiler
./profiler.sh -d 60 -o collapsed -f /tmp/profile1.svg(保存文件路径)  程序pid
./profiler.sh -d 30 -f profile1.svg 17581

 

二、延迟初始化

Spring Boot 2.2版本后引入 spring.main.lazy-initialization属性,配置为 true 表示所有 Bean 都将延迟初始化。可以一定程度上提高启动速度,但是第一次访问可能较慢。

spring.main.lazy-initialization=true

三、Spring Context Indexer

Spring5 之后版本提供了spring-context-indexer功能,主要作用是解决在类扫描的时候避免类过多导致的扫描速度过慢的问题。

使用方法也很简单,导入依赖,然后在启动类打上@Indexed注解,这样在程序编译打包之后会生成META-INT/spring.components文件,当执行ComponentScan扫描类时,会读取索引文件,提高扫描速度。

<dependency>  
    <groupId>org.springframework</groupId>  
    <artifactId>spring-context-indexer</artifactId>          
    <optional>true</optional>
</dependency>

四、关闭JMX

Spring Boot 2.2.X 版本以下默认会开启 JMX,可以使用 jconsole 查看,对于我们无需这些监控的话可以手动关闭它。

spring.jmx.enabled=false

五、关闭分层编译

Java8 之后的版本,默认打开多层编译,使用命令java -XX:+PrintFlagsFinal -version | grep CompileThreshold查看。

Tier3 就是 C1、Tier4 就是 C2,表示一个方法解释编译 2000 次进行 C1编译,C1编译后执行 15000 次会进行 C2编译。

 我们可以通过命令使用 C1 编译器,这样就不存在 C2 的优化阶段,能够提高启动速度,同时配合 -Xverify:none/ -noverify 关闭字节码验证,但是,尽量不要在线上环境使用。

-XX:TieredStopAtLevel=1 -noverify

 

 

 

参考文献:这样优化Spring Boot,启动速度快到飞起! (baidu.com)

https://baijiahao.baidu.com/s?id=1738965029536598948&wfr=spider&for=pc

 

 

posted @ 2023-06-12 11:17  扰扰  阅读(677)  评论(0编辑  收藏  举报