TP13.2: Spring Cloud Config Server
đŻ Objectifs du TPâ
- Créer un Config Server avec backend Git
- Configurer les services comme Config Clients
- Implémenter le refresh de configuration à chaud
- Gérer les profils (dev, prod)
Durée estimée: 1h
đ Architectureâ
Partie 1: CrĂ©er le Repository de Configuration (15 min)â
1.1 CrĂ©er un Repo Git Local (ou GitHub)â
# Créer le dossier
mkdir config-repo
cd config-repo
git init
# Créer les fichiers de configuration
1.2 Configuration Commune (application.yml)â
# config-repo/application.yml
# Configuration partagée par TOUS les services
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 Configuration 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 Configuration 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 Commit les Fichiersâ
cd config-repo
git add .
git commit -m "Initial configuration files"
Partie 2: Config Server (20 min)â
2.1 CrĂ©er le Projetâ
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 Application Principaleâ
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 Configuration (avec Git Local)â
# src/main/resources/application.yml
server:
port: 8888
spring:
application:
name: config-server
cloud:
config:
server:
git:
# Chemin vers votre repo local (Windows)
uri: file:///C:/chemin/vers/config-repo
# OU chemin 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 Configuration Alternative (GitHub)â
spring:
cloud:
config:
server:
git:
uri: https://github.com/votre-username/config-repo
default-label: main
# Si repo privé:
# username: ${GIT_USERNAME}
# password: ${GIT_TOKEN}
2.5 Tester le Config Serverâ
# Démarrer le Config Server
cd config-server
mvn spring-boot:run
# Tester les endpoints
# Format: /{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
Réponse attendue pour /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/"
}
}
]
}
Partie 3: Config Client (User Service) (15 min)â
3.1 Ajouter les DĂ©pendancesâ
Modifiez le pom.xml de User Service:
<dependencies>
<!-- Existantes... -->
<!-- Config Client -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<!-- Bootstrap (pour charger config AVANT l'app) -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>
</dependencies>
3.2 CrĂ©er 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 Simplifier application.yml Localâ
# src/main/resources/application.yml
# La plupart de la config vient du Config Server maintenant
# On garde seulement ce qui est local/override
# Rien ou presque - tout vient du Config Server!
3.4 Utiliser les PropriĂ©tĂ©s ExternalisĂ©esâ
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 // Permet le refresh Ă chaud!
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 Testerâ
# Ordre de démarrage:
# 1. Eureka Server (8761)
# 2. Config Server (8888)
# 3. User Service (8081)
cd user-service
mvn spring-boot:run
# Vérifier que la config est chargée
curl http://localhost:8081/api/config
Résultat attendu:
{
"welcomeMessage": "Welcome to User Service (DEV)!",
"defaultRole": "USER",
"passwordMinLength": 8
}
Partie 4: Refresh Ă Chaud (10 min)â
4.1 Modifier la Configurationâ
Ăditez 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 VĂ©rifier Avant Refreshâ
curl http://localhost:8081/api/config/welcome
# Résultat: "Welcome to User Service (DEV)!"
# (Ancienne valeur - pas encore rafraĂźchie)
4.3 DĂ©clencher le Refreshâ
curl -X POST http://localhost:8081/actuator/refresh
Réponse:
["user.welcome-message"]
4.4 VĂ©rifier AprĂšs Refreshâ
curl http://localhost:8081/api/config/welcome
# Résultat: "Welcome to User Service (DEV) - UPDATED!"
đ La configuration a Ă©tĂ© mise Ă jour sans redĂ©marrer le service!
â Checklist de Validationâ
- Config Server démarre sur http://localhost:8888
-
curl http://localhost:8888/user-service/devretourne la config - User Service charge sa config depuis Config Server
-
/api/configaffiche les propriétés externalisées - Modification + commit +
/actuator/refreshâ nouvelle config
đŻ Exercices Bonusâ
Exercice 1: Profil Productionâ
Démarrez User Service avec le profil prod:
mvn spring-boot:run -Dspring-boot.run.arguments=--spring.profiles.active=prod
Vérifiez que passwordMinLength est 12.
Exercice 2: DĂ©couverte via Eurekaâ
Au lieu d'une URL fixe, utilisez Eureka:
# bootstrap.yml
spring:
cloud:
config:
discovery:
enabled: true
service-id: config-server
Exercice 3: Configuration Product Serviceâ
Configurez Product Service comme Config Client et exposez /api/config.