Quarkus and Gradle

使用 Gradle 创建一个新项目、添加或移除扩展、启动开发模式、调试您的应用程序并构建您的应用程序到 jar 文件、本机可执行文件或容器友好型可执行文件中。使用 Gradle 项目元数据导入您的项目到您喜爱的 IDE 中。

Use Gradle to create a new project, add or remove extensions, launch development mode, debug your application, and build your application into a jar, native executable, or container-friendly executable. Import your project into your favorite IDE using Gradle project metadata.

Creating a new project

若要构建 Gradle 项目,您可以使用 Quarkus CLI 或 Quarkus Maven 插件:

To scaffold a Gradle project you can either use the Quarkus CLI or the Quarkus Maven plugin:

CLI
quarkus create app my-groupId:my-artifactId \
    --extensions=rest,rest-jackson \
    --gradle

For more information about how to install the Quarkus CLI and use it, please refer to the Quarkus CLI guide.

Maven
mvn {quarkus-platform-groupid}:quarkus-maven-plugin:{quarkus-version}:create \
    -DprojectGroupId=my-groupId \
    -DprojectArtifactId=my-artifactId \
    -Dextensions="rest,rest-jackson" \
    -DbuildTool=gradle

如果您刚刚启动 mvn {quarkus-platform-groupid}:quarkus-maven-plugin:{quarkus-version}:create,Maven 插件会询问用户输入。通过向 Maven 命令传递 -B,可以禁用此互动模式(并使用默认值)。

If you just launch mvn {quarkus-platform-groupid}:quarkus-maven-plugin:{quarkus-version}:create the Maven plugin asks for user inputs. You can disable this interactive mode (and use default values) by passing -B to the Maven command.

如果您偏好使用 Kotlin DSL,使用 gradle-kotlin-dsl 而不是 gradle

If you prefer using the Kotlin DSL, use gradle-kotlin-dsl instead of gradle.

Quarkus 项目脚手架在您的项目中自动安装 Gradle 包装器 (./gradlew)。

Quarkus project scaffolding automatically installs the Gradle wrapper (./gradlew) in your project.

如果您更偏好使用独立的 Gradle 安装,请使用 Gradle {gradle-version}。

If you prefer to use a standalone Gradle installation, please use Gradle {gradle-version}.

此项目是在以传递的 artifactId 命名的目录中生成的。

The project is generated in a directory named after the passed artifactId.

这一对适用于本地和 JVM 模式的 Dockerfile 也在 src/main/docker 中生成。这些 Dockerfile 中写有构建镜像和运行容器的说明。

A pair of Dockerfiles for native and JVM modes are also generated in src/main/docker. Instructions to build the image and run the container are written in those Dockerfiles.

Custom test configuration profile in JVM mode

默认情况下,使用 test 配置配置文件运行 JVM 模式下的 Quarkus 测试。如果你不熟悉 Quarkus 配置配置文件,所有你需要了解的内容都在 Configuration Profiles Documentation 中进行了说明。

By default, Quarkus tests in JVM mode are run using the test configuration profile. If you are not familiar with Quarkus configuration profiles, everything you need to know is explained in the Configuration Profiles Documentation.

但是,使用下方所示的 Gradle 构建配置,为您的测试使用自定义配置配置文件是可行的。这可能很有用,例如,如果您需要使用某个不是您的默认测试数据库的特定数据库运行一些测试时。

It is however possible to use a custom configuration profile for your tests with the Gradle build configuration shown below. This can be useful if you need for example to run some tests using a specific database which is not your default testing database.

Groovy DSL
test {
    systemProperty "quarkus.test.profile", "foo" 1
}
1 The foo configuration profile will be used to run the tests.
Kotlin DSL
tasks.test {
    systemProperty("quarkus.test.profile", "foo") 1
}
1 The foo configuration profile will be used to run the tests.

现在还无法在原生模式下使用测试自定义配置文件。始终使用 prod 配置文件运行原生测试。

It is not possible to use a custom test configuration profile in native mode for now. Native tests are always run using the prod profile.

Dealing with extensions

在 Quarkus 项目内部,你可以使用以下命令获取可用扩展的列表:

From inside a Quarkus project, you can obtain a list of the available extensions with:

CLI
quarkus extension
Gradle
./gradlew listExtensions

您可以使用以下方式启用扩展:

You can enable an extension using:

Unresolved directive in gradle-tooling.adoc - include::{includes}/devtools/extension-add.adoc[]

扩展使用逗号分隔的列表传递。

Extensions are passed using a comma-separated list.

扩展名是该扩展的 GAV 名称:例如 io.quarkus:quarkus-agroal 。但您可以传递一个部分名称,Quarkus 将尽力找到合适的扩展。例如,agroalAgroal`或 `agro`将扩展为 `io.quarkus:quarkus-agroal 。如果没有找到扩展或有多个扩展匹配,您将在命令结果中看到一个红色的对号 ❌。

The extension name is the GAV name of the extension: e.g. io.quarkus:quarkus-agroal. But you can pass a partial name and Quarkus will do its best to find the right extension. For example, agroal, Agroal or agro will expand to io.quarkus:quarkus-agroal. If no extension is found or if more than one extensions match, you will see a red check mark ❌ in the command result.

