Lectura de propiedades del servidor de configuración de Spring Cloud
Esta guía explica cómo su aplicación Quarkus puede leer las propiedades de configuración en tiempo de ejecución desde el Servidor de Configuración de Spring Cloud.
Requisitos previos
To complete this guide, you need:
-
Roughly 15 minutes
-
An IDE
-
JDK 11+ installed with
JAVA_HOME
configured appropriately -
Apache Maven 3.8.6
-
Optionally the Quarkus CLI if you want to use it
-
Optionally Mandrel or GraalVM installed and configured appropriately if you want to build a native executable (or Docker if you use a native container build)
Solución
Le recomendamos que siga las instrucciones de las siguientes secciones y cree la aplicación paso a paso.
Poner en marcha un servidor de configuración
Para poner en marcha el Config Server necesario para esta guía, siga las instrucciones indicadas aquí. El resultado final de ese proceso es un Config Server en funcionamiento que proporcionará el valor Hello world
para una propiedad de configuración llamada message
cuando la aplicación que consulta el servidor se llama a-bootiful-client
.
Creación del proyecto Maven
En primer lugar, necesitamos un nuevo proyecto. Cree un nuevo proyecto con el siguiente comando:
Este comando genera un proyecto que importa la extensión spring-cloud-config-client
.
Si ya tienes configurado tu proyecto Quarkus, puedes añadir la extensión spring-cloud-config-client
a tu proyecto ejecutando el siguiente comando en el directorio base de tu proyecto:
quarkus extension add 'spring-cloud-config-client'
./mvnw quarkus:add-extension -Dextensions='spring-cloud-config-client'
./gradlew addExtension --extensions='spring-cloud-config-client'
Esto añadirá lo siguiente a su archivo de construcción:
<dependency>
<groupId>io.quarkus</groupId>
<artifactId>quarkus-spring-cloud-config-client</artifactId>
</dependency>
implementation("io.quarkus:quarkus-spring-cloud-config-client")
GreetingController
En primer lugar, cree un simple recurso JAX-RS GreetingResource
en el archivo src/main/java/org/acme/spring/cloud/config/client/GreetingResource.java
con el siguiente aspecto:
package org.acme.spring.spring.cloud.config.client;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Path("/hello")
public class GreetingResource {
@GET
@Produces(MediaType.TEXT_PLAIN)
public String hello() {
return "hello";
}
}
Como queremos utilizar propiedades de configuración obtenidas del Servidor de Configuración, actualizaremos el GreetingResource
para inyectar la propiedad message
. El código actualizado tendrá el siguiente aspecto:
package org.acme.spring.spring.cloud.config.client;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.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;
}
}
Configuración de la aplicación
Quarkus proporciona varios controles de configuración bajo la raíz quarkus.spring-cloud-config
. Para los propósitos de esta guía, nuestra aplicación Quarkus va a ser configurada en application.properties
como sigue:
# 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
Empaquetar y ejecutar la aplicación
Ejecuta la aplicación con:
quarkus dev
./mvnw quarkus:dev
./gradlew --console=plain quarkusDev
Abra su navegador en http://localhost:8080/greeting.
El resultado debe ser: Hello world
ya que es el valor obtenido del servidor Spring Cloud Config.
Ejecutar la aplicación como un ejecutable nativo
Por supuesto, puedes crear una imagen nativa siguiendo las instrucciones de la guía Construir un ejecutable nativo.
Más guías de Spring
Quarkus tiene más características de compatibilidad con Spring. Consulte las siguientes guías para obtener más detalles:
Referencia del cliente Spring Cloud Config
Configuration property fixed at build time - All other configuration properties are overridable at runtime
Type |
Default |
|
---|---|---|
If enabled, will try to read the configuration from a Spring Cloud Config Server Environment variable: |
boolean |
|
If set to true, the application will not stand up if it cannot obtain configuration from the Config Server Environment variable: |
boolean |
|
The Base URI where the Spring Cloud Config Server is available Environment variable: |
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: |
string |
|
The amount of time to wait when initially establishing a connection before giving up and timing out.
Specify Environment variable: |
|
|
The amount of time to wait for a read on a socket before an exception is thrown.
Specify Environment variable: |
|
|
The username to be used if the Config Server has BASIC Auth enabled Environment variable: |
string |
|
The password to be used if the Config Server has BASIC Auth enabled Environment variable: |
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: |
path |
|
Password of TrustStore to be used containing the SSL certificate used by the Config server Environment variable: |
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: |
path |
|
Password of KeyStore to be used containing the SSL certificate for authentication with the Config server Environment variable: |
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: |
string |
|
When using HTTPS and no keyStore has been specified, whether to trust all certificates Environment variable: |
boolean |
|
Custom headers to pass the Spring Cloud Config Server when performing the HTTP request Environment variable: |
|
About the Duration format
El formato de las duraciones utiliza el formato estándar También puede proporcionar valores de duración que empiecen por un número. En este caso, si el valor consiste sólo en un número, el conversor trata el valor como segundos. En caso contrario, |