Chapitre 4: API Gateway avec Spring Cloud Gateway
đŻ Objectifs du Chapitreâ
- Comprendre le rĂŽle d'une API Gateway
- Configurer Spring Cloud Gateway
- Définir des routes et predicates
- Implémenter des filters (pre/post)
- Configurer le rate limiting
- Intégrer avec Eureka pour le load balancing
1. Pourquoi une API Gateway?â
1.1 Sans Gatewayâ
ProblĂšmes:
- Client doit connaĂźtre tous les services
- CORS Ă configurer sur chaque service
- Authentification dupliquée partout
- Pas de rate limiting centralisé
- Logging dispersé
- SSL à gérer partout
1.2 Avec Gatewayâ
Avantages:
- Point d'entrée unique
- Authentification centralisée
- Rate limiting
- Logging/Monitoring
- SSL termination
- Load balancing
- Transformation des requĂȘtes
2. Spring Cloud Gateway vs Zuulâ
| CritĂšre | Spring Cloud Gateway | Zuul 1.x |
|---|---|---|
| Architecture | Réactive (WebFlux) | Bloquante (Servlet) |
| Performance | Excellente | Bonne |
| Programmation | Fonctionnelle | Impérative |
| Maintenance | Active | Deprecated |
| Spring Boot 3 | â SupportĂ© | â Non supportĂ© |
Recommandation: Utilisez Spring Cloud Gateway pour les nouveaux projets.
3. Concepts ClĂ©sâ
3.1 Routeâ
Une route est la brique de base: elle dĂ©finit oĂč envoyer une requĂȘte.
spring:
cloud:
gateway:
routes:
- id: user-service-route
uri: http://localhost:8081
predicates:
- Path=/api/users/**
3.2 Predicateâ
Un predicate est une condition pour matcher une requĂȘte.
predicates:
- Path=/api/users/** # Par chemin
- Method=GET,POST # Par méthode HTTP
- Header=X-Request-Id, \d+ # Par header
- Query=name # Par query param
- Host=**.example.com # Par hostname
- After=2024-01-01T00:00:00 # Par date
3.3 Filterâ
Un filter modifie la requĂȘte ou la rĂ©ponse.
filters:
- AddRequestHeader=X-Gateway, true
- AddResponseHeader=X-Response-Time, 123
- RewritePath=/api/(?<segment>.*), /$\{segment}
- CircuitBreaker=name=myCircuitBreaker
3.4 Flux de Traitementâ
4. Configuration du Gatewayâ
4.1 Structure du Projetâ
api-gateway/
âââ pom.xml
âââ src/main/
âââ java/com/example/gateway/
â âââ ApiGatewayApplication.java
â âââ config/
â â âââ GatewayConfig.java
â â âââ SecurityConfig.java
â âââ filter/
â âââ LoggingFilter.java
âââ resources/
âââ application.yml
4.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>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>
<!-- Rate Limiter (Redis) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis-reactive</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>
4.3 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);
}
}
5. Configuration YAML des Routesâ
5.1 Routes Basiquesâ
server:
port: 8080
spring:
application:
name: api-gateway
cloud:
gateway:
routes:
# Route vers User Service
- id: user-service
uri: http://localhost:8081
predicates:
- Path=/api/users/**
# Route vers Product Service
- id: product-service
uri: http://localhost:8082
predicates:
- Path=/api/products/**
# Route vers Order Service
- id: order-service
uri: http://localhost:8083
predicates:
- Path=/api/orders/**
# Eureka
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
5.2 Routes avec Eureka (Load Balancing)â
spring:
cloud:
gateway:
routes:
- id: user-service
# lb:// = Load Balanced via Eureka
uri: lb://user-service
predicates:
- Path=/api/users/**
- id: product-service
uri: lb://product-service
predicates:
- Path=/api/products/**
- id: order-service
uri: lb://order-service
predicates:
- Path=/api/orders/**
# Découverte automatique des services
discovery:
locator:
enabled: true
lower-case-service-id: true
5.3 Routes avec Filtersâ
spring:
cloud:
gateway:
routes:
- id: user-service
uri: lb://user-service
predicates:
- Path=/api/users/**
filters:
# Ajouter des headers
- AddRequestHeader=X-Gateway-Source, api-gateway
- AddResponseHeader=X-Response-Time, ${timestamp}
# Réécrire le chemin
- RewritePath=/api/users/(?<segment>.*), /users/$\{segment}
# Retirer un préfixe
- StripPrefix=1
# Circuit Breaker
- name: CircuitBreaker
args:
name: userServiceCircuitBreaker
fallbackUri: forward:/fallback/users
6. Predicates DĂ©taillĂ©sâ
6.1 Path Predicateâ
predicates:
# Chemin exact
- Path=/api/users
# Avec wildcard simple (un segment)
- Path=/api/users/*
# Avec wildcard multiple (plusieurs segments)
- Path=/api/users/**
# Plusieurs chemins
- Path=/api/users/**,/api/accounts/**
6.2 Method Predicateâ
predicates:
- Path=/api/users/**
- Method=GET,POST,PUT,DELETE
6.3 Header Predicateâ
predicates:
- Path=/api/users/**
# Header présent avec valeur regex
- Header=X-Api-Key, ^[a-zA-Z0-9]{32}$
# Header présent (sans vérifier la valeur)
- Header=Authorization
6.4 Query Predicateâ
predicates:
- Path=/api/search
# Query param présent
- Query=q
# Query param avec valeur regex
- Query=category, ^(electronics|books|clothing)$
6.5 Host Predicateâ
predicates:
- Host=**.example.com
- Host=api.example.com,admin.example.com
6.6 DateTime Predicatesâ
predicates:
# Actif aprĂšs cette date
- After=2024-01-01T00:00:00+00:00[UTC]
# Actif avant cette date
- Before=2025-01-01T00:00:00+00:00[UTC]
# Actif entre deux dates
- Between=2024-01-01T00:00:00+00:00[UTC], 2024-12-31T23:59:59+00:00[UTC]
6.7 Weight Predicate (A/B Testing)â
routes:
- id: user-service-v1
uri: lb://user-service-v1
predicates:
- Path=/api/users/**
- Weight=group1, 8 # 80% du trafic
- id: user-service-v2
uri: lb://user-service-v2
predicates:
- Path=/api/users/**
- Weight=group1, 2 # 20% du trafic
7. Filters DĂ©taillĂ©sâ
7.1 AddRequestHeader / AddResponseHeaderâ
filters:
- AddRequestHeader=X-Request-Source, gateway
- AddResponseHeader=X-Gateway-Version, 1.0
7.2 RemoveRequestHeader / RemoveResponseHeaderâ
filters:
- RemoveRequestHeader=Cookie
- RemoveResponseHeader=X-Powered-By
7.3 RewritePathâ
filters:
# /api/users/123 â /users/123
- RewritePath=/api/(?<segment>.*), /$\{segment}
# /old-api/users â /api/v2/users
- RewritePath=/old-api/(?<segment>.*), /api/v2/$\{segment}
7.4 StripPrefix / PrefixPathâ
filters:
# /api/v1/users â /users (supprime 2 segments)
- StripPrefix=2
# /users â /api/users (ajoute prĂ©fixe)
- PrefixPath=/api
7.5 SetStatusâ
filters:
# Forcer un code de retour
- SetStatus=401
7.6 Retryâ
filters:
- name: Retry
args:
retries: 3
statuses: BAD_GATEWAY,SERVICE_UNAVAILABLE
methods: GET
backoff:
firstBackoff: 100ms
maxBackoff: 500ms
factor: 2
7.7 RequestRateLimiterâ
filters:
- name: RequestRateLimiter
args:
redis-rate-limiter.replenishRate: 10
redis-rate-limiter.burstCapacity: 20
redis-rate-limiter.requestedTokens: 1
key-resolver: "#{@userKeyResolver}"
@Bean
public KeyResolver userKeyResolver() {
return exchange -> Mono.just(
exchange.getRequest()
.getHeaders()
.getFirst("X-User-Id") != null
? exchange.getRequest().getHeaders().getFirst("X-User-Id")
: exchange.getRequest().getRemoteAddress().getAddress().getHostAddress()
);
}
8. Configuration Java (Programmatique)â
8.1 RouteLocator Beanâ
package com.example.gateway.config;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class GatewayConfig {
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
return builder.routes()
// Route User Service
.route("user-service", r -> r
.path("/api/users/**")
.filters(f -> f
.stripPrefix(1)
.addRequestHeader("X-Gateway", "true")
.circuitBreaker(c -> c
.setName("userServiceCB")
.setFallbackUri("forward:/fallback/users")
)
)
.uri("lb://user-service")
)
// Route Product Service
.route("product-service", r -> r
.path("/api/products/**")
.and()
.method("GET", "POST", "PUT", "DELETE")
.filters(f -> f
.rewritePath("/api/products/(?<segment>.*)", "/products/${segment}")
.retry(config -> config
.setRetries(3)
.setStatuses(HttpStatus.BAD_GATEWAY)
)
)
.uri("lb://product-service")
)
// Route avec Rate Limiting
.route("order-service", r -> r
.path("/api/orders/**")
.filters(f -> f
.requestRateLimiter(config -> config
.setRateLimiter(redisRateLimiter())
.setKeyResolver(userKeyResolver())
)
)
.uri("lb://order-service")
)
.build();
}
}
9. Custom Filtersâ
9.1 Global Filter (Tous les Routes)â
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) {
// PRE-FILTER: Avant d'envoyer au service
String requestId = UUID.randomUUID().toString();
long startTime = System.currentTimeMillis();
ServerHttpRequest request = exchange.getRequest().mutate()
.header("X-Request-Id", requestId)
.build();
log.info(">>> Request: {} {} | RequestId: {}",
request.getMethod(),
request.getURI().getPath(),
requestId
);
// Modifier l'exchange avec la nouvelle requĂȘte
ServerWebExchange modifiedExchange = exchange.mutate()
.request(request)
.build();
return chain.filter(modifiedExchange)
.then(Mono.fromRunnable(() -> {
// POST-FILTER: AprÚs la réponse
long duration = System.currentTimeMillis() - startTime;
log.info("<<< Response: {} | Duration: {}ms | RequestId: {}",
exchange.getResponse().getStatusCode(),
duration,
requestId
);
}));
}
@Override
public int getOrder() {
return -1; // Exécuté en premier
}
}
9.2 GatewayFilter (Route SpĂ©cifique)â
package com.example.gateway.filter;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
@Component
public class AuthenticationFilter extends AbstractGatewayFilterFactory<AuthenticationFilter.Config> {
public AuthenticationFilter() {
super(Config.class);
}
@Override
public GatewayFilter apply(Config config) {
return (exchange, chain) -> {
String authHeader = exchange.getRequest()
.getHeaders()
.getFirst("Authorization");
if (authHeader == null || !authHeader.startsWith("Bearer ")) {
exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
return exchange.getResponse().setComplete();
}
String token = authHeader.substring(7);
// Valider le token (simplificié)
if (!isValidToken(token)) {
exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
return exchange.getResponse().setComplete();
}
return chain.filter(exchange);
};
}
private boolean isValidToken(String token) {
// Implémentez votre logique de validation JWT
return token != null && token.length() > 10;
}
public static class Config {
// Configuration du filtre si nécessaire
}
}
Usage en YAML:
filters:
- Authentication
10. Fallback et Circuit Breakerâ
10.1 Configuration Fallbackâ
spring:
cloud:
gateway:
routes:
- id: user-service
uri: lb://user-service
predicates:
- Path=/api/users/**
filters:
- name: CircuitBreaker
args:
name: userServiceCB
fallbackUri: forward:/fallback/users
10.2 Fallback Controllerâ
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.util.Map;
@RestController
@RequestMapping("/fallback")
public class FallbackController {
@GetMapping("/users")
public ResponseEntity<Map<String, String>> userServiceFallback() {
return ResponseEntity
.status(HttpStatus.SERVICE_UNAVAILABLE)
.body(Map.of(
"message", "User Service is currently unavailable",
"status", "FALLBACK"
));
}
@GetMapping("/products")
public ResponseEntity<Map<String, String>> productServiceFallback() {
return ResponseEntity
.status(HttpStatus.SERVICE_UNAVAILABLE)
.body(Map.of(
"message", "Product Service is currently unavailable",
"status", "FALLBACK"
));
}
@GetMapping("/orders")
public ResponseEntity<Map<String, String>> orderServiceFallback() {
return ResponseEntity
.status(HttpStatus.SERVICE_UNAVAILABLE)
.body(Map.of(
"message", "Order Service is currently unavailable",
"status", "FALLBACK"
));
}
}
10.3 Configuration Resilience4jâ
resilience4j:
circuitbreaker:
configs:
default:
slidingWindowSize: 10
failureRateThreshold: 50
waitDurationInOpenState: 10000
permittedNumberOfCallsInHalfOpenState: 3
automaticTransitionFromOpenToHalfOpenEnabled: true
instances:
userServiceCB:
baseConfig: default
productServiceCB:
baseConfig: default
failureRateThreshold: 30
11. CORS Configurationâ
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();
corsConfig.setAllowedOrigins(List.of(
"http://localhost:3000",
"https://myapp.com"
));
corsConfig.setAllowedMethods(Arrays.asList(
"GET", "POST", "PUT", "DELETE", "OPTIONS"
));
corsConfig.setAllowedHeaders(List.of("*"));
corsConfig.setAllowCredentials(true);
corsConfig.setMaxAge(3600L);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", corsConfig);
return new CorsWebFilter(source);
}
}
Ou via YAML:
spring:
cloud:
gateway:
globalcors:
cors-configurations:
'[/**]':
allowedOrigins: "http://localhost:3000"
allowedMethods:
- GET
- POST
- PUT
- DELETE
allowedHeaders: "*"
allowCredentials: true
12. Monitoring et Actuatorâ
management:
endpoints:
web:
exposure:
include: health,info,gateway
endpoint:
gateway:
enabled: true
Endpoints Utilesâ
# Liste des routes
curl http://localhost:8080/actuator/gateway/routes
# RafraĂźchir les routes
curl -X POST http://localhost:8080/actuator/gateway/refresh
# Filtres globaux
curl http://localhost:8080/actuator/gateway/globalfilters
# Filtres de route
curl http://localhost:8080/actuator/gateway/routefilters
13. RĂ©sumĂ©â
Points ClĂ©sâ
â
API Gateway = Point d'entrée unique
â
Routes = DĂ©finissent oĂč envoyer les requĂȘtes
â
Predicates = Conditions de matching
â
Filters = Modification request/response
â
lb:// = Load Balancing via Eureka
â
CircuitBreaker = Protection contre les pannes
â
RateLimiter = Protection contre les abus
Configuration Type Productionâ
spring:
cloud:
gateway:
routes:
- id: user-service
uri: lb://user-service
predicates:
- Path=/api/users/**
filters:
- StripPrefix=1
- name: CircuitBreaker
args:
name: userServiceCB
fallbackUri: forward:/fallback/users
- name: RequestRateLimiter
args:
redis-rate-limiter.replenishRate: 100
redis-rate-limiter.burstCapacity: 200