$ ./gradlew addExtension --extensions="jdbc,agroal,non-exist-ent"
[...]
❌ Multiple extensions matching 'jdbc'
     * io.quarkus:quarkus-jdbc-h2
     * io.quarkus:quarkus-jdbc-mariadb
     * io.quarkus:quarkus-jdbc-postgresql
     Be more specific e.g using the exact name or the full gav.
✅ Adding extension io.quarkus:quarkus-agroal
❌ Cannot find a dependency matching 'non-exist-ent', maybe a typo?
[...]

您可以安装所有与某一 globbing 模式匹配的扩展:

You can install all extensions which match a globbing pattern:

Unresolved directive in gradle-tooling.adoc - include::{includes}/devtools/extension-add.adoc[]

Development mode

Quarkus 带有内置的开发模式。您可以使用以下方法启动它:

Quarkus comes with a built-in development mode. You can start it with:

Unresolved directive in gradle-tooling.adoc - include::{includes}/devtools/dev.adoc[]

请注意,如果您以这种方式运行它,持续测试体验将不会那么好,因为 gradle 作为一个守护进程运行,而 Quarkus 无法绘制“美观”的测试输出,因此退回到仅仅记录输出。

Note that if you run it this way the continuous testing experience will not be as nice, as gradle runs as a daemon Quarkus can’t draw the 'pretty' test output so falls back to just logging the output.

然后,你可以更新应用程序源、资源和配置。这些更改将自动反映在正在运行的应用程序中。这非常适合进行跨 UI 和数据库的开发,因为你可以立即看到反映的更改。

You can then update the application sources, resources and configurations. The changes are automatically reflected in your running application. This is great to do development spanning UI and database as you see changes reflected immediately.

quarkusDev 启用热部署以及后台编译,这意味着当您修改 Java 文件或资源文件并刷新您的浏览器时,这些更改将自动生效。这对于资源文件(如配置属性文件)也很有效。刷新浏览器的行为将触发扫描工作区,如果检测到任何更改,Java 文件将被编译,应用程序将重新部署,然后您的请求将由重新部署的应用程序提供服务。如果编译或部署存在任何问题,一个错误页面会让您知道。

quarkusDev enables hot deployment with background compilation, which means that when you modify your Java files or your resource files and refresh your browser these changes will automatically take effect. This works too for resource files like the configuration property file. The act of refreshing the browser triggers a scan of the workspace, and if any changes are detected the Java files are compiled, and the application is redeployed, then your request is serviced by the redeployed application. If there are any issues with compilation or deployment an error page will let you know.

CTRL+C 停止应用程序。

Hit CTRL+C to stop the application.

您可以更改开发环境运行的工作目录:

You can change the working directory the development environment runs on:

Groovy DSL
quarkusDev {
    workingDirectory = rootProject.layout.projectDirectory.asFile
}
Kotlin DSL
tasks.quarkusDev {
    workingDirectory = rootProject.layout.projectDirectory.asFile
}

默认情况下,quarkusDev 任务使用 compileJava 编译器选项。这些选项可以通过在任务中设置 compilerArgs 属性来覆盖。

By default, the quarkusDev task uses compileJava compiler options. These can be overridden by setting the compilerArgs property in the task.

默认情况下,quarkusDev 将调试主机设置为 localhost (出于安全原因)。如果您需要更改此设置,例如,为启用在所有主机上进行调试,您可以像这样使用 -DdebugHost 选项:

By default, quarkusDev sets the debug host to localhost (for security reasons). If you need to change this, for example to enable debugging on all hosts, you can use the -DdebugHost option like so:

include::{includes}/devtools/dev-parameters.adoc[]:!dev-additional-parameters:

Unresolved directive in gradle-tooling.adoc - include::{includes}/devtools/dev-parameters.adoc[] :!dev-additional-parameters:

您还可以向开发环境中添加环境变量:

You also can add environment variables to the development environment:

Groovy DSL
quarkusDev {
    environmentVariables = [FOO_VALUE: 'abc', BAR_VALUE: 'def']
}
Kotlin DSL
tasks.quarkusDev {
    environmentVariables.set(mapOf("FOO_VALUE" to "abc", "BAR_VALUE" to "def"))
}

该插件还公开了一个 quarkusDev 配置。在该配置中声明一个依赖项的使用,将限制其使用仅限于开发模式。 quarkusDev 配置可以使用如下方式:

The plugin also exposes a quarkusDev configuration. Using this configuration to declare a dependency will restrict the usage of that dependency to development mode. The quarkusDev configuration can be used as following:

Groovy DSL
dependencies {
    quarkusDev 'io.quarkus:quarkus-jdbc-h2'
}
Kotlin DSL
dependencies {
    quarkusDev("io.quarkus:quarkus-jdbc-h2")
}

Remote Development Mode

可以使用远程开发模式,以便在容器环境(如 OpenShift)中运行 Quarkus,并使对本地文件进行的更改立即可见。

