代碼地址:https://github.com/showkawa/springBoot_2017/tree/master/spb-demo
springboot優化主要有三類優化:1.包掃描優化 2.運行時JVM參數優化 3.web容器優化
1.包掃描優化
一般我們會使用 @SpringBootApplication 注解來自動獲取應用的配置信息,但這樣也會給應用帶來一些副作用。使用這個注解后,會觸發自動配置( auto-configuration )和 組件掃描 ( component scanning ),這跟使用 @Configuration、@EnableAutoConfiguration 和 @ComponentScan 三個注解的作用是一樣的。這樣做給開發帶來方便的同時,也會有三方面的影響:
1、會導致項目啟動時間變長。當啟動一個大的應用程序,或將做大量的集成測試啟動應用程序時,影響會特別明顯。
2、會加載一些不需要的多余的實例(beans)。
3、會增加 CPU 消耗。
針對以上三個情況,我們可以移除 @SpringBootApplication 和 @ComponentScan 兩個注解來禁用組件自動掃描,然后在我們需要的 bean 上進行顯式配置:
//// 移除 @SpringBootApplication and @ComponentScan, 用 @EnableAutoConfiguration 來替代 //@SpringBootApplication @Configuration @EnableAutoConfiguration public class AppTest{ public static void main(String[] args) { SpringApplication.run(AppTest.class, args); } }
具體需要注入哪些bean到ioc容器跟據實際的項目來。
2.運行時JVM參數優化
JVM調優主要目的減少GC回收次數
測試JVM堆內存128M和1024M,垃圾回收次數(直接使用JDK里面的jconsole.exe查看)
java -server -Xms128m -Xmx128m -jar spb-brian-query-service-0.0.1-SNAPSHOT.jar
java -server -Xms1024m -Xmx1024m -jar spb-brian-query-service-0.0.1-SNAPSHOT.jar
或者使用以后命令在控制台打印GC日志
java -server -XX:+PrintGCDetails -Xms128m -Xmx128m -jar springboot_v2.jar
3.web容器優化
默認情況下,Spring Boot 使用 Tomcat 來作為內嵌的 Servlet 容器
可以將 Web 服務器切換到 Undertow 來提高應用性能。Undertow 是一個采用 Java 開發的靈活的高性能 Web 服務器,提供包括阻塞和基於 NIO 的非堵塞機制。Undertow 是紅帽公司的開源產品,是 Wildfly 默認的 Web 服務器。首先,從依賴信息里移除 Tomcat 配置:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </exclusion> </exclusions> </dependency>
然后添加 Undertow:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-undertow</artifactId> </dependency>