SpringBoot3新特性AOT介绍,在win11配置GraalVM环境并打包本地镜像.exe可执行文件
文章目录
一、AOT与JIT简介
AOT:Ahead-of-Time(提前编译):程序执行前,全部被编译成机器码
JIT:Just in Time(即时编译): 程序边编译,边运行;
以下我们将使用SpringBoot3,用GraalVM代替JDK实现AOP。
二、GraalVM安装与配置
- 进入GraalVM下载地址,下载下图框选的文件,并解压
- 配置环境变量
有个小建议,如果电脑上有多个Java的jdk,可以各自创建一个一个JAVA_HOMExxx,最后再设置一个JAVA_HOME引用想用的那个jdk,如下图我的配置
还需要配置Path
环境变量,如下图
配置完成后,打开CMD,运行gu
命令,如下正确打印提示即完成配置
GraalVM Component Updater v2.0.0
Usage:
gu info [-cClLnprstuvVJ] <param> print info about a specific component (from a file, a URL or a catalog)
gu available [-aClvVJ] <expr> list components available in a catalog
gu install [-0CcDfiLMnosruvyxY] <param> install a component package
gu list [-clvJ] <expression> list installed components, or components from a catalog
gu remove [-0DfMxv] <id> uninstall a component
gu upgrade [-cCnLsuxSd] [<ver>] [<cmp>] upgrade to a recent GraalVM or edition
gu rebuild-images rebuild native executables. Use -h for detailed usage
Common options:
-A, --auto-yes respond YES or ACCEPT to all questions.
-c, --catalog treat parameters as component IDs from a catalog of GraalVM components. This is the default.
-C, --custom-catalog <url> use user-supplied catalog at URL.
-e, --debug debugging. Prints stacktraces, ...
-E, --no-catalog-errors do not stop if at least one catalog is working.
-h, --help print help.
-L, --local-file, --file treat parameters as local filenames of packaged components.
-N, --non-interactive noninteractive mode. Fail when input is required.
--show-version print version information and continue.
-u, --url interpret parameters as URLs of packaged components.
-v, --verbose be verbose. Print versions and dependency information.
--version print version.
Additonal options:
--email <address> email address that confirms acceptance of GDS license.
can only be used with some commands.
--config <path> path to configuration file
--show-ee-token print current download token
Use
gu <command> -h
to get specific help.
Runtime options:
Jan 04, 2025 10:31:44 PM org.graalvm.shadowed.org.jline.utils.Log logr
WARNING: Unable to create a system terminal, creating a dumb terminal (enable debug logging for more information)
--native Run using the native launcher with limited access to Java libraries
(default).
--jvm Run on the Java Virtual Machine with access to Java libraries.
--vm.[option] Pass options to the host VM. To see available options, use '--help:vm'.
--log.file=<String> Redirect guest languages logging into a given file.
--log.[logger].level=<String> Set language log level to OFF, SEVERE, WARNING, INFO, CONFIG, FINE,
FINER, FINEST or ALL.
--help Print this help message.
--help:vm Print options for the host VM.
三、本地镜像打包工具——native-image安装
1. 自动在线安装
CMD运行命令:
gu install native-image
如下则安装完成:
Downloading: Component catalog from www.graalvm.org
Processing Component: Native Image
Downloading: Component native-image: Native Image from github.com
Installing new component: Native Image (org.graalvm.native-image, version 22.3.0)
由于程序会去GitHub下载,因此有可能会网络原因失败,可以多试几次
2. 手动安装
访问native-image下载地址,找到下图文件native-image-installable-svm-java17-windows-amd64-22.3.0.jar
,点击下载
CMD执行命令,完成安装
gu install [安装位置/native-image-installable-svm-java17-windows-amd64-22.3.0.jar]
安装完成后,运行命令,查看安装结果
gu list
ComponentId Version Component name Stability Origin
---------------------------------------------------------------------------------------------------------------------------------
graalvm 22.3.0 GraalVM Core Supported
native-image 22.3.0 Native Image Early adopter github.com
顺利打印,以上就安装完成了!
四、安装Visual Studio Community2022
进入官网下载,下载完成后打开,选择“使用C++的桌面开发”,右边安装详细信息仅需勾选MSVC和Win11 JDK,如下图
在语言包选项中,勾选英语,如果选择中文,可能会出现乱码报错的问题。点击安装,等待片刻完成。
以上完成配置安装GraalVM、native-image和Visual Studio之后,就完成了环境的搭建,接下来以一个实际打包案例来演示使用。
五、打包本地镜像案例
1. 创建SpringBoot项目
选择Graalvm的JDK17
这里我踩坑了,设置项目地址的时候,不要带有中文字符,不然会报错
勾选以下依赖:
GraalVM Native Support
Spring Web
2. 简单项目初始化
项目结构如下
创建HelloController.java
文件,编写一个接口。
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "Hello World!";
}
}
运行主程序之后,可实现网页访问http://localhost:8080/hello
后,屏幕打印:Hello World!
3. 方式一:通过jar包方式打包本地镜像
利用maven工具打包项目jar包
此时在CMD命令行中执行 java -jar demo-0.0.1-SNAPSHOT.jar
,也可实现程序功能。
打开Native工具,以管理员身份运行
cd /d [目录地址]
进入到对应目录。
- 错误记录:
在命令行中执行以下命令:
native-image -cp demo-0.0.1-SNAPSHOT.jar com.mystudy.demo.DemoApplication -o demo
出现报错:
========================================================================================================================
GraalVM Native Image: Generating 'demo' (executable)...
========================================================================================================================
[1/7] Initializing... (0.0s @ 0.14GB)
Error: Main entry point class 'com.mystudy.demo.DemoApplication' neither found on the classpath nor on the modulepath.
classpath: 'D:\demo\target\demo-0.0.1-SNAPSHOT.jar'
modulepath: 'D:\graalvm-ce-java17-22.3.0\lib\svm\library-support.jar'
Error: Use -H:+ReportExceptionStackTraces to print stacktrace of underlying exception
Error: Image build request failed with exit status 1
说是找不到启动主类,其实是主类设置错误,后来我到jar包里面看设置,修改后执行成功。
- 解决方法
用解压工具打开demo-0.0.1-SNAPSHOT.jar
文件,打开META-INF
文件夹中的MANIFEST.MF
文件,可以看到其中定义了Main-Class是org.springframework.boot.loader.launch.JarLauncher
,而Start-Class才是我写的那个,因此要把命令中的主类修改。
- 正确方法:
执行以下命令:
native-image -cp demo-0.0.1-SNAPSHOT.jar org.springframework.boot.loader.launch.JarLauncher -o demo
打包成功后,文件夹中出现demo.exe
,双击运行,程序快速启动
此时访问http://localhost:8080/hello
,成功出现和本地运行一样的效果。
4. 方式二(推荐):通过maven调用native-image打包
先用maven
命令clean
刚才生成的target
目录。接着仍然是先打开Native工具,进入到项目根目录即可,例如我的:
CD D:\demo
执行以下命令
mvn -Pnative native:compile
在等待了3分多钟后,直接打包完成了,打印输出:
------------------------------------------------------------------------------------------------------------------------
Top 10 packages in code area: Top 10 object types in image heap:
1.64MB sun.security.ssl 7.25MB byte[] for code metadata
1.05MB java.util 3.88MB byte[] for embedded resources
839.02KB java.lang.invoke 3.63MB java.lang.Class
725.92KB com.sun.crypto.provider 3.40MB java.lang.String
542.65KB org.apache.catalina.core 2.85MB byte[] for general heap data
507.08KB org.apache.tomcat.util.net 2.80MB byte[] for java.lang.String
494.38KB org.apache.coyote.http2 1.28MB com.oracle.svm.core.hub.DynamicHubCompanion
473.87KB java.lang 816.94KB byte[] for reflection metadata
467.46KB java.util.concurrent 659.81KB java.lang.String[]
464.97KB sun.security.x509 636.33KB java.util.HashMap$Node
25.84MB for 629 more packages 5.71MB for 3065 more object types
------------------------------------------------------------------------------------------------------------------------
8.5s (6.6% of total time) in 38 GCs | Peak RSS: 5.72GB | CPU load: 4.72
------------------------------------------------------------------------------------------------------------------------
Produced artifacts:
D:\demo\target\demo.build_artifacts.txt (txt)
D:\demo\target\demo.exe (executable)
========================================================================================================================
Finished generating 'demo' in 2m 7s.
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 03:26 min
[INFO] Finished at: 2025-01-06T13:39:35+08:00
[INFO] ------------------------------------------------------------------------
同样是在target
目录下,双击执行demo.exe
,同样可访问并显示helloworld
,则打包成功!这也是官方文档推荐的Maven方式。