It is possible to use development mode remotely, so that you can run Quarkus in a container environment (such as OpenShift) and have changes made to your local files become immediately visible.

这使你能够在实际运行应用程序的相同环境中进行开发,并且有权访问相同服务。

This allows you to develop in the same environment you will actually run your app in, and with access to the same services.

不要在生产中使用此项功能。此功能仅应用于开发环境。不要在开发模式中运行生产应用程序。

Do not use this in production. This should only be used in a development environment. You should not run production applications in dev mode.

为此,你必须使用 mutable-jar 格式构建一个可变应用程序。在 application.properties 中设置以下属性:

To do this you must build a mutable application, using the mutable-jar format. Set the following properties in application.properties:

quarkus.package.jar.type=mutable-jar 1
quarkus.live-reload.password=changeit 2
quarkus.live-reload.url=http://my.cluster.host.com:8080 3
1 This tells Quarkus to use the mutable-jar format. Mutable applications also include the deployment time parts of Quarkus, so they take up a bit more disk space. If run normally they start just as fast and use the same memory as an immutable application, however they can also be started in dev mode.
2 The password that is used to secure communication between the remote side and the local side.
3 The URL that your app is going to be running in dev mode at. This is only needed on the local side, so you may want to leave it out of the properties file and specify it as a system property on the command line.

然后,以构建正常 Quarkus jar 的相同方式构建 mutable-jar,即通过发布:

The mutable-jar is then built in the same way that a regular Quarkus jar is built, i.e. by issuing:

Unresolved directive in gradle-tooling.adoc - include::{includes}/devtools/build.adoc[]

在你启动远程主机上的 Quarkus 之前,设置环境变量 QUARKUS_LAUNCH_DEVMODE=true。如果你在裸机上,你可以通过 export QUARKUS_LAUNCH_DEVMODE=true 命令进行设置,然后使用正确的 java -jar …​ 命令运行应用程序来运行应用程序。

Before you start Quarkus on the remote host set the environment variable QUARKUS_LAUNCH_DEVMODE=true. If you are on bare metal you can set it via the export QUARKUS_LAUNCH_DEVMODE=true command and then run the application with the proper java -jar …​ command to run the application.

如果你计划通过 Docker 运行应用程序,那么你需要向 docker run 命令中添加 -e QUARKUS_LAUNCH_DEVMODE=true。当应用程序启动时,你现在应该在日志中看到以下行:Profile dev activated. Live Coding activated。你还需要通过在 Dockerfile 中向 COPY 命令后面添加 RUN chmod o+rw -R /deployments 来向应用程序授予更新部署资源的权限。出于安全原因,不应将此选项添加到生产 Dockerfile 中。

If you plan on running the application via Docker, then you’ll need to add -e QUARKUS_LAUNCH_DEVMODE=true to the docker run command. When the application starts you should now see the following line in the logs: Profile dev activated. Live Coding activated. You will also need to give the application the rights to update the deployment resources by adding RUN chmod o+rw -R /deployments after the COPY commands into your Dockerfile. For security reasons, this option should not be added to the production Dockerfile.

远程端无需包含 Maven 或任何其他开发工具。使用新 Quarkus 应用程序生成的法规 fast-jar Dockerfile 是你唯一需要的。如果你正在使用裸机启动 Quarkus runner jar,请不要尝试运行正常开发模式。

The remote side does not need to include Maven or any other development tools. The normal fast-jar Dockerfile that is generated with a new Quarkus application is all you need. If you are using bare metal launch the Quarkus runner jar, do not attempt to run normal dev mode.

现在你需要使用 remote-dev 命令将本地代理连接到远程主机:

Now you need to connect your local agent to the remote host, using the remote-dev command:

./gradlew quarkusRemoteDev -Dquarkus.live-reload.url=http://my-remote-host:8080

现在,每次刷新浏览器时,你应该立即看到自己在远程应用程序中对本地做出的任何更改。

Now every time you refresh the browser you should see any changes you have made locally immediately visible in the remote app.

所有配置选项如下所示:

All the config options are shown below:

Unresolved directive in gradle-tooling.adoc - include::{generated-dir}/config/quarkus-core_quarkus.live-reload.adoc[]

Debugging

在开发模式下,Quarkus 默认以启用调试模式启动,侦听端口 5005,且不会挂起 JVM。

In development mode, Quarkus starts by default with debug mode enabled, listening to port 5005 without suspending the JVM.

可以通过向 debug 系统属性赋予以下值之一来改变此行为:

This behavior can be changed by giving the debug system property one of the following values:

  • false - the JVM will start with debug mode disabled

  • true - The JVM is started in debug mode and will be listening on port 5005

  • client - the JVM will start in client mode and attempt to connect to localhost:5005

  • {port} - The JVM is started in debug mode and will be listening on {port}

一个附加的系统属性 suspend 可用来在调试模式下启动时挂起 JVM。suspend 支持以下值:

An additional system property suspend can be used to suspend the JVM, when launched in debug mode. suspend supports the following values:

  • y or true - The debug mode JVM launch is suspended

  • n or false - The debug mode JVM is started without suspending

