Pular para o conteúdo principal

TP13.3: Spring Cloud Gateway

🎯 Objetivos do TP​

  • Criar uma API Gateway com Spring Cloud Gateway
  • Configurar o roteamento para os serviços
  • Implementar filters personalizados
  • Configurar o rate limiting
  • Adicionar fallbacks para serviços indisponíveis

Duração estimada: 1h30


📋 Arquitetura​


Parte 1: Criar a API Gateway (20 min)​

1.1 Criar o Projeto​

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 Aplicação Principal​

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 Configuração das Rotas (YAML)​

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

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

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

# Descoberta automática (opcional)
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

Parte 2: Fallback Controller (15 min)​

2.1 Criar o 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()
));
}
}

Parte 3: Custom Logging Filter (20 min)​

3.1 Global Filter para Logar as Requisições​

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) {
// Gerar um ID de correlação
String correlationId = UUID.randomUUID().toString().substring(0, 8);
long startTime = System.currentTimeMillis();

ServerHttpRequest request = exchange.getRequest();

// Log da requisição recebida
log.info(">>> [{}] Incoming: {} {} from {}",
correlationId,
request.getMethod(),
request.getURI().getPath(),
request.getRemoteAddress()
);

// Adicionar o correlation ID ao 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; // Executado bem cedo
}
}

3.2 Filter para Adicionar Headers de Resposta​

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

Parte 4: Configuração CORS (10 min)​

4.1 Configuração 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();

// Origens permitidas
corsConfig.setAllowedOrigins(List.of(
"http://localhost:3000", // React dev
"http://localhost:4200", // Angular dev
"http://localhost:8080" // Mesma origem
));

// Métodos permitidos
corsConfig.setAllowedMethods(Arrays.asList(
"GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"
));

// Headers permitidos
corsConfig.setAllowedHeaders(List.of("*"));

// Credentials
corsConfig.setAllowCredentials(true);

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

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

return new CorsWebFilter(source);
}
}

Parte 5: Testar o Gateway (15 min)​

5.1 Ordem de Inicialização​

  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 Testar as Rotas​

# 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

# Verificar os headers de resposta
curl -i http://localhost:8080/api/users
# Deve incluir:
# X-Gateway-Version: 1.0.0
# X-Powered-By: Spring Cloud Gateway

5.3 Testar o Fallback​

# Parar User Service (Ctrl+C no terminal dele)

# Esperar 30 segundos (evicção Eureka)

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

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

5.4 Consultar as Rotas Ativas​

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

Resposta:

[
{
"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 Validação​

  • API Gateway inicia em http://localhost:8080
  • curl http://localhost:8080/api/users → resposta do User Service
  • curl http://localhost:8080/api/products → resposta do Product Service
  • Headers X-Gateway-Version e X-Powered-By presentes
  • Logs de requisições com correlation ID
  • Fallback funciona quando um serviço está fora do ar
  • /actuator/gateway/routes lista as rotas

🎯 Exercícios Bônus​

Exercício 1: Rate Limiting​

Adicione um rate limiter (necessita Redis):

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

Exercício 2: Rewrite Path​

Redirecione /v1/users/** para /api/users/**:

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

Exercício 3: Autenticação Simples​

Crie um filtro que verifica a presença de um header X-API-Key.


TP13.4: Feign + Resilience4j →

Voltar ao Módulo 13