2023年10月19日
将虚拟线程应用程序编译为原生可执行文件
在另一篇博文中,我们看到了如何使用 Quarkus 实现一个 CRUD 应用程序来利用虚拟线程。这篇博文将展示如何将此类应用程序编译为原生可执行文件。
安装 GraalVM 21
要将利用虚拟线程的 Quarkus 应用程序编译为原生可执行文件,您需要一个支持 Java 21 的 GraalVM 版本。您可以从GitHub下载。
或者,您可以使用SDKMAN工具进行安装
> sdk install java 21-graalce
Downloading: java 21-graalce
In progress...
Repackaging Java 21-graalce...
Done repackaging...
Cleaning up residual files...
Installing: java 21-graalce
Done installing!
Do you want java 21-graalce to be set as default? (Y/n): n
安装完成后,请确保 GRAALVM_HOME
环境变量指向 GraalVM 安装目录
> export GRAALVM_HOME=$HOME/.sdkman/candidates/java/21-graalce
将应用程序编译为原生可执行文件
我们将重用在之前的博文中开发的 CRUD 应用程序。源代码位于virtual-threads-demos GitHub 仓库。请注意,虽然我们使用的是 CRUD 应用程序,但相同的方法也可用于任何利用虚拟线程的 Quarkus 应用程序,包括该仓库中的其他演示。
首先,请确保您使用的是 Java 21+ 并且 GRAALVM_HOME
环境变量指向 GraalVM 安装目录。
然后,在 pom.xml
文件中,添加 native
profile
<profiles>
<profile>
<id>native</id>
<activation>
<property>
<name>native</name>
</property>
</activation>
<properties>
<quarkus.package.type>native</quarkus.package.type>
</properties>
</profile>
</profiles>
当设置了 native
属性时,native
profile 会被激活。因此,使用以下命令编译应用程序:
> mvn clean package -Dnative
编译需要几分钟时间。完成后,您可以运行应用程序
-
1) 首先,启动数据库
> docker run --ulimit memlock=-1:-1 -d -it --rm=true --memory-swappiness=0 \
--name postgres-quarkus-demo -e POSTGRES_USER=restcrud \
-e POSTGRES_PASSWORD=restcrud -e POSTGRES_DB=rest-crud \
-p 5432:5432 postgres:15-bullseye
-
2) 然后,启动应用程序
> ./target/crud-example-1.0.0-SNAPSHOT-runner
您会看到
> ./target/crud-example-1.0.0-SNAPSHOT-runner
__ ____ __ _____ ___ __ ____ ______
--/ __ \/ / / / _ | / _ \/ //_/ / / / __/
-/ /_/ / /_/ / __ |/ , _/ ,< / /_/ /\ \
--\___\_\____/_/ |_/_/|_/_/|_|\____/___/
2023-10-17 09:44:34,925 INFO [io.quarkus] (main) crud-example 1.0.0-SNAPSHOT native (powered by Quarkus 3.4.1) started in 0.072s. Listening on: http://0.0.0.0:8080
2023-10-17 09:44:34,925 INFO [io.quarkus] (main) Profile prod activated.
2023-10-17 09:44:34,925 INFO [io.quarkus] (main) Installed features: [agroal, cdi, hibernate-orm, hibernate-orm-panache, hibernate-validator, jdbc-postgresql, narayana-jta, resteasy-reactive, resteasy-reactive-jackson, smallrye-context-propagation, vertx]
然后,在浏览器中打开应用程序(https://:8080),开始添加、更新和完成任务。您将在日志中看到这些请求的处理是在虚拟线程上执行的。
2023-10-17 10:15:09,992 INFO [org.acm.cru.TodoResource] (quarkus-virtual-thread-0) Called on VirtualThread[#78,quarkus-virtual-thread-0]/runnable@ForkJoinPool-5-worker-1
2023-10-17 10:15:13,136 INFO [org.acm.cru.TodoResource] (quarkus-virtual-thread-1) Called on VirtualThread[#85,quarkus-virtual-thread-1]/runnable@ForkJoinPool-5-worker-1