Reading properties from Spring Cloud Config Server
This guide explains how your Quarkus application can read configuration properties at runtime from the Spring Cloud Config Server.
Pré-requisitos
Para concluir este guia, você precisa:
-
Cerca de 15 minutos
-
Um IDE
-
JDK 17+ installed with
JAVA_HOME
configured appropriately -
Apache Maven 3.9.9
-
Opcionalmente, o Quarkus CLI se você quiser usá-lo
-
Opcionalmente, Mandrel ou GraalVM instalado e configurado apropriadamente se você quiser criar um executável nativo (ou Docker se você usar uma compilação de contêiner nativo)
Solução
We recommend that you follow the instructions in the next sections and create the application step by step.
Stand up a Config Server
To stand up the Config Server required for this guide, please follow the instructions outlined here.
The end result of that process is a running Config Server that will provide the Hello world
value for a configuration property named message
when the application querying the server is named a-bootiful-client
.
Criar o projeto Maven
Primeiro, precisamos de um novo projeto. Crie um novo projeto com o seguinte comando:
Para usuários do Windows:
-
Se estiver usando cmd, (não use barra invertida '\' e coloque tudo na mesma linha)
-
Se estiver usando o Powershell, envolva os parâmetros '-D' entre aspas duplas, por exemplo, '"-DprojectArtifactId=spring-cloud-config-quickstart"'
This command generates a project which imports the spring-cloud-config-client
extension.
If you already have your Quarkus project configured, you can add the spring-cloud-config-client
extension
to your project by running the following command in your project base directory:
quarkus extension add spring-cloud-config-client
./mvnw quarkus:add-extension -Dextensions='spring-cloud-config-client'
./gradlew addExtension --extensions='spring-cloud-config-client'
Isto irá adicionar o seguinte trecho no seu arquivo de build:
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-spring-cloud-config-client</artifactId>
</dependency>
implementation("io.quarkus:quarkus-spring-cloud-config-client")
GreetingController
First, create a simple GreetingResource
Jakarta REST resource in the
src/main/java/org/acme/spring/cloud/config/client/GreetingResource.java
file that looks like:
package org.acme.spring.spring.cloud.config.client;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
@Path("/hello")
public class GreetingResource {
@GET
@Produces(MediaType.TEXT_PLAIN)
public String hello() {
return "hello";
}
}
As we want to use configuration properties obtained from the Config Server, we will update the GreetingResource
to inject the message
property. The updated code will look like this:
package org.acme.spring.spring.cloud.config.client;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
import org.eclipse.microprofile.config.inject.ConfigProperty;
@Path("/hello")
public class GreetingResource {
@ConfigProperty(name = "message", defaultValue="hello default")
String message;
@GET
@Produces(MediaType.TEXT_PLAIN)
public String hello() {
return message;
}
}
Configuring the application
Quarkus provides various configuration knobs under the quarkus.spring-cloud-config
root. For the purposes of this guide, our Quarkus application is going to be configured in application.properties
as follows:
# use the same name as the application name that was configured when standing up the Config Server
quarkus.application.name=a-bootiful-client
# enable retrieval of configuration from the Config Server - this is off by default
quarkus.spring-cloud-config.enabled=true
# configure the URL where the Config Server listens to HTTP requests - this could have been left out since http://localhost:8888 is the default
quarkus.spring-cloud-config.url=http://localhost:8888
If you are using Gradle, the Gradle setting |
Empacote e execute a aplicação
Execute a aplicação com:
quarkus dev
./mvnw quarkus:dev
./gradlew --console=plain quarkusDev
Abra o seu navegador em http://localhost:8080/greeting .
The result should be: Hello world
as it is the value obtained from the Spring Cloud Config server.
Run the application as a native executable
You can of course create a native image using the instructions of the Building a native executable guide.
Mais guias de Spring
O Quarkus possui mais funcionalidades compatíveis com o Spring. Para mais informações, consulte os seguintes guias:
Spring Cloud Config Client Reference
Propriedade de Configuração Fixa no Momento da Compilação - Todas as outras propriedades de configuração podem ser sobrepostas em tempo de execução.
Configuration property |
Tipo |
Padrão |
---|---|---|
If enabled, will try to read the configuration from a Spring Cloud Config Server Environment variable: Show more |
boolean |
|
If set to true, the application will not stand up if it cannot obtain configuration from the Config Server Environment variable: Show more |
boolean |
|
The Base URI where the Spring Cloud Config Server is available Environment variable: Show more |
string |
|
Name of the application on Spring Cloud Config server. Could be a list of names to load multiple files (value separated by a comma) Environment variable: Show more |
string |
|
The label to be used to pull remote configuration properties. The default is set on the Spring Cloud Config Server (generally "master" when the server uses a Git backend). Environment variable: Show more |
string |
|
The amount of time to wait when initially establishing a connection before giving up and timing out. Specify Environment variable: Show more |
|
|
The amount of time to wait for a read on a socket before an exception is thrown. Specify Environment variable: Show more |
|
|
The username to be used if the Config Server has BASIC Auth enabled Environment variable: Show more |
string |
|
The password to be used if the Config Server has BASIC Auth enabled Environment variable: Show more |
string |
|
TrustStore to be used containing the SSL certificate used by the Config server Can be either a classpath resource or a file system path Environment variable: Show more |
path |
|
Password of TrustStore to be used containing the SSL certificate used by the Config server Environment variable: Show more |
string |
|
KeyStore to be used containing the SSL certificate for authentication with the Config server Can be either a classpath resource or a file system path Environment variable: Show more |
path |
|
Password of KeyStore to be used containing the SSL certificate for authentication with the Config server Environment variable: Show more |
string |
|
Password to recover key from KeyStore for SSL client authentication with the Config server If no value is provided, the key-store-password will be used Environment variable: Show more |
string |
|
When using HTTPS and no keyStore has been specified, whether to trust all certificates Environment variable: Show more |
boolean |
|
Custom headers to pass the Spring Cloud Config Server when performing the HTTP request Environment variable: Show more |
Map<String,String> |
|
The profiles to use for lookup Environment variable: Show more |
list of string |
|
Microprofile Config ordinal. Environment variable: Show more |
int |
|
About the Duration format
To write duration values, use the standard Você também pode usar um formato simplificado, começando com um número:
Em outros casos, o formato simplificado é traduzido para o formato 'java.time.Duration' para análise:
|