[最佳實踐] quarkus編譯二進位制可執行檔案
阿新 • • 發佈:2022-03-11
簡介
本節將前兩節的工程程式碼打包成window上可執行的二進位制檔案,拓展名為exe。這一節主要會有些坑,本節主要參考官方文件
環境
如果需要打包二進位制檔案,需要先安裝graalvm。推薦使用chocolatey安裝, 只需要一條命令choco install graalvm
graalvm 22.0
PS D:\Project\quarkus-demo001\target> java -version openjdk version "17.0.2" 2022-01-18 OpenJDK Runtime Environment GraalVM CE 22.0.0.2 (build 17.0.2+8-jvmci-22.0-b05) OpenJDK 64-Bit Server VM GraalVM CE 22.0.0.2 (build 17.0.2+8-jvmci-22.0-b05, mixed mode, sharing)
步驟
- 打包成jar包執行
- 打包成依賴graalvm的二進位制檔案
- 打包成不依賴grallvm的二進位制檔案
1. 打包普通jar包
官方教程:shell script ./mvnw package
It produces the `quarkus-run.jar` file in the `target/quarkus-app/` directory. Be aware that it’s not an _über-jar_ as the dependencies are copied into the `target/quarkus-app/lib/` directory. The application is now runnable using `java -jar target/quarkus-app/quarkus-run.jar`. If you want to build an _über-jar_, execute the following command: ```shell script ./mvnw package -Dquarkus.package.type=uber-jar ```
翻譯一下,其實就是執行命令./mvnw package
就可以得到jar包target/quarkus-app/quarkus-run.jar
,使用java -jar target/quarkus-app/quarkus-run.jar
來執行jar包。這不是我們的重頭戲,主要是打二進位制包。
2. 打包成依賴graalvm的二進位制檔案
此方法打包的二進位制檔案仍需要依賴graalvm,但程式碼已經做了靜態編譯處理,所以執行效率有大幅提升,比較適合容器化啟動。
- 安裝vs c++依賴
下載Visual Studio Installer
需要取消中文並選擇英文
打包命令(實際可能會報錯)
./mvnw package -Pnative
正確的打包命令
使用附加依賴的打包命令
cmd /c 'call "C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\VC\Auxiliary\Build\vcvars64.bat" && mvn package -Pnative'
- 執行上述命令或許會遇到一下錯誤
[ERROR] Failed to execute goal io.quarkus:quarkus-maven-plugin:1.1.1.Final:build (default) on project quarkus-echo: Failed to build a runnable JAR: Failed to augment application classes: Build failure: Build failed due to errors
[ERROR] [error]: Build step io.quarkus.deployment.pkg.steps.NativeImageBuildStep#build threw an exception: java.lang.RuntimeException: Cannot find the `native-image` in the GRAALVM_HOME, JAVA_HOME and System PATH. Install it using `gu install native-image`
其實日誌已經說出瞭解決方法,那就是執行命令安裝native-image,在window平臺上使用該命令安裝
gu.cmd install native-image
打包過程似乎非常耗資源,需要耐心等待
- 獲得打包檔案
廢了九牛二虎之力,終於得到了可執行檔案,該檔案在安裝了graalvm的機器上就可以直接執行了
3. 打包不需要依賴的二進位制檔案
第二種方法可以的話,這種方法其實很簡單了,只需要更換打包命令即可。
cmd /c 'call "C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\VC\Auxiliary\Build\vcvars64.bat" && mvn package -Pnative -Dquarkus.native.container-build=true'
同樣可以得到可執行檔案,這個檔案的原理大概是把需要的graalvm精簡api也一起打包進來了,跟jre的思路差不多吧,只不過實現的更為巧妙,更加輕量化。