什么是 GraalVM Native Image?
GraalVM 是一个高性能的运行时,其 Native Image 功能可以:
将 Java 字节码在编译时(Build Time)静态分析,生成独立的本地可执行文件(Native Executable)
对比
特性 | JVM 模式 | Native Image 模式 |
启动时间 | 5s - 30s | 10ms - 200ms |
内存占用 | 100MB - 500MB+ | 30MB - 80MB |
镜像大小 | 200MB - 500MB | 50MB - 100MB |
CPU 利用率 | 启动时高 | 启动后极低 |
适用场景 | 传统应用、长时服务 | Serverless、K8s、边缘计算 |
环境准备
1. 安装 GraalVM
# 使用 sdkman
sdk install java 21.0.4-graal
# 或使用 Docker
docker pull ghcr.io/graalvm/graalvm-ce:ol8-java17
2. 安装 Native Image 工具
gu install native-image
实战:构建第一个 Native Image Spring Boot 应用
步骤 1:创建 Spring Boot 项目(使用 Spring Boot 3+)
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.3.3</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 关键:Spring Native 支持 -->
<dependency>
<groupId>org.springframework.experimental</groupId>
<artifactId>spring-native</artifactId>
<version>0.12.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<!-- Native Image 插件 -->
<plugin>
<groupId>org.graalvm.buildtools</groupId>
<artifactId>native-maven-plugin</artifactId>
<version>0.9.28</version>
<executions>
<execution>
<id>build-native</id>
<goals>
<goal>build</goal>
</goals>
<phase>package</phase>
</execution>
</executions>
</plugin>
</plugins>
</build>
步骤 2:添加 @NativeHint
或配置文件
Spring Boot 3+ 已大幅简化 Native Image 配置。
你可以在 src/main/resources/META-INF/native-image
创建配置文件,或使用注解。
步骤 3:编写简单的 Web 应用
@SpringBootApplication
@RestController
public class NativeDemoApplication {
public static void main(String[] args) {
SpringApplication.run(NativeDemoApplication.class, args);
}
@GetMapping("/hello")
public String hello() {
return "Hello from Native Image! 🚀";
}
}
步骤 4:编译为 Native Image
# 使用 Maven
./mvnw -Pnative native:compile
# 或使用打包
./mvnw -Pnative package
# 生成 target/native-demo (可执行文件)
步骤 5:运行
# 直接运行
./target/native-demo
# 访问
curl http://localhost:8080/hello
✅ 你会惊讶于 0.1 秒内的启动速度!