Skip to main content

TP13.3: Spring Cloud Gateway

🎯 Objectives of the Lab​

  • Create an API Gateway with Spring Cloud Gateway
  • Configure routing to services
  • Implement custom filters
  • Configure rate limiting
  • Add fallbacks for unavailable services

Estimated duration: 1h30


📋 Architecture​


Part 1: Create the API Gateway (20 min)​

1.1 Create the Project​

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 Main Application​

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 Route Configuration (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

# Automatic discovery (optional)
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

Part 2: Fallback Controller (15 min)​

2.1 Create the 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.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()
));
}
}

Part 3: Custom Logging Filter (20 min)​

3.1 Global Filter to Log Requests​

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) {
// Generate a correlation ID
String correlationId = UUID.randomUUID().toString().substring(0, 8);
long startTime = System.currentTimeMillis();

ServerHttpRequest request = exchange.getRequest();

// Log the incoming request
log.info(">>> [{}] Incoming: {} {} from {}",
correlationId,
request.getMethod(),
request.getURI().getPath(),
request.getRemoteAddress()
);

// Add the correlation ID to the 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; // Executed very early
}
}

3.2 Filter to Add Response Headers​

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;
}
}

Part 4: CORS Configuration (10 min)​

4.1 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();

// Allowed origins
corsConfig.setAllowedOrigins(List.of(
"http://localhost:3000", // React dev
"http://localhost:4200", // Angular dev
"http://localhost:8080" // Same origin
));

// Allowed methods
corsConfig.setAllowedMethods(Arrays.asList(
"GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"
));

// Allowed headers
corsConfig.setAllowedHeaders(List.of("*"));

// Credentials
corsConfig.setAllowCredentials(true);

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

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

return new CorsWebFilter(source);
}
}

Part 5: Test the Gateway (15 min)​

5.1 Startup Order​

  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 Test the 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

# Check response headers
curl -i http://localhost:8080/api/users
# Should include:
# X-Gateway-Version: 1.0.0
# X-Powered-By: Spring Cloud Gateway

5.3 Test the Fallback​

# Stop User Service (Ctrl+C in its terminal)

# Wait 30 seconds (Eureka eviction)

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

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

5.4 View Active Routes​

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

Response:

[
{
"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
}
]

✅ Validation Checklist​

  • API Gateway starts on http://localhost:8080
  • curl http://localhost:8080/api/users → response from User Service
  • curl http://localhost:8080/api/products → response from Product Service
  • Headers X-Gateway-Version and X-Powered-By present
  • Request logs with correlation ID
  • Fallback works when a service is down
  • /actuator/gateway/routes lists the routes

🎯 Bonus Exercises​

Exercise 1: Rate Limiting​

Add a rate limiter (requires Redis):

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

Exercise 2: Rewrite Path​

Redirect /v1/users/** to /api/users/**:

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

Exercise 3: Simple Authentication​

Create a filter that checks for the presence of an X-API-Key header.


TP13.4: Feign + Resilience4j →

Back to Module 13