Aller au contenu principal

Chapitre 3: Configuration Centralisée avec Spring Cloud Config

🎯 Objectifs du Chapitre​

  • Comprendre le besoin de configuration centralisée
  • Configurer un Spring Cloud Config Server
  • Connecter les services comme Config Clients
  • Utiliser Git comme backend de configuration
  • Implémenter le refresh de configuration à chaud
  • Gérer l'encryption des secrets

1. Pourquoi la Configuration Centralisée?​

1.1 Le Problème Sans Config Server​

microservices/
├── user-service/
│ └── application.yml # Config spécifique
├── product-service/
│ └── application.yml # Config spécifique
├── order-service/
│ └── application.yml # Config spécifique
├── payment-service/
│ └── application.yml # Config spécifique
└── inventory-service/
└── application.yml # Config spécifique

Problèmes:

  • Changer le mot de passe DB = modifier 5 fichiers
  • Redéployer 5 services
  • Pas de versioning centralisé
  • Secrets en clair dans chaque service
  • Pas de refresh sans redémarrage

1.2 La Solution: Config Server​

Avantages:

  • Une seule source de vérité
  • Versioning avec Git (historique, branches)
  • Refresh sans redéploiement
  • Encryption des secrets
  • Configuration par environnement (dev, prod)

2. Architecture Spring Cloud Config​

2.1 Composants​

2.2 Flux de Configuration​


3. Configuration du Config Server​

3.1 Structure du Projet​

config-server/
├── pom.xml
└── src/main/
├── java/com/example/configserver/
│ └── ConfigServerApplication.java
└── resources/
└── application.yml

3.2 Dépendances Maven​

<?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>
<!-- Config Server -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>

