YAML配置
YAML 是一种非常流行的格式。Kubernetes高度依赖YAML格式来编写各种资源描述符。
除了标准的 Java Properties 文件之外,Quarkus 还提供了使用 YAML 的能力。
启用YAML配置
要启用YAML配置,添加以下 quarkus-config-yaml
扩展:
quarkus extension add 'quarkus-config-yaml'
./mvnw quarkus:add-extension -Dextensions='quarkus-config-yaml'
./gradlew addExtension --extensions='quarkus-config-yaml'
你也可以直接将以下依赖添加到你的项目中:
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-config-yaml</artifactId>
</dependency>
implementation("io.quarkus:quarkus-config-yaml")
删除 src/main/resources/application.properties
,并创建一个 src/main/resources/application.yaml
文件。
如果两者都存在,Quarkus会优先考虑YAML文件中的配置属性,接着是 Properties 文件中的配置属性。然而,为了避免混淆,我们建议删除 Properties 文件。 |
Quarkus同时支持 yml 和 yaml 文件扩展名。
|
例子
以下代码段提供了YAML配置的示例:
# YAML支持注释
quarkus:
datasource:
db-kind: postgresql
jdbc:
url: jdbc:postgresql://localhost:5432/some-database
# REST Client 配置属性
quarkus:
rest-client:
org.acme.rest.client.ExtensionsService:
url: https://stage.code.quarkus.io/api
# 对于使用引号的配置属性名称,不需要拆分引号内的字符串
quarkus:
log:
category:
"io.quarkus.category":
level: INFO
quarkus:
datasource:
url: jdbc:postgresql://localhost:5432/quarkus_test
hibernate-orm:
database:
generation: drop-and-create
oidc:
enabled: true
auth-server-url: http://localhost:8180/auth/realms/quarkus
client-id: app
app:
frontend:
oidc-realm: quarkus
oidc-app: app
oidc-server: http://localhost:8180/auth
# 使用环境
"%test":
quarkus:
oidc:
enabled: false
security:
users:
file:
enabled: true
realm-name: quarkus
plain-text: true
环境配置(Profiles)
正如你在之前的代码片段中所看到的,你可以在YAML中使用 profiles 。该环境配置的key 需要使用双引号: "%test"
。这是因为YAML不支持以 %
开始的键。
只有当 test
环境配置处于激活状态时, "%test"
键下的所有内容才会被启用。例如在前面的代码片段中,它禁用了OIDC ( quarkus.oidc.enabled: false
),反之,如果没有 test
环境配置,它将会被启用。
至于Java Properties 格式,你可以定义你自己的环境配置:
quarkus:
http:
port: 8081
"%staging":
quarkus:
http:
port: 8082
如果你启用了 staging
环境配置,HTTP 端口将会是 8082,反之,端口将会是 8081。
YAML 配置还支持环境配置文件的感知。在这种情况下,特定环境下的配置文件的属性可以书写在一个名为 application-{profile}.yaml
的文件中。前面的例子也可以表示为:
quarkus:
http:
port: 8081
quarkus:
http:
port: 8082
表达式
The YAML format also supports property expressions, using the same format as Java Properties:
mach: 3
x:
factor: 2.23694
display:
mach: ${mach}
unit:
name: "mph"
factor: ${x.factor}
Note that you can reference nested properties using the .
(dot) separator as in ${x.factor}
.
外部application.yaml 文件
The application.yaml
file may also be placed in config/application.yaml
to specialize the runtime configuration. The file has to be present in the root of the working directory relative to the Quarkus application runner:
.
├── config
│ └── application.yaml
├── my-app-runner
如果存在的话,此文件中的值将覆盖常规 application.yaml
文件中的任何值。
配置键冲突
MicroProfile Config 规范将配置键定义为任意的 .
- 分隔字符串。然而,像 YAML 这样的结构化格式可能只支持配置命名空间的一个子集。例如,考虑有两个配置属性 quarkus.http.cors
和 quarkus.http.cors.methods
的情况。一个属性是另一个属性的前缀,因此如何在 YAML 配置中指定这两个键可能不是很明确。
这可以通过为任意YAML属性使用 null
键(以 ~
为代表)来解决,该属性是另一个属性的前缀:
quarkus:
http:
cors:
~: true
methods: GET,PUT,POST
YAML null
键不被包含在配置属性名称的程序集中,允许在任意级别使用它们来消除配置键的歧义。