你还可以使用以下命令用一个挂起的 JVM 在调试模式下运行 Quarkus 应用程序:

You can also run a Quarkus application in debug mode with a suspended JVM using:

include::{includes}/devtools/dev-parameters.adoc[]:!dev-additional-parameters:

Unresolved directive in gradle-tooling.adoc - include::{includes}/devtools/dev-parameters.adoc[] :!dev-additional-parameters:

然后,将你的调试器附加到 localhost:5005

Then, attach your debugger to localhost:5005.

Import in your IDE

拥有一个 project generated 后,你可以将其导入你最喜欢的 IDE。唯一要求就是导入 Gradle 项目的能力。

Once you have a project-creation, you can import it in your favorite IDE. The only requirement is the ability to import a Gradle project.

Eclipse

在 Eclipse 中,单击: `File → Import`在向导中,选择: `Gradle → Existing Gradle Project`在下一个屏幕中,选择项目的根位置。下一个屏幕列出找到的模块;选择生成项目,然后单击 `Finish`这样就完成了!

In Eclipse, click on: File → Import. In the wizard, select: Gradle → Existing Gradle Project. On the next screen, select the root location of the project. The next screen list the found modules; select the generated project and click on Finish. Done!

在单独的终端中,运行:

In a separated terminal, run:

Unresolved directive in gradle-tooling.adoc - include::{includes}/devtools/dev.adoc[]

并尽享高产出环境。

and enjoy a highly productive environment.

IntelliJ IDEA

在 IntelliJ IDEA 中:

In IntelliJ IDEA:

  1. From inside IntelliJ IDEA select File → New → Project From Existing Sources…​ or, if you are on the welcome dialog, select Import project.

  2. Select the project root

  3. Select Import project from external model and Gradle

  4. Next a few times (review the different options if needed)

  5. On the last screen click on Finish

在单独的终端中或在嵌入式终端中,运行:

In a separated terminal or in the embedded terminal, run:

Unresolved directive in gradle-tooling.adoc - include::{includes}/devtools/dev.adoc[]

享受!

Enjoy!

Apache NetBeans

在 NetBeans 中:

In NetBeans:

  1. Select File → Open Project

  2. Select the project root

  3. Click on Open Project

在单独的终端或嵌入式终端中,转到项目根目录并运行:

In a separated terminal or the embedded terminal, go to the project root and run:

Unresolved directive in gradle-tooling.adoc - include::{includes}/devtools/dev.adoc[]

享受!

Enjoy!

Visual Studio Code

在 VS Code 中打开项目目录。如果你已经安装了 Java Extension Pack(分组一系列 Java 扩展程序),则会将项目加载为 Gradle 项目。

Open the project directory in VS Code. If you have installed the Java Extension Pack (grouping a set of Java extensions), the project is loaded as a Gradle project.

Downloading dependencies for offline development and testing

Quarkus 扩展程序依赖关系分为最终出现在应用程序运行时类路径中的运行时扩展程序依赖关系和仅在应用程序构建时由 Quarkus 解析以创建构建类路径的部署(或构建时)扩展程序依赖关系。应用程序开发人员应该只依赖 Quarkus 扩展程序的运行时构件。

Quarkus extension dependencies are divided into the runtime extension dependencies that end up on the application runtime classpath and the deployment (or build time) extension dependencies that are resolved by Quarkus only at application build time to create the build classpath. Application developers are expected to express dependencies only on the runtime artifacts of Quarkus extensions.

为了实现离线构建和测试 Quarkus 应用程序的用例,该插件包含可以像这样从命令行调用的 quarkusGoOffline 任务:

To enable the use-case of building and testing a Quarkus application offline, the plugin includes the quarkusGoOffline task that could be called from the command line like this:

./gradlew quarkusGoOffline

该任务会将应用程序的所有运行时、构建时、测试和开发模式依赖关系解析到 Gradle 缓存。执行后,你将能够放心地使用 --offline 标志来运行 quarkus 任务。

This task will resolve all the runtime, build time, test and dev mode dependencies of the application to the Gradle cache. Once executed, you will be able to safely run quarkus task with --offline flag.

Building a native executable

本机可执行文件使 Quarkus 应用程序非常适合容器和无服务器工作负载。

Native executables make Quarkus applications ideal for containers and serverless workloads.

确保已经配置 GRAALVM_HOME,并且指向 GraalVM {graalvm-version} 的最新版本。

Make sure to have GRAALVM_HOME configured and pointing to the latest release of GraalVM {graalvm-version}.

使用以下命令创建本机可执行文件:

Create a native executable using:

Unresolved directive in gradle-tooling.adoc - include::{includes}/devtools/build-native.adoc[]

本机可执行文件将出现在 build/ 中。

A native executable will be present in build/.

本机相关属性可以添加到 application.properties 文件、作为命令行参数或添加到 quarkusBuild 任务中。可以按照以下步骤配置 quarkusBuild 任务:

Native related properties can either be added in application.properties file, as command line arguments or in the quarkusBuild task. Configuring the quarkusBuild task can be done as following:

Groovy DSL
quarkusBuild {
    nativeArgs {
        containerBuild = true 1
        builderImage = "quay.io/quarkus/ubi-quarkus-mandrel-builder-image:{mandrel-flavor}" 2
    }
}
1 Set quarkus.native.container-build property to true
2 Set quarkus.native.builder-image property to quay.io/quarkus/ubi-quarkus-mandrel-builder-image:{mandrel-flavor}
Kotlin DSL
tasks.quarkusBuild {
    nativeArgs {
        "container-build" to true 1
        "builder-image" to "quay.io/quarkus/ubi-quarkus-mandrel-builder-image:{mandrel-flavor}" 2
    }
}
1 Set quarkus.native.container-build property to true
2 Set quarkus.native.builder-image property to quay.io/quarkus/ubi-quarkus-mandrel-builder-image:{mandrel-flavor}

当使用 Gradle Groovy DSL 时,属性键必须遵循小驼峰式命名法。例如:container-build 无效,应该替换为 containerBuild。此限制不适用于 Gradle Kotlin DSL。

When using the Gradle Groovy DSL, property keys must follow lower camel case notation. e.g. container-build is not valid, and should be replaced by containerBuild. This limitation does not apply to the Gradle Kotlin DSL.

Build a container friendly executable

本机可执行文件将特定于您的操作系统。要创建一个将在容器中运行的可执行文件,请使用以下内容:

The native executable will be specific to your operating system. To create an executable that will run in a container, use the following:

Unresolved directive in gradle-tooling.adoc - include::{includes}/devtools/build-native-container.adoc[]

生成的执行文件将是 64 位 Linux 执行文件,因此,根据你的操作系统,它可能不再可运行。但是,这不是问题,因为我们准备将它复制到 Docker 容器中。请注意,在这种情况下,构建本身也运行在 Docker 容器中,因此你不必在本地安装 GraalVM。

The produced executable will be a 64-bit Linux executable, so depending on your operating system it may no longer be runnable. However, it’s not an issue as we are going to copy it to a Docker container. Note that in this case the build itself runs in a Docker container too, so you don’t need to have GraalVM installed locally.

默认情况下,将使用 quay.io/quarkus/ubi-quarkus-mandrel-builder-image:{mandrel-flavor} Docker 映像生成原生可执行文件。

By default, the native executable will be generated using the quay.io/quarkus/ubi-quarkus-mandrel-builder-image:{mandrel-flavor} Docker image.

如果您要使用不同的 Docker 映像(例如使用不同的 GraalVM 版本)构建原生可执行文件,请使用 -Dquarkus.native.builder-image=<image name> 构建参数。

If you want to build a native executable with a different Docker image (for instance to use a different GraalVM version), use the -Dquarkus.native.builder-image=<image name> build argument.

可在此处找到可用 Docker 镜像列表: quay.io。请注意,给定的 Quarkus 版本可能与所有可用的镜像不兼容。

The list of the available Docker images can be found on quay.io. Be aware that a given Quarkus version might not be compatible with all the images available.

Running native tests

使用以下命令运行本机测试:

Run the native tests using:

./gradlew testNative

该任务依赖于 quarkusBuild,因此它会在运行测试之前生成本机镜像。

This task depends on quarkusBuild, so it will generate the native image before running the tests.

默认情况下,native-test 源集基于 maintest 源集。可以添加一个额外的源集。例如,如果你的集成测试位于 integrationTest 源集中,你可以将其指定为:

By default, the native-test source set is based on main and test source sets. It is possible to add an extra source set. For example, if your integration tests are located in an integrationTest source set, you can specify it as:

Groovy DSL
quarkus {
    sourceSets {
        extraNativeTest = sourceSets.integrationTest
    }
}
Kotlin DSL
quarkus {
    sourceSets {
        setExtraNativeTest(sourceSets["integrationTest"])
    }
}

Running integration tests

使用 @QuarkusIntegrationTest 注释的 Quarkus 集成测试将在 Quarkus 生成的工件上运行。这些测试可以放在 src/integrationTest/java 目录中并使用以下内容执行:

Quarkus integration tests (annotated with @QuarkusIntegrationTest) will run on the artifact produced by Quarkus. Those tests can be placed in a src/integrationTest/java directory and executed using:

./gradlew quarkusIntTest

此任务依赖于 testquarkusBuild 任务。最终工件将在运行测试之前生成。

This task depends on both test and quarkusBuild tasks. The final artifact will be produced before running tests.

Using fast-jar

fast-jar 现在是默认的 Quarkus 软件包类型。./gradlew build 命令的结果是在 build 下的新目录,名为 quarkus-app

fast-jar is now the default quarkus package type. The result of ./gradlew build command is a new directory under build named quarkus-app.

你可以使用以下命令运行应用程序:java -jar build/quarkus-app/quarkus-run.jar

You can run the application using: java -jar build/quarkus-app/quarkus-run.jar.

若要成功运行生成的 jar,你需要 quarkus-app 目录的全部内容。如果缺少任何文件,应用程序将无法启动或可能无法正确运行。

In order to successfully run the produced jar, you need to have the entire contents of the quarkus-app directory. If any of the files are missing, the application will not start or might not function correctly.

