代碼地址:https://github.com/showkawa/springBoot_2017/tree/master/spb-demojava
springboot優化主要有三類優化:1.包掃描優化 2.運行時JVM參數優化 3.web容器優化git
1.包掃描優化github
通常咱們會使用 @SpringBootApplication 註解來自動獲取應用的配置信息,但這樣也會給應用帶來一些反作用。使用這個註解後,會觸發自動配置( auto-configuration )和 組件掃描 ( component scanning ),這跟使用 @Configuration、@EnableAutoConfiguration 和 @ComponentScan 三個註解的做用是同樣的。這樣作給開發帶來方便的同時,也會有三方面的影響:web
一、會致使項目啓動時間變長。當啓動一個大的應用程序,或將作大量的集成測試啓動應用程序時,影響會特別明顯。spring
二、會加載一些不須要的多餘的實例(beans)。tomcat
三、會增長 CPU 消耗。springboot
針對以上三個狀況,咱們能夠移除 @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容器跟據實際的項目來。spring-boot
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>