Aller au contenu principal

TP13.3: Spring Cloud Gateway

🎯 Objectifs du TP​

  • CrĂ©er une API Gateway avec Spring Cloud Gateway
  • Configurer le routing vers les services
  • ImplĂ©menter des filters personnalisĂ©s
  • Configurer le rate limiting
  • Ajouter des fallbacks pour les services indisponibles

Durée estimée: 1h30


📋 Architecture​


Partie 1: CrĂ©er l'API Gateway (20 min)​

1.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>api-gateway</artifactId>
<version>1.0.0</version>

<properties>
<java.version>17</java.version>
<spring-cloud.version>2023.0.0</spring-cloud.version>
</properties>

<dependencies>
<!-- Spring Cloud Gateway -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>

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

<!-- Circuit Breaker -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-circuitbreaker-reactor-resilience4j</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>

1.2 Application Principale​

package com.example.gateway;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ApiGatewayApplication {

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

1.3 Configuration des Routes (YAML)​

# src/main/resources/application.yml
server:
port: 8080

spring:
application:
name: api-gateway
cloud:
gateway:
routes:
# Route User Service
- id: user-service
uri: lb://user-service
predicates:
- Path=/api/users/**
filters:
- name: CircuitBreaker
args:
name: userServiceCB
fallbackUri: forward:/fallback/users

# Route Product Service
- id: product-service
uri: lb://product-service
predicates:
- Path=/api/products/**
filters:
- name: CircuitBreaker
args:
name: productServiceCB
fallbackUri: forward:/fallback/products

# Découverte automatique (optionnel)
discovery:
locator:
enabled: true
lower-case-service-id: true

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

# Actuator
management:
endpoints:
web:
exposure:
include: health,info,gateway
endpoint:
gateway:
enabled: true

# Resilience4j
resilience4j:
circuitbreaker:
instances:
userServiceCB:
slidingWindowSize: 10
failureRateThreshold: 50
waitDurationInOpenState: 10000
permittedNumberOfCallsInHalfOpenState: 3
productServiceCB:
slidingWindowSize: 10
failureRateThreshold: 50
waitDurationInOpenState: 10000

# Logging
logging:
level:
org.springframework.cloud.gateway: DEBUG

Partie 2: Fallback Controller (15 min)​

2.1 CrĂ©er le Controller de Fallback​

package com.example.gateway.controller;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.Map;

@RestController
@RequestMapping("/fallback")
public class FallbackController {

@GetMapping("/users")
public ResponseEntity<Map<String, Object>> userServiceFallback() {
return ResponseEntity
.status(HttpStatus.SERVICE_UNAVAILABLE)
.body(Map.of(
"status", "SERVICE_UNAVAILABLE",
"message", "User Service is currently unavailable. Please try again later.",
"timestamp", LocalDateTime.now().toString(),
"service", "user-service"
));
}

@GetMapping("/products")
public ResponseEntity<Map<String, Object>> productServiceFallback() {
return ResponseEntity
.status(HttpStatus.SERVICE_UNAVAILABLE)
.body(Map.of(
"status", "SERVICE_UNAVAILABLE",
"message", "Product Service is currently unavailable. Please try again later.",
"timestamp", LocalDateTime.now().toString(),
"service", "product-service"
));
}

@GetMapping("/default")
public ResponseEntity<Map<String, Object>> defaultFallback() {
return ResponseEntity
.status(HttpStatus.SERVICE_UNAVAILABLE)
.body(Map.of(
"status", "SERVICE_UNAVAILABLE",
"message", "Service temporarily unavailable",
"timestamp", LocalDateTime.now().toString()
));
}
}

Partie 3: Custom Logging Filter (20 min)​

3.1 Global Filter pour Logger les RequĂȘtes​

package com.example.gateway.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.UUID;

@Component
public class LoggingFilter implements GlobalFilter, Ordered {

private static final Logger log = LoggerFactory.getLogger(LoggingFilter.class);

@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
// Générer un ID de corrélation
String correlationId = UUID.randomUUID().toString().substring(0, 8);
long startTime = System.currentTimeMillis();

ServerHttpRequest request = exchange.getRequest();

// Log la requĂȘte entrante
log.info(">>> [{}] Incoming: {} {} from {}",
correlationId,
request.getMethod(),
request.getURI().getPath(),
request.getRemoteAddress()
);

// Ajouter le correlation ID au header
ServerHttpRequest mutatedRequest = request.mutate()
.header("X-Correlation-Id", correlationId)
.build();

ServerWebExchange mutatedExchange = exchange.mutate()
.request(mutatedRequest)
.build();

return chain.filter(mutatedExchange)
.then(Mono.fromRunnable(() -> {
long duration = System.currentTimeMillis() - startTime;
log.info("<<< [{}] Response: {} | Duration: {}ms",
correlationId,
exchange.getResponse().getStatusCode(),
duration
);
}));
}

@Override
public int getOrder() {
return -100; // Exécuté trÚs tÎt
}
}

3.2 Filter pour Ajouter des Headers de RĂ©ponse​

package com.example.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class ResponseHeaderFilter implements GlobalFilter, Ordered {

@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
return chain.filter(exchange)
.then(Mono.fromRunnable(() -> {
ServerHttpResponse response = exchange.getResponse();
response.getHeaders().add("X-Gateway-Version", "1.0.0");
response.getHeaders().add("X-Powered-By", "Spring Cloud Gateway");
}));
}

@Override
public int getOrder() {
return -1;
}
}

Partie 4: CORS Configuration (10 min)​

4.1 Configuration CORS​

package com.example.gateway.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

import java.util.Arrays;
import java.util.List;

@Configuration
public class CorsConfig {

@Bean
public CorsWebFilter corsWebFilter() {
CorsConfiguration corsConfig = new CorsConfiguration();

// Origines autorisées
corsConfig.setAllowedOrigins(List.of(
"http://localhost:3000", // React dev
"http://localhost:4200", // Angular dev
"http://localhost:8080" // Same origin
));

// Méthodes autorisées
corsConfig.setAllowedMethods(Arrays.asList(
"GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"
));

// Headers autorisés
corsConfig.setAllowedHeaders(List.of("*"));

// Credentials
corsConfig.setAllowCredentials(true);

// Cache preflight
corsConfig.setMaxAge(3600L);

UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", corsConfig);

return new CorsWebFilter(source);
}
}

Partie 5: Tester le Gateway (15 min)​

5.1 Ordre de DĂ©marrage​

  1. Eureka Server (8761)
  2. User Service (8081)
  3. Product Service (8083)
  4. API Gateway (8080)
# Terminal 1
cd eureka-server && mvn spring-boot:run

# Terminal 2
cd user-service && mvn spring-boot:run

# Terminal 3
cd product-service && mvn spring-boot:run

# Terminal 4
cd api-gateway && mvn spring-boot:run

5.2 Tester les Routes​

# Via Gateway - Users
curl http://localhost:8080/api/users
curl http://localhost:8080/api/users/1

# Via Gateway - Products
curl http://localhost:8080/api/products
curl http://localhost:8080/api/products/1

# Vérifier les headers de réponse
curl -i http://localhost:8080/api/users
# Devrait inclure:
# X-Gateway-Version: 1.0.0
# X-Powered-By: Spring Cloud Gateway

5.3 Tester le Fallback​

# ArrĂȘter User Service (Ctrl+C dans son terminal)

# Attendre 30 secondes (éviction Eureka)

# Tester via Gateway
curl http://localhost:8080/api/users

# Résultat attendu:
{
"status": "SERVICE_UNAVAILABLE",
"message": "User Service is currently unavailable. Please try again later.",
"timestamp": "2024-01-15T10:30:00",
"service": "user-service"
}

5.4 Consulter les Routes Actives​

curl http://localhost:8080/actuator/gateway/routes

Réponse:

[
{
"predicate": "Paths: [/api/users/**], match trailing slash: true",
"route_id": "user-service",
"filters": ["CircuitBreaker name='userServiceCB' fallback='forward:/fallback/users'"],
"uri": "lb://user-service",
"order": 0
},
{
"predicate": "Paths: [/api/products/**], match trailing slash: true",
"route_id": "product-service",
"filters": ["CircuitBreaker name='productServiceCB' fallback='forward:/fallback/products'"],
"uri": "lb://product-service",
"order": 0
}
]

✅ Checklist de Validation​

  • API Gateway dĂ©marre sur http://localhost:8080
  • curl http://localhost:8080/api/users → rĂ©ponse de User Service
  • curl http://localhost:8080/api/products → rĂ©ponse de Product Service
  • Headers X-Gateway-Version et X-Powered-By prĂ©sents
  • Logs de requĂȘtes avec correlation ID
  • Fallback fonctionne quand un service est down
  • /actuator/gateway/routes liste les routes

🎯 Exercices Bonus​

Exercice 1: Rate Limiting​

Ajoutez un rate limiter (nécessite Redis):

filters:
- name: RequestRateLimiter
args:
redis-rate-limiter.replenishRate: 10
redis-rate-limiter.burstCapacity: 20

Exercice 2: Rewrite Path​

Redirigez /v1/users/** vers /api/users/**:

- id: user-service-v1
uri: lb://user-service
predicates:
- Path=/v1/users/**
filters:
- RewritePath=/v1/(?<segment>.*), /api/$\{segment}

Exercice 3: Authentification Simple​

Créez un filtre qui vérifie la présence d'un header X-API-Key.


TP13.4: Feign + Resilience4j →

Retour au Module 13