fast-jar 打包通过创建工件以比旧 Quarkus jar 更快地启动并消耗更少的内存,因为它已对哪个依赖项 jar 包含类和资源编制索引。在加载类或资源时,它因此可以避免像传统 jar 在类路径中搜索每个 jar。

The fast-jar packaging results in creating an artifact that starts a little faster and consumes slightly less memory than a legacy Quarkus jar because it has indexed information about which dependency jar contains classes and resources. It can thus avoid the lookup into potentially every jar on the classpath that the legacy jar necessitates, when loading a class or resource.

Building Uber-Jars

Quarkus Gradle 插件支持通过指定 quarkus.package.jar.type 参数生成单一 JAR,如下所示:

Quarkus Gradle plugin supports the generation of Uber-Jars by specifying a quarkus.package.jar.type argument as follows:

include::{includes}/devtools/build.adoc[]:!build-additional-parameters:

Unresolved directive in gradle-tooling.adoc - include::{includes}/devtools/build.adoc[] :!build-additional-parameters:

生成单一 JAR 时,你可以使用 --ignored-entry 参数指定要从生成的 JAR 中排除的项:

When building an Uber-Jar you can specify entries that you want to exclude from the generated jar by using the --ignored-entry argument:

./gradlew quarkusBuild -Dquarkus.package.jar.type=uber-jar --ignored-entry=META-INF/file1.txt

这些项相对于生成的单一 JAR 的根目录。你可以通过添加额外的 --ignored-entry 参数来指定多个项。

The entries are relative to the root of the generated Uber-Jar. You can specify multiple entries by adding extra --ignored-entry arguments.

Working with multi-module projects

默认情况下,Quarkus 不会在另一个模块内部发现 CDI Bean。

By default, Quarkus will not discover CDI beans inside another module.

在多模块项目中为模块启用 CDI bean 发现的最佳方式是包含一个 META-INF/beans.xml 文件,除非它已经是使用 quarkus-maven-plugin 配置的主应用程序模块,在这种情况下它将自动编制索引。

The best way to enable CDI bean discovery for a module in a multi-module project would be to include a META-INF/beans.xml file, unless it is the main application module already configured with the quarkus-maven-plugin, in which case it will be indexed automatically.

或者,可以使用一些非官方 ` Gradle Jandex plugins` 代替 META-INF/beans.xml 文件。

Alternatively, there is some unofficial Gradle Jandex plugins that can be used instead of the META-INF/beans.xml file.

有关此主题的更多信息,请参见 CDI 指南的 Bean Discovery 部分。

More information on this topic can be found on the Bean Discovery section of the CDI guide.

Publishing your application

为了确保 Gradle 使用正确的依赖项版本,BOM 在你的构建文件中声明为一个 enforcedPlatform。默认情况下,maven-publish 插件将阻止你因 enforcedPlatform 而发布你的应用程序。可以通过在构建文件中添加以下配置来跳过此验证:

In order to make sure the right dependency versions are being used by Gradle, the BOM is declared as an enforcedPlatform in your build file. By default, the maven-publish plugin will prevent you from publishing your application due to this enforcedPlatform. This validation can be skipped by adding the following configuration in your build file:

Groovy DSL
tasks.withType(GenerateModuleMetadata).configureEach {
    suppressedValidationErrors.add('enforced-platform')
}
Kotlin DSL
tasks.withType<GenerateModuleMetadata>().configureEach {
    suppressedValidationErrors.add("enforced-platform")
}

Configuring Quarkus builds

影响 Quarkus 构建的配置源不止一个,按照优先级顺序提到。Quarkus 构建使用 prod 配置文件:

There are multiple configuration sources that influence Quarkus builds, mentioned in the order of their priority. The Quarkus build uses the prod configuration profile:

  1. System properties (for example ./gradlew -Dquarkus.package.jar.type=fast-jar …​)

  2. System environment (for example QUARKUS_PACKAGE_JAR_TYPE=fast-jar ./gradlew …​)

  3. Configuration via the quarkus extensions’s quarkusBuildProperties For example:quarkus { quarkusBuildProperties { set("package.jar.type", "uber-jar") } }

  4. Configuration via Gradle project properties (for example ./gradlew -Pquarkus.package.jar.type=fast-jar)

  5. Configuration from a project’s application.properties, application.yaml and application.yml files, as well as a project’s application-prod.properties, application-prod.yaml and application-prod.yml files

上述优先级在 Quarkus 插件中从 3.0 开始发生了变化。较旧版本的 Quarkus Gradle 插件更喜欢设置中的 application.properties 而不是 Gradle 构建中的设置。

The above priorities have changed in Quarkus plugin starting with 3.0. Older versions of the Quarkus Gradle plugin preferred application.properties over settings in the Gradle build.

Quarkus Gradle 插件使用“标准”Quarkus 机制加载和解析配置。除了 application.properties 外,在 Quarkus 3.0 中增加了对 application.(yaml|yml) 的支持。在 3.0 中的另一项新增功能是通过 SmallRye Config 提供的所有机制现在也隐式地可用于 Quarkus Gradle 插件。