<!-- Eureka Client (pour s'enregistrer) -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

<!-- Security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>

<!-- Actuator -->
<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>

3.3 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 // Active le Config Server
public class ConfigServerApplication {

public static void main(String[] args) {
SpringApplication.run(ConfigServerApplication.class, args);
}
}

3.4 Configuration avec Git​

# application.yml
server:
port: 8888

spring:
application:
name: config-server
cloud:
config:
server:
git:
# Repository Git (GitHub, GitLab, Bitbucket, local)
uri: https://github.com/votre-org/config-repo
# Branche par défaut
default-label: main
# Dossier dans le repo (optionnel)
search-paths: config
# Clone au démarrage
clone-on-start: true
# Credentials si repo privé
username: ${GIT_USERNAME:}
password: ${GIT_PASSWORD:}
# Timeout
timeout: 10

# Eureka Client
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/

# Security
spring:
security:
user:
name: config
password: config123

3.5 Configuration Locale (pour dev)​

spring:
cloud:
config:
server:
native:
search-locations:
- file:///C:/config-repo
- classpath:/config
profiles:
active: native # Utiliser le filesystem au lieu de Git

4. Structure du Repository de Configuration​

4.1 Convention de Nommage​

config-repo/
├── application.yml # Config commune à TOUS les services
├── application-dev.yml # Config dev pour TOUS les services
├── application-prod.yml # Config prod pour TOUS les services
├── user-service.yml # Config spécifique user-service
├── user-service-dev.yml # user-service en dev
├── user-service-prod.yml # user-service en prod
├── product-service.yml
├── product-service-dev.yml
├── product-service-prod.yml
├── order-service.yml
├── order-service-dev.yml
└── order-service-prod.yml

4.2 Priorité de Configuration​

La configuration est mergée dans cet ordre (du moins au plus prioritaire):

  1. application.yml (base commune)
  2. application-\{profile\}.yml (profil commun)
  3. {service-name}.yml (service spécifique)
  4. {service-name}-\{profile\}.yml (service + profil)

4.3 Exemple: application.yml (commun)​

# config-repo/application.yml
# Configuration partagée par TOUS les services

# Eureka commun
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
instance:
prefer-ip-address: true

# Actuator commun
management:
endpoints:
web:
exposure:
include: health,info,refresh
endpoint:
health:
show-details: always

# Logging commun
logging:
level:
root: INFO
com.example: DEBUG

4.4 Exemple: user-service.yml​

# config-repo/user-service.yml
# Configuration spécifique au User Service

server:
port: 8081

spring:
datasource:
url: jdbc:postgresql://localhost:5432/users_db
username: ${DB_USERNAME:postgres}
password: ${DB_PASSWORD:postgres}
jpa:
hibernate:
ddl-auto: validate
show-sql: false

# Configuration métier
user:
default-role: USER
password-min-length: 8
token-expiration-hours: 24

4.5 Exemple: user-service-dev.yml​

# config-repo/user-service-dev.yml
# Surcharge pour l'environnement de développement

spring:
datasource:
url: jdbc:h2:mem:users_dev
driver-class-name: org.h2.Driver
h2:
console:
enabled: true
jpa:
hibernate:
ddl-auto: create-drop
show-sql: true

logging:
level:
com.example.userservice: TRACE
org.hibernate.SQL: DEBUG

4.6 Exemple: user-service-prod.yml​

# config-repo/user-service-prod.yml
# Configuration production

spring:
datasource:
url: jdbc:postgresql://prod-db.example.com:5432/users_db
username: ${DB_USERNAME}
password: ${DB_PASSWORD}
hikari:
maximum-pool-size: 20
minimum-idle: 5
jpa:
hibernate:
ddl-auto: none
show-sql: false

logging:
level:
root: WARN
com.example: INFO

# Désactiver les endpoints sensibles
management:
endpoints:
web:
exposure:
include: health,info

5. Configuration du Config Client​

5.1 Dépendances Maven (Service)​

<dependencies>
<!-- Spring Boot Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<!-- Config Client -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>

<!-- Bootstrap (pour charger config avant app) -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>

<!-- Eureka Client -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

<!-- Actuator (pour /refresh) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>

5.2 Configuration Client (Méthode 1: bootstrap.yml)​

# src/main/resources/bootstrap.yml
# Chargé AVANT application.yml

spring:
application:
name: user-service # Doit correspondre au nom des fichiers de config
profiles:
active: dev
cloud:
config:
# URL directe du Config Server
uri: http://localhost:8888
# Credentials si Config Server sécurisé
username: config
password: config123
# Retry si Config Server non disponible
fail-fast: true
retry:
initial-interval: 1000
max-attempts: 6
max-interval: 2000
multiplier: 1.1

5.3 Configuration Client (Méthode 2: application.yml avec import)​

# src/main/resources/application.yml
# Spring Boot 2.4+ - pas besoin de bootstrap.yml

spring:
application:
name: user-service
profiles:
active: dev
config:
import: "optional:configserver:http://localhost:8888"
cloud:
config:
username: config
password: config123

5.4 Découverte via Eureka​

# Au lieu d'une URL fixe, découvrir via Eureka
spring:
cloud:
config:
discovery:
enabled: true
service-id: config-server # Nom dans Eureka
fail-fast: true

eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/

6. Accès aux Propriétés dans le Code​

6.1 Injection avec @Value​

@RestController
@RequestMapping("/api/users")
public class UserController {

@Value("${user.default-role}")
private String defaultRole;

@Value("${user.password-min-length}")
private int passwordMinLength;

@Value("${user.token-expiration-hours}")
private int tokenExpirationHours;

@GetMapping("/config")
public Map<String, Object> getConfig() {
return Map.of(
"defaultRole", defaultRole,
"passwordMinLength", passwordMinLength,
"tokenExpirationHours", tokenExpirationHours
);
}
}

6.2 Injection avec @ConfigurationProperties​

package com.example.userservice.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "user")
public class UserProperties {

private String defaultRole;
private int passwordMinLength;
private int tokenExpirationHours;

// Getters et Setters
public String getDefaultRole() { return defaultRole; }
public void setDefaultRole(String defaultRole) {
this.defaultRole = defaultRole;
}

public int getPasswordMinLength() { return passwordMinLength; }
public void setPasswordMinLength(int passwordMinLength) {
this.passwordMinLength = passwordMinLength;
}

public int getTokenExpirationHours() { return tokenExpirationHours; }
public void setTokenExpirationHours(int tokenExpirationHours) {
this.tokenExpirationHours = tokenExpirationHours;
}
}
@Service
public class UserService {

private final UserProperties userProperties;

public UserService(UserProperties userProperties) {
this.userProperties = userProperties;
}

public User createUser(UserRequest request) {
User user = new User();
user.setRole(userProperties.getDefaultRole());
// ...
return user;
}
}

7. Refresh de Configuration à Chaud​

7.1 Le Problème​

