TP13.2: Spring Cloud Config Server
🎯 Objetivos del TP
- Crear un Config Server con backend Git
- Configurar los servicios como Config Clients
- Implementar el refresh de configuración en caliente
- Gestionar los perfiles (dev, prod)
Duración estimada: 1h
📋 Arquitectura
Parte 1: Crear el Repositorio de Configuración (15 min)
1.1 Crear un Repo Git Local (o GitHub)
# Crear la carpeta
mkdir config-repo
cd config-repo
git init
# Crear los archivos de configuración
1.2 Configuración Común (application.yml)
# config-repo/application.yml
# Configuración compartida por TODOS los servicios
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
instance:
prefer-ip-address: true
management:
endpoints:
web:
exposure:
include: health,info,refresh
logging:
level:
root: INFO
1.3 Configuración User Service
# config-repo/user-service.yml
server:
port: 8081
user:
default-role: USER
password-min-length: 8
welcome-message: "Welcome to User Service!"
# config-repo/user-service-dev.yml
user:
welcome-message: "Welcome to User Service (DEV)!"
logging:
level:
com.example: DEBUG
# config-repo/user-service-prod.yml
user:
welcome-message: "Welcome to User Service (PRODUCTION)"
password-min-length: 12
logging:
level:
com.example: WARN
1.4 Configuración Product Service
# config-repo/product-service.yml
server:
port: 8083
product:
max-per-page: 20
currency: CAD
featured-enabled: true
# config-repo/product-service-dev.yml
product:
currency: DEV-CAD
featured-enabled: true
logging:
level:
com.example: DEBUG
1.5 Hacer Commit de los Archivos
cd config-repo
git add .
git commit -m "Initial configuration files"
Parte 2: Config Server (20 min)
2.1 Crear el Proyecto
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.0</version>
</parent>
<groupId>com.example</groupId>
<artifactId>config-server</artifactId>
<version>1.0.0</version>
<properties>
<java.version>17</java.version>
<spring-cloud.version>2023.0.0</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
2.2 Aplicación Principal
package com.example.configserver;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.config.server.EnableConfigServer;
@SpringBootApplication
@EnableConfigServer
public class ConfigServerApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigServerApplication.class, args);
}
}
2.3 Configuración (con Git Local)
# src/main/resources/application.yml
server:
port: 8888
spring:
application:
name: config-server
cloud:
config:
server:
git:
# Ruta a su repo local (Windows)
uri: file:///C:/chemin/vers/config-repo
# O ruta Linux/Mac
# uri: file://${user.home}/config-repo
default-label: master
clone-on-start: true
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
2.4 Configuración Alternativa (GitHub)
spring:
cloud:
config:
server:
git:
uri: https://github.com/votre-username/config-repo
default-label: main
# Si el repo es privado:
# username: ${GIT_USERNAME}
# password: ${GIT_TOKEN}
2.5 Probar el Config Server
# Iniciar el Config Server
cd config-server
mvn spring-boot:run
# Probar los endpoints
# Formato: /{application}/{profile}
curl http://localhost:8888/user-service/default
curl http://localhost:8888/user-service/dev
curl http://localhost:8888/user-service/prod
curl http://localhost:8888/product-service/dev
Respuesta esperada para /user-service/dev:
{
"name": "user-service",
"profiles": ["dev"],
"label": null,
"version": "abc123...",
"propertySources": [
{
"name": "file:///C:/config-repo/user-service-dev.yml",
"source": {
"user.welcome-message": "Welcome to User Service (DEV)!",
"logging.level.com.example": "DEBUG"
}
},
{
"name": "file:///C:/config-repo/user-service.yml",
"source": {
"server.port": 8081,
"user.default-role": "USER"
}
},
{
"name": "file:///C:/config-repo/application.yml",
"source": {
"eureka.client.service-url.defaultZone": "http://localhost:8761/eureka/"
}
}
]
}
Parte 3: Config Client (User Service) (15 min)
3.1 Agregar las Dependencias
Modifique el pom.xml de User Service:
<dependencies>
<!-- Existentes... -->
<!-- Config Client -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<!-- Bootstrap (para cargar config ANTES de la app) -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>
</dependencies>
3.2 Crear bootstrap.yml
# src/main/resources/bootstrap.yml
spring:
application:
name: user-service
profiles:
active: dev
cloud:
config:
uri: http://localhost:8888
fail-fast: true
retry:
initial-interval: 1000
max-attempts: 6
3.3 Simplificar application.yml Local
# src/main/resources/application.yml
# La mayoría de la configuración ahora viene del Config Server
# Solo se mantiene lo que es local/override
# Nada o casi nada - ¡todo viene del Config Server!
3.4 Usar las Propiedades Externalizadas
package com.example.userservice.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
@RestController
@RequestMapping("/api/config")
@RefreshScope // ¡Permite el refresh en caliente!
public class ConfigController {
@Value("${user.welcome-message}")
private String welcomeMessage;
@Value("${user.default-role}")
private String defaultRole;
@Value("${user.password-min-length}")
private int passwordMinLength;
@GetMapping
public ResponseEntity<Map<String, Object>> getConfig() {
return ResponseEntity.ok(Map.of(
"welcomeMessage", welcomeMessage,
"defaultRole", defaultRole,
"passwordMinLength", passwordMinLength
));
}
@GetMapping("/welcome")
public ResponseEntity<String> getWelcome() {
return ResponseEntity.ok(welcomeMessage);
}
}
3.5 Probar
# Orden de inicio:
# 1. Eureka Server (8761)
# 2. Config Server (8888)
# 3. User Service (8081)
cd user-service
mvn spring-boot:run
# Verificar que la configuración está cargada
curl http://localhost:8081/api/config
Resultado esperado:
{
"welcomeMessage": "Welcome to User Service (DEV)!",
"defaultRole": "USER",
"passwordMinLength": 8
}
Parte 4: Refresh en Caliente (10 min)
4.1 Modificar la Configuración
Edite config-repo/user-service-dev.yml:
user:
welcome-message: "Welcome to User Service (DEV) - UPDATED!"
logging:
level:
com.example: DEBUG
cd config-repo
git add .
git commit -m "Update welcome message"
4.2 Verificar Antes del Refresh
curl http://localhost:8081/api/config/welcome
# Resultado: "Welcome to User Service (DEV)!"
# (Valor anterior - aún no actualizado)
4.3 Disparar el Refresh
curl -X POST http://localhost:8081/actuator/refresh
Respuesta:
["user.welcome-message"]
4.4 Verificar Después del Refresh
curl http://localhost:8081/api/config/welcome
# Resultado: "Welcome to User Service (DEV) - UPDATED!"
🎉 ¡La configuración se ha actualizado sin reiniciar el servicio!
✅ Checklist de Validación
- Config Server inicia en http://localhost:8888
-
curl http://localhost:8888/user-service/devretorna la configuración - User Service carga su configuración desde Config Server
-
/api/configmuestra las propiedades externalizadas - Modificación + commit +
/actuator/refresh→ nueva configuración
🎯 Ejercicios Bonus
Ejercicio 1: Perfil Producción
Inicie User Service con el perfil prod:
mvn spring-boot:run -Dspring-boot.run.arguments=--spring.profiles.active=prod
Verifique que passwordMinLength es 12.
Ejercicio 2: Descubrimiento vía Eureka
En lugar de una URL fija, utilice Eureka:
# bootstrap.yml
spring:
cloud:
config:
discovery:
enabled: true
service-id: config-server
Ejercicio 3: Configuración Product Service
Configure Product Service como Config Client y exponga /api/config.