作为JAVA开发人员,有时会经历更长的启动时间和相对较高的内存使用率,在本文中,我们将介绍一个简单的Spring Boot应用程序,然后使用GraalVM将其转换为本机映像( Native Image)。
GraalVM是一种高性能的多语言编译器,可帮助实现-
- 提高应用程序吞吐量并减少延迟
- 将应用程序编译为独立的小型本机二进制文件
- 无缝使用多种语言和库
对于AOT编译,它使用Native Image Builder或native-image技术将Java代码提前编译为独立的可执行文件。它处理应用程序的所有类及其依赖项,包括来自JDK的那些类。它静态分析这些数据,以确定在应用程序执行期间可以访问哪些类和方法。
安装GraalVM- https://github.com/shivamgarg7276/graal-spring-native/blob/main/README.md
不久前,Spring团队宣布了Spring Native Beta 项目,该项目可以使用GraalVM将Spring应用程序编译为Native Image。内存消耗有望大大降低,并且启动几乎是即时的。
- 添加org.springframework.experimental:spring-native-imageMaven依赖项:
<dependency>
<groupId> org.springframework.experimental </ groupId>
<artifactId> spring-native </ artifactId>
<version> 0.9.2 </ version>
</ dependency>
- 添加Spring AOT插件:
<plugin>
<groupId>org.springframework.experimental</groupId>
<artifactId>spring-aot-maven-plugin</artifactId>
<version>0.9.2</version>
<executions>
<execution>
<id>test-generate</id>
<goals>
<goal>test-generate</goal>
</goals>
</execution>
<execution>
<id>generate</id>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
</plugin>
- 添加native-image,在package阶段期间触发插件:
<profiles>
<profile>
<id>native-image</id>
<build>
<plugins>
<plugin>
<groupId>org.graalvm.nativeimage</groupId>
<artifactId>native-image-maven-plugin</artifactId>
<version>21.0.0.2</version>
<configuration>
<!-- The native image build needs to know the entry point to your application -->
<mainClass>com.example.graal.restserver.main.RestApplicationWithAOT</mainClass>
<buildArgs>
<buildArg>--enable-https</buildArg>
</buildArgs>
</configuration>
<executions>
<execution>
<goals>
<goal>native-image</goal>
</goals>
<phase>package</phase>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
到目前为止,我们讨论过的代码更改可以在这里找到-https: //github.com/shivamgarg7276/graal-spring-native/tree/main/spring-boot-with-aot
您只需使用此命令即可构建模块-mvn -Pnative-image clean package
这将target在模块文件夹下创建一个包含Spring Boot应用程序的本地可执行文件。
只需调用-target/com.example.graal.restserver.main.restapplicationwithaot
这将在port启动Spring Boot服务器8081。
您还可以使用GraalVM + Spring Native生成优化的容器映像,该映像可以轻松部署并包含最少的OS层。