The Quarkus Gradle plugin uses the "standard" Quarkus mechanisms to load and parse configurations. Support for application.(yaml|yml) has been added in Quarkus 3.0 in addition to application.properties. Also new in 3.0 is that all mechanisms available via SmallRye Config, are implicitly also now available for the Quarkus Gradle plugin.

使用 quarkusShowEffectiveConfig 任务来显示 Quarkus 构建中使用的有效配置选项。如果您指定 --save-config-properties 命令行选项,则配置文件属性还存储在 build/<final-name>.quarkus-build.properties 文件中。

Use the quarkusShowEffectiveConfig task to show the effective configuration options used for a Quarkus build. If you specify the --save-config-properties command line option, the configuration properties are also store in the file build/<final-name>.quarkus-build.properties.

Gradle caching / task inputs

默认情况下,从 quarkus. 开头开始的系统属性和环境变量(包括来自 ~/.env 的那些环境变量)从 QUARKUS_ 开始,被视为 Gradle 任务的输入。这意味着只有那些系统属性或环境变量的更改才会导致 Gradle 的最新版本触发重新构建。对其他系统属性或环境变量的更改不会更改 Quarkus 的 Gradle 任务输入,也不会触发不必要的重新构建。

By default, system properties starting with quarkus. and environment variables, including those from ~/.env, starting with QUARKUS_, are considered as inputs for the Gradle tasks. This means that only changes to those system properties or environment variables will cause Gradle’s up-to-date to trigger a rebuild. Changes to other system properties or environment variables do not change Quarkus' Gradle task inputs and do not trigger an unnecessary rebuild.

通过 quarkus.quarkusBuildProperties 指定的或通过 Quarkus application.* 配置文件指定的配置文件属性都视为 Gradle 任务输入,换句话说,这些文件中的每次更改都会导致重新构建。

Configuration properties specified via quarkus.quarkusBuildProperties or via the Quarkus application.* configuration files are all considered as Gradle task inputs, in other words: every change in these files causes a rebuild.

如果您的 Quarkus 构建引用了不是以 quarkus. 开头开始的系统属性(或不是以 QUARKUS_ 开头开始的环境变量),则必须通过 Quarkus 构建扩展来引用那些属性。例如,如果您的 application.properties 文件引用了这样的环境变量:

If your Quarkus build references system properties that do not start with quarkus. (or environment variables that do not start with QUARKUS_), you must reference those via the Quarkus build extension. For example, if your application.properties file references an environment variable like this:

greeting.message=${FOO_MESSAGE:Hello!}

则必须将其明确声明为“缓存相关”:

it must be explicitly declared as "caching relevant":

