Aller au contenu principal

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/dev retourne la config
  • User Service charge sa config depuis Config Server
  • /api/config affiche 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.


TP13.3: API Gateway →

Retour au Module 13