1. Modifier user-service-dev.yml dans Git
2. Commit & Push
3. Config Server voit le changement
4. MAIS: user-service a toujours l'ancienne config!
(Il l'a chargée au démarrage)

7.2 Solution 1: Endpoint /actuator/refresh​

# Exposer l'endpoint refresh
management:
endpoints:
web:
exposure:
include: health,info,refresh
# Déclencher le refresh manuellement
curl -X POST http://localhost:8081/actuator/refresh

7.3 Beans @RefreshScope​

@RestController
@RequestMapping("/api/config")
@RefreshScope // Ce bean sera recréé lors du refresh
public class ConfigController {

@Value("${user.token-expiration-hours}")
private int tokenExpirationHours;

@GetMapping("/token-expiration")
public int getTokenExpiration() {
return tokenExpirationHours;
}
}

7.4 Solution 2: Spring Cloud Bus (Propagation automatique)​

Dépendance:

<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>

Déclencher refresh global:

curl -X POST http://config-server:8888/actuator/busrefresh

8. Encryption des Secrets​

8.1 Pourquoi Encrypter?​

# ❌ DANGER: Mot de passe en clair dans Git!
spring:
datasource:
password: SuperSecret123!

8.2 Configuration Encryption​

# Config Server - application.yml
encrypt:
key: ${ENCRYPT_KEY:my-secret-encryption-key-32chars!}

Ou avec un keystore:

encrypt:
key-store:
location: classpath:/server.jks
password: keystorepassword
alias: configserver
secret: keypassword

8.3 Encrypter une Valeur​

# Encrypter
curl -X POST http://localhost:8888/encrypt -d "SuperSecret123!"
# Résultat: AQB...encodedValue...

# Décrypter (pour vérifier)
curl -X POST http://localhost:8888/decrypt -d "AQB...encodedValue..."
# Résultat: SuperSecret123!

8.4 Utiliser la Valeur Encryptée​

# config-repo/user-service-prod.yml
spring:
datasource:
password: '{cipher}AQB...encodedValue...'

Le Config Server décrypte automatiquement avant d'envoyer au client.

8.5 Encryption Asymétrique (RSA)​

# Générer un keystore
keytool -genkeypair -alias configserver -keyalg RSA \
-dname "CN=Config Server,OU=Unit,O=Organization,L=City,S=State,C=US" \
-keypass changeme -keystore server.jks -storepass changeme
encrypt:
key-store:
location: file:/etc/config-server/server.jks
password: ${KEYSTORE_PASSWORD}
alias: configserver
secret: ${KEY_PASSWORD}

9. Endpoints du Config Server​

9.1 Patterns d'URL​

/{application}/{profile}[/{label}]
/{application}-{profile}.yml
/{label}/{application}-{profile}.yml
/{application}-{profile}.properties
/{label}/{application}-{profile}.properties

9.2 Exemples​

# Configuration user-service avec profil dev
curl http://localhost:8888/user-service/dev
curl http://localhost:8888/user-service-dev.yml

# Configuration avec branche spécifique
curl http://localhost:8888/user-service/dev/feature-branch

# Configuration en format properties
curl http://localhost:8888/user-service-dev.properties

9.3 Réponse JSON​

curl http://localhost:8888/user-service/dev
{
"name": "user-service",
"profiles": ["dev"],
"label": "main",
"version": "abc123def456",
"propertySources": [
{
"name": "https://github.com/org/config-repo/user-service-dev.yml",
"source": {
"spring.datasource.url": "jdbc:h2:mem:users_dev",
"user.default-role": "USER"
}
},
{
"name": "https://github.com/org/config-repo/user-service.yml",
"source": {
"server.port": 8081
}
},
{
"name": "https://github.com/org/config-repo/application.yml",
"source": {
"eureka.client.service-url.defaultZone": "http://localhost:8761/eureka/"
}
}
]
}

10. Bonnes Pratiques​

10.1 Séparation des Environnements​

config-repo/
├── application.yml # JAMAIS de secrets ici
├── application-dev.yml # Config dev (peut avoir des valeurs par défaut)
├── application-staging.yml # Config staging
├── application-prod.yml # SEULEMENT des références à des variables d'env

10.2 Secrets en Production​

# ❌ Mauvais
spring:
datasource:
password: '{cipher}AQB...' # Même encrypté, c'est dans Git

# ✅ Bon
spring:
datasource:
password: ${DB_PASSWORD} # Variable d'environnement

10.3 Fail-Fast​

spring:
cloud:
config:
fail-fast: true # Le service ne démarre pas si Config Server indisponible
retry:
max-attempts: 6
initial-interval: 1000

10.4 Timeouts Appropriés​

spring:
cloud:
config:
request-connect-timeout: 5000
request-read-timeout: 10000

10.5 Health Check​

// Le health check inclut automatiquement le Config Server
// GET /actuator/health
{
"status": "UP",
"components": {
"configServer": {
"status": "UP",
"details": {
"propertySources": [...]
}
}
}
}

11. Résumé​

Points Clés​

✅ Config Server = Source unique de configuration
✅ Git Backend = Versioning, historique, branches
✅ Convention de nommage = {service}-\{profile\}.yml
✅ @RefreshScope = Beans qui se rechargent
✅ Encryption = Secrets sécurisés
✅ Spring Cloud Bus = Refresh automatique distribué

Ordre de Démarrage​

  1. Eureka Server (8761) - Service Discovery
  2. Config Server (8888) - Configuration
  3. Autres services - Récupèrent leur config puis s'enregistrent

Checklist​

  • Config Server configuré avec Git
  • Repository de configuration structuré
  • Clients configurés avec bootstrap.yml ou spring.config.import
  • Endpoint /refresh exposé
  • Secrets encryptés ou via variables d'environnement
  • fail-fast activé

Chapitre Suivant: API Gateway →

Retour au Module 13