quarkus { cachingRelevantProperties.add("FOO_MESSAGE") // Note: cachingRelevantProperties accepts regular expressions }

Build workers

Quarkus 应用程序构建使用 Gradle 的工作人员 API 在隔离进程中运行。这包括 Quarkus 应用程序构建和 Quarkus 代码生成。这对于从 quarkus 扩展和 Gradle 项目属性正确传递配置到 Quarkus 的代码生成器/应用程序构建器是必需的。

Quarkus application builds are ran in isolated processes using Gradle’s worker API. This includes the Quarkus application build and Quarkus code generation. This is necessary to properly pass the configuration from the quarkus extension and Gradle project properties to Quarkus' code generator / application builder.

执行代码生成和/或 Quarkus 构建的进程的 JVM 设置可以按如下方式进行配置,详情请见 JavaForkOptions

The JVM settings of the processes performing the code generation and/or Quarkus build can be configured as follows. See JavaForkOptions for details.

Groovy DSL
plugins {
    id 'java'
    id 'io.quarkus'
}

quarkus {
    buildForkOptions {
        maxHeapSize = '2g'
    }
    codeGenForkOptions {
        maxHeapSize = '128m'
    }
}
Kotlin DSL
plugins {
    java
    id("io.quarkus")
}

quarkus {
    buildForkOptions {
        maxHeapSize = '2g'
    }
    codeGenForkOptions {
        maxHeapSize = '128m'
    }
}

Cached build artifacts

Gradle’s build cache 是一种非常有效的机制,可以通过重复使用以前生成的输出( Incremental build 了解技术细节)来改善整体构建运行时。

Gradle’s build cache is a very efficient mechanism to improve the overall build runtime, by reusing previously generated outputs (see Incremental build for technical details).

Quarkus 插件利用了 Gradle 的最新检查机制和构建缓存。构建缓存可以是本地或本地 plus 远程缓存服务器,或者如果在 CI 环境中配置,则可以作为检索和存储整个缓存的工件的远程环境,例如使用 Gradle’s GitHub action 或直接/手动使用 GitHub 的 GitHub’s cache action

The Quarkus plugin leverages the Gradle mechanisms of up-to-date checks and the build cache. The build cache can be local or local plus a remote cache server or, if configured in CI environments, remote in the sense of retrieving and storing the whole cache as an artifact, for example using Gradle’s GitHub action or directly/manually GitHub’s GitHub’s cache action.

Quarkus Gradle 插件关心 what 是否已缓存 in which environment(CI 或本地开发)。像 uber-jar 和本机二进制文件这样的大型工件在 CI 中不会被缓存,但在本地开发环境中会被缓存。

The Quarkus Gradle plugin cares about what is cached in which environment (CI or local development). Big artifacts like uber-jars and native binaries are not cached in CI, but are cached in local development environments.

如果存在 CI 环境变量,则 Quarkus Gradle 插件会检测一个 CI environment

The Quarkus Gradle plugin detects a CI environment, if the CI environment variable is present.

非 CI 和 CI 环境中各种 Quarkus 包类型如何进行缓存,在下表中进行了介绍。请注意,即使任务的输出不是 cachedup-to-date 检查仍然适用。

How the various Quarkus package types are cached in non-CI and CI environments is described in the following table. Note that even if a task’s output is not cached, the up-to-date checks still apply.

Quarkus 应用程序构建被拆分为三个任务。 quarkusBuild 任务负责 provide 一个已构建的 Quarkus 应用程序。 quarkusDependenciesBuildquarkusAppPartsBuild 任务被视为内部任务(可能会在任何时间改变且没有事先通知)。请参阅以下详情。

The Quarkus application build is split across three tasks. The quarkusBuild task is responsible to provide a built Quarkus application. The tasks quarkusDependenciesBuild and quarkusAppPartsBuild are considered internal tasks (may change at any time w/o prior notice). See below for details.

Quarkus package type

Notes

Caching (non-CI)

Caching in CI

fast-jar, jar

Dependency jars are stored unmodified as individual files in the quarkus-app/lib/ directory. All other files in the quarkus-app/ directory are generated.

The quarkusAppPartsBuild task builds fast-jar package-type applications and allows caching of the generated pieces, which is everything except the dependencies in the quarkus-app/lib/ directory. The quarkusDependenciesBuild task is used to collect the dependencies via Gradle mechanisms. The quarkusBuild task then assembles the outputs of the quarkusAppPartsBuild and quarkusDependenciesBuild tasks.

Note: fast-jar (or -jar) is the default if no package type has been explicitly configured.

mutable-jar, uber-jar, native, native-sources

The quarkusBuild task is responsible for building the Quarkus application.

The quarkusAppPartsBuild and quarkusDependenciesBuild tasks do nothing for `uber-jar`s.

legacy-jar, legacy

legacy-jar builds work similar to fast-jar builds, except that the directory structure is different and the modified-*.jar files are considered as generated.

在本地开发环境中,存储(和检索)更大缓存工件的成本(即时间)低于重新构建 Quarkus 应用程序的成本。这意味着 Quarkus Gradle 插件允许在非 CI 环境中缓存甚至像 uber-jar 或本机二进制文件这样可能较大的工件。在 CI 环境中,针对不断变化的代码库状态运行构建(例如:针对主分支上的每次提交运行 CI),将每个构建的(和较大的)工件添加到构建缓存中将导致构建缓存变得不必要的大,这在 GitHub 中尤为成问题,GitHub 中缓存工件的总量被限制为 10 GB。

In a local development environment, the cost (think: time) of storing (and retrieving) even bigger cache artifacts is lower than the cost of re-building a Quarkus application. This means, that The Quarkus Gradle plugin allows caching even potentially big artifacts like uber-jars or native binaries in non-CI environments. In CI environments, which run builds against varying states of a code base (think: running CI against every commit on a main branch), adding each built (and big) artifact to the build cache would let the build cache become unnecessarily big, which becomes a problem for example in GitHub, where the total amount of cached artifacts is limited to 10 GB.

背景信息:Gradle 中有两种相关的机制可用于提高构建性能:

Background information: There are two related mechanisms in Gradle at play to improve build performance:

  • Up-to-date checks allow a task’s execution to be skipped, if the inputs and outputs of the tasks did not change. For example, consider a Java compile tasks: if the library dependencies and the source files (the inputs) did not change and the compiled class files (the outputs) are still available, compilation can be skipped.

  • The build cache can store the outputs of (cacheable) tasks in the local build cache. The output of a task can be restored from the cache.

最新检查和构建缓存的交互带来的好处是以建模“inputs”和“outputs”为代价的。输入不仅是文件或目录,还有构建期间使用的 Java 版本、操作系统、工作目录、配置选项等。因此,所有会影响任务操作的输出的内容都必须声明为任务的输入。

The benefits of up-to-date checks and the interaction of the build cache come with the cost of modeling the inputs and outputs. Inputs are not only files or directories, but also the Java version used during the build, the operating system, the working directory, configuration options, and so on. So everything that influences the output of a task action must be declared as an input of the task.

Gradle configuration cache

Quarkus Gradle 插件适用于启用了“ Gradle’s configuration cache” 的构建,但已禁用 Quarkus 任务的配置缓存。这意味着 Quarkus 插件不会破坏此类 Gradle 构建。

The Quarkus Gradle plugin works with builds that have the Gradle’s configuration cache enabled, but the configuration cache is disabled for the Quarkus tasks. This means, that the Quarkus plugin does not break such Gradle builds.