SpringBoot集成GraalVm生成native image

配置环境

https://blog.csdn.net/q412086027/article/details/113878426
参考该篇配置好GraalVm环境后开始创建项目

创建项目

直接到spring官网生产一个最简单的SpringWeb项目创建项目

添加依赖

native依赖
	<!--添加此依赖,可以通过在编译时创建候选对象的静态列表来提高大型应用程序的启动性能 -->
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-context-indexer</artifactId>
	</dependency>
	
	<!--Graalvm-native 依赖 -->
	<dependency>
		<groupId>org.springframework.experimental</groupId>
		<artifactId>spring-graalvm-native</artifactId>
		<version>0.8.3</version>
	</dependency>
maven native iamge插件
	<plugin>
		<groupId>org.graalvm.nativeimage</groupId>
		<artifactId>native-image-maven-plugin</artifactId>
		<version>21.0.0.2</version>
		<configuration>
			<skip>false</skip>
			<imageName>${project.artifactId}</imageName>
			<buildArgs>
				--no-fallback
			</buildArgs>
		</configuration>
		<executions>
			<execution>
				<goals>
					<goal>native-image</goal>
				</goals>
				<phase>package</phase>
			</execution>
		</executions>
	</plugin>
	<plugin>
		<artifactId>maven-assembly-plugin</artifactId>
		<version>3.1.0</version>
		<configuration>
			<descriptorRefs>
				<descriptorRef>jar-with-dependencies</descriptorRef>
			</descriptorRefs>
			<archive>
				<manifest>
					<mainClass>com.example.demo.DemoApplication</mainClass>
				</manifest>
			</archive>
		</configuration>
		<executions>
			<execution>
				<id>make-assembly</id>
				<phase>package</phase>
				<goals>
					<goal>single</goal>
				</goals>
			</execution>
		</executions>
	</plugin>

打包运行

打包为native iamge
mvn package -Pnative

生成文件

nateive image运行结果

native-image
打包为原生应用后冷启动时间为0.15秒

jar包方式运行结果

在这里插入图片描述

直接运行jar包时间为3.3秒

总结

目前spring-graalvm-native尚处于实验阶段, 但是能预想到如果正式发布后对目前的springboot项目启动速度的提升之巨大.简直是天生为docker k8s等容器准备的. 目前随随便便一个小项目启动速度都要接近分钟级别了.如果能将启动速度提升到秒级对我们项目的好处不言而喻, 但是缺点也很明显 编译速度大大降低了, 该demo编译耗时6分钟. 如果只打包成jar只需5秒. 期待后续的优化

demo地址https://gitee.com/zyxnice/spring-boot-native

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