您好,登錄后才能下訂單哦!
這篇文章主要介紹“如何實現Spring Boot基于GraalVM構建”,在日常操作中,相信很多人在如何實現Spring Boot基于GraalVM構建問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”如何實現Spring Boot基于GraalVM構建”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!
容器化、函數式、低代碼、云原生各種概念和技術層出不窮,無奈,與時俱進,跟進研究,發現 Quarkus 最近比較火爆,抽空研究了一下,這就引出了本文的豬腳: GraalVM ,口號是:Run Programs Faster Anywhere
GraalVM Native Image是由Oracle Labs開發的一種AOT編譯器,支持基于JVM的高級語言,如Java, Scala, Clojure, Kotlin。Native Image以Java bytecode作為輸入,將所有應用所需的class依賴項及runtime庫打包編譯生成一個單獨可執行文件。具有高效的startup及較小的運行時內存開銷的優勢。
與傳統的Java虛擬機不同,Native Image是封閉式的靜態分析和編譯,不支持class的動態加載,程序運行所需要的多有依賴項均在靜態分析階段完成。此外GraalVM Native Image運行在一個名為SubstrateVM的輕量級的虛擬機之上。雖說是輕量級虛擬機,SubstrateVM卻擁有運行Java程序所必需的所有組件,包括deoptimizer、gc及thread scheduling等。 目前GraalVM Native Image并沒有完全支持多有的Java動態特性,如不支持class動態加載。 感興趣的童鞋可以點擊去看看,這里就不過多介紹了。
本文不涉及 GraalVM 的安裝和部署,只實踐 SpringBoot 基于 GraalVM 的構建
SpringBoot 從 2.3 開始,已經支持 GraalVM 打包。
構建一個基本的 SpringBoot 項目
分別使用普通 jar 和 Native-image 方式打包,對比資源占用情況。
用你熟悉的工具搭建一個基本的 SpringBoot 項目
貓咪DTO:
@Data @Accessors(chain = true) public class CatDTO implements Serializable { private String id; private String name; private Integer age; }
實現基本增刪改查 API(模擬)
@RestController @Slf4j @RequestMapping("/cats") public class CatController { @PostMapping public CatDTO save(@RequestBody @Validated CatDTO param) { return param; } @DeleteMapping("/{id}") public ResponseEntity<String> delete(@PathVariable String id) { return ResponseEntity.ok("Success" + id); } @PutMapping public CatDTO update(@RequestBody @Validated CatDTO param) { return param; } @GetMapping public ResponseEntity<String> list(CatDTO param, Pageable page) { return ResponseEntity.ok("列表查看"); } @GetMapping("/{id}") public CatDTO getById(@PathVariable String id) { return new CatDTO(); } }
其他代碼省略,感興趣的童鞋請參考 : 示例代碼
打包
$ ./mvnw package
運行
$ cd target $ java -jar graalvm-demo-0.0.1-SNAPSHOT.jar
留意一下啟動時間,我本機的是:
。。。。。。。 Started GraalvmDemoApplication in 1.774 seconds (JVM running for 2.212)
可以看到,啟動用了將近 2 秒鐘。 如果引入數據庫、MQ等,肯定還會更多。
再看看內存使用情況:
命令: $ ps aux | grep graalvm-demo | awk '{print $1 "\t" $2 "\t" $3 "\t" $4 "\t" $5 "\t" $6/1024"MB" "\t" $11$12$13$14$15$16$17$18 }' 結果: 51460 0.0 2.9 10508892 473.863MB /usr/bin/java-jargraalvm-demo-0.0.1-SNAPSHOT.jar
473.863MB ,就這么簡單個功能的應用,將近 500MB 內存沒了。這個資源占用,不小! 相比之下,PHP、C#、甚至 Nodejs 實現同樣功能,哪個都沒 Java 吃的多~~妥妥的干飯專家....
GraalVM的安裝,請參考官方文檔,本文不做介紹。
安裝完畢后,記得安裝 native-image 本地映像打包插件。安裝命令:
gu install native-image
本例中具體環境如下:
// GraalVM 版本 $ java -version openjdk version "1.8.0_282" OpenJDK Runtime Environment (build 1.8.0_282-b07) OpenJDK 64-Bit Server VM GraalVM CE 20.3.1 (build 25.282-b07-jvmci-20.3-b09, mixed mode)
為了使用 GraalVM 打包,SpringBoot 項目需要進行一些調整
//@SpringBootApplication //這里proxyBeanMethods方法代理關閉 @SpringBootApplication(proxyBeanMethods = false) public class GraalvmDemoApplication { public static void main(String[] args) { SpringApplication.run(GraalvmDemoApplication.class, args); } }
SringBoot 提供了 GraalVM Native 打包的 Maven 插件,可通過如下方式引入:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.4.2</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.luter</groupId> <artifactId>graalvm-demo</artifactId> <version>0.0.1-SNAPSHOT</version> <name>graalvm-demo</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <!-- graalvm 打包 插件--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-indexer</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.experimental</groupId> <artifactId>spring-graalvm-native</artifactId> <version>0.8.3</version> </dependency> </dependencies> <!-- graalvm 插件不在中央庫,所以還需要指定 repository--> <repositories> <repository> <id>spring-milestones</id> <name>Spring Milestones</name> <url>https://repo.spring.io/milestone</url> </repository> </repositories> <pluginRepositories> <pluginRepository> <id>spring-milestones</id> <name>Spring Milestones</name> <url>https://repo.spring.io/milestone</url> </pluginRepository> </pluginRepositories> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <excludes> <exclude> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </exclude> </excludes> </configuration> </plugin> </plugins> </build> <profiles> <!-- 加一個 native 打包的 配置--> <profile> <id>native</id> <build> <plugins> <plugin> <groupId>org.graalvm.nativeimage</groupId> <artifactId>native-image-maven-plugin</artifactId> <version>20.3.1</version> <configuration> <mainClass>com.luter.graalvmdemo.GraalvmDemoApplication</mainClass> <buildArgs>-Dspring.native.remove-yaml-support=false -Dspring.spel.ignore=true </buildArgs> </configuration> <executions> <execution> <goals> <goal>native-image</goal> </goals> <phase>package</phase> </execution> </executions> </plugin> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </profile> </profiles> </project>
打包命令:
$ ./mvnw -P native package
會顯示如下信息:
[com.luter.graalvmdemo.graalvmdemoapplication:49751] classlist: 6,378.68 ms, 2.20 GB _____ _ _ __ __ _ / ___/ ____ _____ (_) ____ ____ _ / | / / ____ _ / /_ (_) _ __ ___ \__ \ / __ \ / ___/ / / / __ \ / __ `/ / |/ / / __ `/ / __/ / / | | / / / _ \ ___/ / / /_/ / / / / / / / / / / /_/ / / /| / / /_/ / / /_ / / | |/ / / __/ /____/ / .___/ /_/ /_/ /_/ /_/ \__, / /_/ |_/ \__,_/ \__/ /_/ |___/ \___/ /_/ /____/ Removing unused configurations Verification turned on Removing XML support Removing SpEL support Removing JMX support Use -Dspring.native.verbose=true on native-image call to see more detailed information from the feature [com.luter.graalvmdemo.graalvmdemoapplication:49751] (cap): 3,263.36 ms, 2.51 GB feature operating mode: reflection (spring init active? false) Found #15 types in static reflection list to register Skipping #12 types not on the classpath Attempting proxy registration of #12 proxies Skipped registration of #4 proxies - relevant types not on classpath [com.luter.graalvmdemo.graalvmdemoapplication:49751] setup: 12,937.89 ms, 2.93 GB 。。。。。。。。 [com.luter.graalvmdemo.graalvmdemoapplication:49751] (clinit): 3,141.89 ms, 5.59 GB [com.luter.graalvmdemo.graalvmdemoapplication:49751] (typeflow): 73,234.16 ms, 5.59 GB [com.luter.graalvmdemo.graalvmdemoapplication:49751] (objects): 92,334.47 ms, 5.59 GB [com.luter.graalvmdemo.graalvmdemoapplication:49751] (features): 18,891.77 ms, 5.59 GB [com.luter.graalvmdemo.graalvmdemoapplication:49751] analysis: 196,029.89 ms, 5.59 GB [com.luter.graalvmdemo.graalvmdemoapplication:49751] universe: 5,281.74 ms, 5.62 GB [com.luter.graalvmdemo.graalvmdemoapplication:49751] (parse): 17,570.40 ms, 5.28 GB [com.luter.graalvmdemo.graalvmdemoapplication:49751] (inline): 23,751.47 ms, 7.13 GB [com.luter.graalvmdemo.graalvmdemoapplication:49751] (compile): 73,916.12 ms, 7.74 GB [com.luter.graalvmdemo.graalvmdemoapplication:49751] compile: 123,244.44 ms, 7.74 GB [com.luter.graalvmdemo.graalvmdemoapplication:49751] image: 15,852.33 ms, 7.83 GB [com.luter.graalvmdemo.graalvmdemoapplication:49751] write: 3,908.93 ms, 7.83 GB [com.luter.graalvmdemo.graalvmdemoapplication:49751] [total]: 371,061.00 ms, 7.83 GB [INFO] [INFO] --- spring-boot-maven-plugin:2.4.2:repackage (repackage) @ graalvm-demo --- [INFO] Replacing main artifact with repackaged archive [INFO] ------------------------------------------------------------------------ [INFO] BUILD SUCCESS [INFO] ------------------------------------------------------------------------ [INFO] Total time: 06:21 min [INFO] Finished at: 2021-01-27T12:52:16+08:00 [INFO] ------------------------------------------------------------------------
這一步還是比較慢的,我本機用了將近 4 分鐘,請耐心等待.打包完畢后,target 目錄下會出現運行文件: com.luter.graalvmdemo.graalvmdemoapplication,這個文件 57.6MB ,普通 Fat Jar 方式打包文件:graalvm-demo-0.0.1-SNAPSHOT.jar 17.7MB,大了三倍多
運行 :
$ ./com.luter.graalvmdemo.graalvmdemoapplication . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.4.2) 2021-01-27 13:31:04.357 INFO 51785 --- [ main] c.l.graalvmdemo.GraalvmDemoApplication : Starting GraalvmDemoApplication v0.0.1-SNAPSHOT using Java 1.8.0_282 on localhost with PID 51785 (/opt/luter/develop/temp/graalvm-demo/target/com.luter.graalvmdemo.graalvmdemoapplication started by clt in /opt/luter/develop/temp/graalvm-demo/target) 2021-01-27 13:31:04.357 INFO 51785 --- [ main] c.l.graalvmdemo.GraalvmDemoApplication : No active profile set, falling back to default profiles: default 2021-01-27 13:31:04.387 INFO 51785 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 10000 (http) Jan 27, 2021 1:31:04 PM org.apache.coyote.AbstractProtocol init INFO: Initializing ProtocolHandler ["http-nio-10000"] Jan 27, 2021 1:31:04 PM org.apache.catalina.core.StandardService startInternal INFO: Starting service [Tomcat] Jan 27, 2021 1:31:04 PM org.apache.catalina.core.StandardEngine startInternal INFO: Starting Servlet engine: [Apache Tomcat/9.0.41] Jan 27, 2021 1:31:04 PM org.apache.catalina.core.ApplicationContext log INFO: Initializing Spring embedded WebApplicationContext 2021-01-27 13:31:04.390 INFO 51785 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 33 ms 2021-01-27 13:31:04.401 INFO 51785 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor' Jan 27, 2021 1:31:04 PM org.apache.coyote.AbstractProtocol start INFO: Starting ProtocolHandler ["http-nio-10000"] 2021-01-27 13:31:04.408 INFO 51785 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 10000 (http) with context path '' 2021-01-27 13:31:04.408 INFO 51785 --- [ main] c.l.graalvmdemo.GraalvmDemoApplication : Started GraalvmDemoApplication in 0.066 seconds (JVM running for 0.068)
這個啟動太順滑了,回車后,幾乎是秒開,用時0.066秒。傳統 Fatjar 方式啟動用時:1.774秒,20 多倍的提升。試想一下,一個動不動啟動半分鐘的大型項目上云,是不是很激動人心?
再看看內存占用情況:
//命令 $ ps aux | grep com.luter.graalvmdemo.graalvmdemoapplication | grep S+ | awk '{print $1 "\t" $2 "\t" $3 "\t" $4 "\t" $5 "\t" $6/1024"MB" "\t" $11 }' //結果 51785 0.0 0.3 4526816 53.8711MB ./com.luter.graalvmdemo.graalvmdemoapplication
內存占用:53.8711MB ,相比較傳統 FatJar 的 473.863MB ,差不多 10 倍。 從啟動速度到資源占用,都大幅度降低了,這對降低部署成本,還是很有幫助的。
到此,關于“如何實現Spring Boot基于GraalVM構建”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續學習更多相關知識,請繼續關注億速云網站,小編會繼續努力為大家帶來更多實用的文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。