spring-boot+graalvm实践
1、环境配置(Windows 10)
- 安装
VS
编译环境
下载visual studio2019安装包完成安装 https://visualstudio.microsoft.com/zh-hans/vs/older-downloads/
下载安装版本Visual Studio Professional 2019 (version 16.11)
以及msvc如下
配置如下环境变量
PATH=C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\VC\Tools\MSVC\14.16.27023\bin\HostX64\x64
INCLUDE=C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\VC\Tools\MSVC\14.16.27023\crt;C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\VC\Tools\MSVC\14.16.27023\include
如在编辑过程中出现以下错误,则需要将语言改为英文尝试
Native-image building on Windows currently only supports target architecture: AMD64
- 安装
graalvm jdk
在oracle官网https://www.oracle.com/downloads/graalvm-downloads.html?selected_tab=1
下载graalvm
软件包graalvm-ee-java17-windows-amd64-22.3.1.zip
解压并配置环境变量
GRAALVM_HOME=C:\jdk\graalvm-ee-java17-22.3.1
JAVA_HOME=C:\jdk\graalvm-ee-java17-22.3.1
PATH=%GRAALVM_HOME%\bin;
gu list 查看当前镜像,在首次编译时会下载native镜像
2、编写一个简单的spring-boot项目,使用graalvm构建成本地应用
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
...
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.0.3</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>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</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>
DemoApplication.java
@SpringBootApplication
@RestController
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@GetMapping("/demo")
public String demo(){
System.out.println("current time is "+System.currentTimeMillis());
return "demo-"+System.currentTimeMillis();
}
}
打开命令行x64 Native Tools Command Prompt for VS 2019
构建命令,需要特别注意不是普通的命令行cmd
mvn clean package -DskipTests -Pnative native:compile
编译成功后在target
目录中将会有一个demo.exe
,直接运行可秒启动应用。
centos环境中需要安装以下依赖
sudo dnf install gcc gcc-c++ -y
sudo dnf install zlib-devel