优势
- 使用Java虚拟机所需资源的一小部分,因此运行成本更低
- 启动时间大幅度下降,以毫秒为单位,可以大大减小内存的使用。
- 不需要进行预热即可提供最佳性能
- 可以打包到轻量级容器映像中以便快速有效地部署
- 减少了攻击面(这个和网络安全相关)
确定使用的jdk版本
jdk21
下载 GraalVM [二选一]
-
直接下载
oracle -
或者使用sdk 下载
# 安装sdk
https://sdkman.io/install
# 安装
sdk install java 21.0.3-graal
sdk use java 21.0.3-graal
创建项目 https://start.spring.io/
<?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>3.2.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>21</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.graalvm.buildtools</groupId>
<artifactId>native-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
@RestController
@SpringBootApplication
public class DemoApplication {
@RequestMapping("/")
String home() {
return "Hello World!";
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
打包编译
mvn -Pnative native:compile
运行
# 启动1 -> Started DemoApplication in 0.048 seconds (process running for 0.068)java
./target/demo
# 启动2 -> Started DemoApplication in 0.818 seconds (process running for 1.143)
java -jar ./target/demo-0.0.1-SNAPSHOT.jar
浏览器打开 http://127.0.0.1:8080
打包镜像
使用 alpine:latest 作为基础镜像,加入 上一步骤生成的可执行文件 demo
PS: 原生包比jar 还大
解决反射问题 todo
参考
https://docs.spring.io/spring-boot/docs/current/reference/html/native-image.html
文章评论