Spring Native 入门实战
基础环境说明
GraalVM 是一种高性能的虚拟机,它可以显著的提高程序的性能和运行效率,非常适合微服务。
下载地址如下,和普通 JDK 安装一致:
- Linux (amd64) - link[1]
- Linux (aarch64) - link[2]
- MacOS (amd64) † - link[3]
- Windows (amd64) - link[4]
PS: 如果使用 MacOS Catalina 及更新版本,请在安装之前执行以下命令,不然会提示文件已损坏。
sudo xattr -r -d com.apple.quarantine path/to/graalvm/folder/
上手 Spring Native
- 基于https://start.spring.io[5] 创建项目
- 添加
native-image
构建 profile
<profiles>
<profile>
<id>native-image</id>
<build>
<plugins>
<plugin>
<groupId>org.graalvm.nativeimage</groupId>
<artifactId>native-image-maven-plugin</artifactId>
<version>21.0.0</version>
<configuration>
<!-- 这里要指定 Main 方法的入口 -->
<mainClass>com.example.demo.DemoApplication</mainClass>
</configuration>
<executions>
<execution>
<goals>
<goal>native-image</goal>
</goals>
<phase>package</phase>
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
</profiles>
- 指定原有的 spring-boot-maven-plugin 构建出 exec 程序
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<!--执行classifier为exec-->
<classifier>exec</classifier>
<image>
<builder>paketobuildpacks/builder:tiny</builder>
<env>
<BP_NATIVE_IMAGE>true</BP_NATIVE_IMAGE>
</env>
</image>
</configuration>
</plugin>
开始构建
- 执行 mvn 命令
mvn -Pnative-image package
- 构建成功, 耗时三分钟。
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 03:03 min
[INFO] Finished at: 2021-03-28T12:17:55+08:00
[INFO] Final Memory: 113M/310M
[INFO] ------------------------------------------------------------------------
ls -lh target/com.example.demo.demoapplication
-rwxr-xr-x 1 lengleng staff 57M Mar 28 12:17 target/com.example.demo.demoapplication
- 运行测试
target/com.example.demo.demoapplication
使用 upx 继续压缩
UPX - the Ultimate Packer for eXecutables 是一款开源的可执行文件压缩程序,可以压缩常见平台下的可执行程序包。
- 安装并压缩 native-image 生成的执行文件
brew install upx
upx com.example.demo.demoapplication
- 压缩为原来的 30% ,且能够正常运行。
Ultimate Packer for eXecutables
Copyright (C) 1996 - 2020
UPX 3.96 Markus Oberhumer, Laszlo Molnar & John Reiser Jan 23rd 2020
File size Ratio Format Name
-------------------- ------ ----------- -----------
60185112 -> 18501648 30.74% macho/amd64 com.example.demo.demoapplication
Packed 1 file.
ls -lh target/com.example.demo.demoapplication
-rwxr-xr-x 1 lengleng staff 18M Mar 28 12:17 target/com.example.demo.demoapplication
参考资料
[1]link: https://github.com/graalvm/graalvm-ce-builds/releases/download/vm-21.0.0.2/graalvm-ce-java11-linux-amd64-21.0.0.2.tar.gz
[2]link: https://github.com/graalvm/graalvm-ce-builds/releases/download/vm-21.0.0.2/graalvm-ce-java11-linux-aarch64-21.0.0.2.tar.gz
[3]link: https://github.com/graalvm/graalvm-ce-builds/releases/download/vm-21.0.0.2/graalvm-ce-java11-darwin-amd64-21.0.0.2.tar.gz
[4]link: https://github.com/graalvm/graalvm-ce-builds/releases/download/vm-21.0.0.2/graalvm-ce-java11-windows-amd64-21.0.0.2.zip
[5]https://start.spring.io: https://start.spring.io