Rozmowa kwalifikacyjna Spring Cloud Gateway: Routing, Filtry i Load Balancing

Opanuj Spring Cloud Gateway na rozmowy techniczne: 12 pytań o routing, filtry, load balancing i wzorce API Gateway z przykładami kodu.

Spring Cloud Gateway: pytania rekrutacyjne o routing, filtry i load balancing

Spring Cloud Gateway to wzorcowe rozwiązanie do implementacji API Gateway w architekturze mikroserwisów Spring. Rozmowy techniczne sprawdzają umiejętność konfiguracji routingu, tworzenia własnych filtrów oraz skutecznego zarządzania load balancingiem.

Wskazówka przygotowawcza

Rekruterzy weryfikują znajomość wzorców Gateway: scentralizowanej autentykacji, rate limitingu i circuit breakera. Umiejętność uzasadnienia wyboru Spring Cloud Gateway zamiast alternatyw robi różnicę.

Architektura i podstawy Spring Cloud Gateway

Pytanie 1: Czym jest Spring Cloud Gateway i dlaczego z niego korzystać?

Spring Cloud Gateway to reaktywny API Gateway zbudowany na Spring WebFlux i Project Reactor. Pełni rolę pojedynczego punktu wejścia dla wszystkich żądań do mikroserwisów, oferując routing, filtrację i load balancing.

GatewayApplication.javajava
// Podstawowa konfiguracja Spring Cloud Gateway
@SpringBootApplication
public class GatewayApplication {

    public static void main(String[] args) {
        // Uruchamia reaktywny serwer Netty (nie Tomcat)
        SpringApplication.run(GatewayApplication.class, args);
    }
}
yaml
# application.yml
# Minimalna konfiguracja gateway
spring:
  cloud:
    gateway:
      routes:
        # Trasa do serwisu użytkowników
        - id: user-service
          uri: http://localhost:8081
          predicates:
            - Path=/api/users/**
        # Trasa do serwisu zamówień
        - id: order-service
          uri: http://localhost:8082
          predicates:
            - Path=/api/orders/**

Główne zalety Spring Cloud Gateway: nieblokująca architektura zapewniająca wysoką wydajność, natywna integracja z ekosystemem Spring Cloud oraz wsparcie dla nowoczesnych wzorców reaktywnych.

Pytanie 2: Wyjaśnij pojęcia Route, Predicate i Filter

Trzy podstawowe koncepcje strukturyzują Spring Cloud Gateway: Routes definiują cele, Predicates określają, kiedy zastosować trasę, a Filters modyfikują żądania i odpowiedzi.

RouteConfiguration.javajava
// Programowa konfiguracja tras
@Configuration
public class RouteConfiguration {

    @Bean
    public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
        return builder.routes()
            // Trasa z wieloma predykatami
            .route("product-service", r -> r
                // Predykat: ścieżka URL
                .path("/api/products/**")
                // Predykat: metoda HTTP
                .and()
                .method(HttpMethod.GET, HttpMethod.POST)
                // Predykat: obecność nagłówka
                .and()
                .header("X-Api-Version", "v2")
                // Filtr: przepisanie ścieżki
                .filters(f -> f
                    .rewritePath("/api/products/(?<segment>.*)", "/products/${segment}")
                    // Filtr: dodanie nagłówka
                    .addRequestHeader("X-Gateway-Source", "spring-cloud-gateway")
                )
                // Docelowy URI
                .uri("http://localhost:8083"))
            .build();
    }
}

Przepływ przetwarzania przebiega w następującej kolejności:

text
Przychodzące żądanie
┌─────────────────┐
│   Predicates    │ → Sprawdza warunki (ścieżka, metoda, nagłówek...)
└────────┬────────┘
         │ Trafienie znalezione
┌─────────────────┐
│  Pre-Filters    │ → Modyfikuje żądanie przed routingiem
└────────┬────────┘
┌─────────────────┐
│   HTTP Proxy    │ → Przekazuje do docelowego serwisu
└────────┬────────┘
┌─────────────────┐
│  Post-Filters   │ → Modyfikuje odpowiedź przed zwróceniem klientowi
└────────┬────────┘
   Odpowiedź do klienta

Pytanie 3: Jakie są najczęściej używane predykaty?

Spring Cloud Gateway dostarcza wiele wbudowanych predykatów do różnych warunków routingu. Łączenie kilku predykatów pozwala tworzyć zaawansowane reguły routingu.

yaml
# application.yml
# Przykłady popularnych predykatów
spring:
  cloud:
    gateway:
      routes:
        # Routing po ścieżce z przechwyceniem zmiennej
        - id: user-details
          uri: http://user-service
          predicates:
            - Path=/users/{userId}

        # Routing po metodzie HTTP
        - id: user-create
          uri: http://user-service
          predicates:
            - Path=/users
            - Method=POST

        # Routing po nagłówkach
        - id: mobile-api
          uri: http://mobile-service
          predicates:
            - Header=X-Client-Type, mobile

        # Routing po parametrach query
        - id: search-api
          uri: http://search-service
          predicates:
            - Query=q

        # Routing po hoście
        - id: admin-portal
          uri: http://admin-service
          predicates:
            - Host=admin.example.com

        # Routing czasowy
        - id: maintenance-mode
          uri: http://maintenance-service
          predicates:
            - Between=2026-03-20T02:00:00Z,2026-03-20T04:00:00Z
CustomPredicateFactory.javajava
// Tworzenie własnego predykatu
@Component
public class ApiKeyRoutePredicateFactory
    extends AbstractRoutePredicateFactory<ApiKeyRoutePredicateFactory.Config> {

    public ApiKeyRoutePredicateFactory() {
        super(Config.class);
    }

    @Override
    public Predicate<ServerWebExchange> apply(Config config) {
        return exchange -> {
            // Sprawdza obecność i poprawność klucza API
            String apiKey = exchange.getRequest()
                .getHeaders()
                .getFirst("X-Api-Key");

            return apiKey != null && config.getValidKeys().contains(apiKey);
        };
    }

    @Validated
    public static class Config {
        private List<String> validKeys = new ArrayList<>();

        public List<String> getValidKeys() {
            return validKeys;
        }

        public void setValidKeys(List<String> validKeys) {
            this.validKeys = validKeys;
        }
    }
}
Kolejność predykatów

Kolejność predykatów nie wpływa na ich ewaluację, ale kolejność tras ma znaczenie. Trasy są oceniane sekwencyjnie i używana jest pierwsza pasująca.

Filtry i transformacja żądań

Pytanie 4: Jak działają filtry pre- i post-procesowe?

Filtry GatewayFilter wykonywane są w uporządkowanym łańcuchu. Filtry „pre" modyfikują żądanie przed routingiem, filtry „post" modyfikują odpowiedź po otrzymaniu jej z serwisu docelowego.

LoggingFilter.javajava
// Globalny filtr logowania
@Component
@Slf4j
public class LoggingFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // PRE-FILTER: przed routingiem
        String requestId = UUID.randomUUID().toString();
        long startTime = System.currentTimeMillis();

        log.info("Request {} started: {} {}",
            requestId,
            exchange.getRequest().getMethod(),
            exchange.getRequest().getPath());

        // Dodaje ID żądania do nagłówków
        ServerHttpRequest modifiedRequest = exchange.getRequest()
            .mutate()
            .header("X-Request-Id", requestId)
            .build();

        // Kontynuuje łańcuch i obsługuje odpowiedź
        return chain.filter(exchange.mutate().request(modifiedRequest).build())
            .then(Mono.fromRunnable(() -> {
                // POST-FILTER: po odpowiedzi
                long duration = System.currentTimeMillis() - startTime;
                HttpStatusCode status = exchange.getResponse().getStatusCode();

                log.info("Request {} completed: status={}, duration={}ms",
                    requestId, status, duration);
            }));
    }

    @Override
    public int getOrder() {
        // Ujemna kolejność = wykonywany pierwszy
        return -1;
    }
}
AuthenticationFilter.javajava
// Filtr autentykacji JWT
@Component
@RequiredArgsConstructor
public class AuthenticationFilter implements GatewayFilter {

    private final JwtTokenValidator tokenValidator;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String authHeader = exchange.getRequest()
            .getHeaders()
            .getFirst(HttpHeaders.AUTHORIZATION);

        // Sprawdza obecność tokenu
        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
            return handleUnauthorized(exchange, "Missing or invalid Authorization header");
        }

        String token = authHeader.substring(7);

        // Waliduje token reaktywnie
        return tokenValidator.validate(token)
            .flatMap(claims -> {
                // Wzbogaca żądanie o informacje o użytkowniku
                ServerHttpRequest enrichedRequest = exchange.getRequest()
                    .mutate()
                    .header("X-User-Id", claims.getSubject())
                    .header("X-User-Roles", String.join(",", claims.getRoles()))
                    .build();

                return chain.filter(exchange.mutate().request(enrichedRequest).build());
            })
            .onErrorResume(e -> handleUnauthorized(exchange, e.getMessage()));
    }

    private Mono<Void> handleUnauthorized(ServerWebExchange exchange, String message) {
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        exchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_JSON);

        String body = String.format("{\"error\": \"%s\"}", message);
        DataBuffer buffer = exchange.getResponse()
            .bufferFactory()
            .wrap(body.getBytes(StandardCharsets.UTF_8));

        return exchange.getResponse().writeWith(Mono.just(buffer));
    }
}

Pytanie 5: Jakie są najbardziej użyteczne wbudowane filtry?

Spring Cloud Gateway dostarcza wiele wbudowanych filtrów obsługujących typowe przypadki: przepisywanie URL, modyfikacja nagłówków, retry oraz circuit breaker.

yaml
# application.yml
# Popularne wbudowane filtry
spring:
  cloud:
    gateway:
      routes:
        - id: order-service
          uri: lb://order-service
          predicates:
            - Path=/api/orders/**
          filters:
            # Przepisanie ścieżki
            - RewritePath=/api/orders/(?<segment>.*), /orders/${segment}

            # Dodanie nagłówków żądania
            - AddRequestHeader=X-Gateway-Version, 1.0

            # Usunięcie wrażliwych nagłówków odpowiedzi
            - RemoveResponseHeader=X-Powered-By
            - RemoveResponseHeader=Server

            # Prefiks ścieżki
            - PrefixPath=/v2

            # Usunięcie prefiksu
            - StripPrefix=1

            # Automatyczny retry przy błędach
            - name: Retry
              args:
                retries: 3
                statuses: BAD_GATEWAY,SERVICE_UNAVAILABLE
                methods: GET
                backoff:
                  firstBackoff: 100ms
                  maxBackoff: 500ms
                  factor: 2

            # Limit szybkości
            - name: RequestRateLimiter
              args:
                redis-rate-limiter.replenishRate: 10
                redis-rate-limiter.burstCapacity: 20
                key-resolver: "#{@userKeyResolver}"
RateLimiterConfiguration.javajava
// Konfiguracja rate limitera per użytkownik
@Configuration
public class RateLimiterConfiguration {

    @Bean
    public KeyResolver userKeyResolver() {
        // Limit dla uwierzytelnionego użytkownika
        return exchange -> Mono.just(
            exchange.getRequest()
                .getHeaders()
                .getFirst("X-User-Id")
        ).defaultIfEmpty("anonymous");
    }

    @Bean
    public KeyResolver ipKeyResolver() {
        // Limit per adres IP
        return exchange -> Mono.just(
            Objects.requireNonNull(exchange.getRequest()
                .getRemoteAddress())
                .getAddress()
                .getHostAddress()
        );
    }
}

Gotowy na rozmowy o Spring Boot?

Ćwicz z naszymi interaktywnymi symulatorami, flashcards i testami technicznymi.

Pytanie 6: Jak zaimplementować filtr modyfikujący body?

Modyfikacja ciała żądania lub odpowiedzi wymaga specyficznego podejścia z ModifyRequestBodyGatewayFilterFactory lub ModifyResponseBodyGatewayFilterFactory.

RequestBodyModificationFilter.javajava
// Filtr modyfikujący body żądania
@Component
@RequiredArgsConstructor
public class RequestBodyModificationFilter implements GlobalFilter, Ordered {

    private final ObjectMapper objectMapper;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // Modyfikuje tylko żądania POST/PUT z JSON
        if (!isJsonRequest(exchange)) {
            return chain.filter(exchange);
        }

        return DataBufferUtils.join(exchange.getRequest().getBody())
            .flatMap(dataBuffer -> {
                byte[] bytes = new byte[dataBuffer.readableByteCount()];
                dataBuffer.read(bytes);
                DataBufferUtils.release(dataBuffer);

                try {
                    // Parsuje i modyfikuje JSON
                    Map<String, Object> body = objectMapper.readValue(
                        bytes,
                        new TypeReference<Map<String, Object>>() {}
                    );

                    // Dodaje metadane
                    body.put("processedAt", Instant.now().toString());
                    body.put("gatewayVersion", "1.0");

                    byte[] modifiedBytes = objectMapper.writeValueAsBytes(body);

                    // Tworzy nowe żądanie ze zmodyfikowanym body
                    ServerHttpRequest modifiedRequest = new ServerHttpRequestDecorator(
                        exchange.getRequest()
                    ) {
                        @Override
                        public Flux<DataBuffer> getBody() {
                            return Flux.just(
                                exchange.getResponse()
                                    .bufferFactory()
                                    .wrap(modifiedBytes)
                            );
                        }

                        @Override
                        public HttpHeaders getHeaders() {
                            HttpHeaders headers = new HttpHeaders();
                            headers.putAll(super.getHeaders());
                            headers.setContentLength(modifiedBytes.length);
                            return headers;
                        }
                    };

                    return chain.filter(exchange.mutate().request(modifiedRequest).build());

                } catch (IOException e) {
                    return Mono.error(new RuntimeException("Failed to parse request body", e));
                }
            });
    }

    private boolean isJsonRequest(ServerWebExchange exchange) {
        MediaType contentType = exchange.getRequest().getHeaders().getContentType();
        return contentType != null &&
               contentType.isCompatibleWith(MediaType.APPLICATION_JSON);
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
ResponseBodyModificationConfig.javajava
// Konfiguracja modyfikacji odpowiedzi
@Configuration
public class ResponseBodyModificationConfig {

    @Bean
    public RouteLocator responseModifyingRoutes(
        RouteLocatorBuilder builder,
        ModifyResponseBodyGatewayFilterFactory modifyResponseBodyFilter
    ) {
        return builder.routes()
            .route("modify-response", r -> r
                .path("/api/users/**")
                .filters(f -> f.modifyResponseBody(
                    String.class,
                    String.class,
                    MediaType.APPLICATION_JSON_VALUE,
                    (exchange, responseBody) -> {
                        // Pakuje odpowiedź w standardowy format
                        return Mono.just(String.format(
                            "{\"success\": true, \"data\": %s, \"timestamp\": \"%s\"}",
                            responseBody,
                            Instant.now()
                        ));
                    }
                ))
                .uri("lb://user-service"))
            .build();
    }
}

Load Balancing i odporność

Pytanie 7: Jak skonfigurować load balancing ze Spring Cloud LoadBalancer?

Spring Cloud Gateway integruje się ze Spring Cloud LoadBalancer w celu rozdzielania ruchu pomiędzy instancjami serwisów. Schemat URI lb:// aktywuje automatyczny load balancing.

yaml
# application.yml
# Konfiguracja load balancingu
spring:
  cloud:
    gateway:
      routes:
        - id: user-service
          # lb:// aktywuje load balancing
          uri: lb://user-service
          predicates:
            - Path=/api/users/**

    # Konfiguracja load balancera
    loadbalancer:
      ribbon:
        enabled: false  # Używa Spring Cloud LoadBalancer (nie Ribbon)

      # Konfiguracja per serwis
      configurations: default

      # Health check dla load balancingu
      health-check:
        path:
          user-service: /actuator/health
        interval: 10s

# Service discovery (Eureka lub inne)
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
LoadBalancerConfiguration.javajava
// Niestandardowa konfiguracja load balancera
@Configuration
@LoadBalancerClients(defaultConfiguration = CustomLoadBalancerConfig.class)
public class LoadBalancerConfiguration {
}

// CustomLoadBalancerConfig.java
// Niestandardowa strategia load balancingu
public class CustomLoadBalancerConfig {

    @Bean
    public ReactorLoadBalancer<ServiceInstance> loadBalancer(
        Environment environment,
        LoadBalancerClientFactory clientFactory
    ) {
        String serviceId = environment.getProperty(
            LoadBalancerClientFactory.PROPERTY_NAME
        );

        // Domyślnie Round Robin
        return new RoundRobinLoadBalancer(
            clientFactory.getLazyProvider(serviceId, ServiceInstanceListSupplier.class),
            serviceId
        );
    }

    @Bean
    public ServiceInstanceListSupplier serviceInstanceListSupplier(
        ConfigurableApplicationContext context
    ) {
        // Dodaje health check do instancji
        return ServiceInstanceListSupplier.builder()
            .withDiscoveryClient()
            .withHealthChecks()
            .withCaching()
            .build(context);
    }
}
WeightedLoadBalancer.javajava
// Ważony load balancer
@Component
@RequiredArgsConstructor
public class WeightedLoadBalancer implements ReactorServiceInstanceLoadBalancer {

    private final String serviceId;
    private final ObjectProvider<ServiceInstanceListSupplier> supplierProvider;
    private final Random random = new Random();

    @Override
    public Mono<Response<ServiceInstance>> choose(Request request) {
        return supplierProvider.getIfAvailable()
            .get()
            .next()
            .map(instances -> {
                if (instances.isEmpty()) {
                    return new EmptyResponse();
                }

                // Oblicza wagi na podstawie metadanych
                List<WeightedInstance> weighted = instances.stream()
                    .map(instance -> {
                        int weight = Integer.parseInt(
                            instance.getMetadata().getOrDefault("weight", "1")
                        );
                        return new WeightedInstance(instance, weight);
                    })
                    .toList();

                // Wybór ważony
                int totalWeight = weighted.stream()
                    .mapToInt(WeightedInstance::weight)
                    .sum();

                int randomWeight = random.nextInt(totalWeight);
                int currentWeight = 0;

                for (WeightedInstance wi : weighted) {
                    currentWeight += wi.weight();
                    if (randomWeight < currentWeight) {
                        return new DefaultResponse(wi.instance());
                    }
                }

                return new DefaultResponse(weighted.get(0).instance());
            });
    }

    private record WeightedInstance(ServiceInstance instance, int weight) {}
}

Pytanie 8: Jak zaimplementować circuit breaker w gateway?

Circuit breaker chroni przed kaskadowymi awariami. Spring Cloud Gateway integruje się z Resilience4j w celu zaawansowanego zarządzania awariami.

yaml
# application.yml
# Konfiguracja circuit breakera Resilience4j
spring:
  cloud:
    gateway:
      routes:
        - id: order-service
          uri: lb://order-service
          predicates:
            - Path=/api/orders/**
          filters:
            # Circuit breaker z fallbackiem
            - name: CircuitBreaker
              args:
                name: orderServiceCB
                fallbackUri: forward:/fallback/orders

resilience4j:
  circuitbreaker:
    configs:
      default:
        # Liczba ocenianych żądań
        slidingWindowSize: 10
        # Próg awarii do otwarcia obwodu
        failureRateThreshold: 50
        # Czas otwartego obwodu przed kolejną próbą
        waitDurationInOpenState: 30s
        # Dozwolone żądania w stanie half-open
        permittedNumberOfCallsInHalfOpenState: 3
        # Automatyczne przejścia
        automaticTransitionFromOpenToHalfOpenEnabled: true

    instances:
      orderServiceCB:
        baseConfig: default
        failureRateThreshold: 60

  timelimiter:
    configs:
      default:
        timeoutDuration: 5s

    instances:
      orderServiceCB:
        timeoutDuration: 3s
FallbackController.javajava
// Kontroler fallbacku
@RestController
@RequestMapping("/fallback")
@Slf4j
public class FallbackController {

    @GetMapping("/orders")
    public Mono<ResponseEntity<Map<String, Object>>> ordersFallback(
        ServerWebExchange exchange
    ) {
        log.warn("Circuit breaker activated for orders service");

        Map<String, Object> response = Map.of(
            "success", false,
            "error", "Service temporarily unavailable",
            "code", "SERVICE_UNAVAILABLE",
            "retryAfter", 30
        );

        return Mono.just(ResponseEntity
            .status(HttpStatus.SERVICE_UNAVAILABLE)
            .body(response));
    }

    @PostMapping("/orders")
    public Mono<ResponseEntity<Map<String, Object>>> ordersPostFallback() {
        Map<String, Object> response = Map.of(
            "success", false,
            "error", "Order creation temporarily unavailable",
            "code", "SERVICE_UNAVAILABLE",
            "message", "Please try again later"
        );

        return Mono.just(ResponseEntity
            .status(HttpStatus.SERVICE_UNAVAILABLE)
            .body(response));
    }
}
CircuitBreakerEventListener.javajava
// Monitoring zdarzeń circuit breakera
@Component
@Slf4j
@RequiredArgsConstructor
public class CircuitBreakerEventListener {

    private final MeterRegistry meterRegistry;

    @EventListener
    public void onCircuitBreakerStateTransition(
        CircuitBreakerOnStateTransitionEvent event
    ) {
        CircuitBreaker.StateTransition transition = event.getStateTransition();

        log.info("Circuit breaker {} state changed: {} -> {}",
            event.getCircuitBreakerName(),
            transition.getFromState(),
            transition.getToState());

        // Metryka Micrometer
        meterRegistry.counter(
            "circuit_breaker.state_transition",
            "name", event.getCircuitBreakerName(),
            "from", transition.getFromState().name(),
            "to", transition.getToState().name()
        ).increment();
    }

    @EventListener
    public void onCircuitBreakerFailure(CircuitBreakerOnErrorEvent event) {
        log.error("Circuit breaker {} error: {}",
            event.getCircuitBreakerName(),
            event.getThrowable().getMessage());
    }
}
Timeout i circuit breaker

Skonfiguruj spójny timeout pomiędzy circuit breakerem a klientem HTTP. Zbyt długi timeout blokuje wątki, a zbyt krótki powoduje fałszywe alarmy.

Pytanie 9: Jak zaimplementować retry z wykładniczym backoffem?

Inteligentny retry z wykładniczym backoffem zapobiega przeciążeniu serwisu w trudnościach, jednocześnie maksymalizując szanse powodzenia.

yaml
# application.yml
# Konfiguracja retry z backoffem
spring:
  cloud:
    gateway:
      routes:
        - id: payment-service
          uri: lb://payment-service
          predicates:
            - Path=/api/payments/**
          filters:
            - name: Retry
              args:
                # Liczba prób
                retries: 3
                # Kody HTTP wyzwalające retry
                statuses: BAD_GATEWAY,SERVICE_UNAVAILABLE,GATEWAY_TIMEOUT
                # Tylko idempotentne metody HTTP
                methods: GET,PUT
                # Wyjątki wyzwalające retry
                exceptions:
                  - java.io.IOException
                  - java.net.ConnectException
                  - org.springframework.cloud.gateway.support.TimeoutException
                # Wykładniczy backoff
                backoff:
                  firstBackoff: 100ms
                  maxBackoff: 2000ms
                  factor: 2
                  basedOnPreviousValue: true
CustomRetryFilter.javajava
// Niestandardowy retry z logiką biznesową
@Component
@Slf4j
public class CustomRetryFilter implements GatewayFilter, Ordered {

    private static final int MAX_RETRIES = 3;
    private static final Duration INITIAL_BACKOFF = Duration.ofMillis(100);
    private static final double BACKOFF_MULTIPLIER = 2.0;
    private static final double JITTER_FACTOR = 0.1;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        return Mono.defer(() -> attemptRequest(exchange, chain, 0));
    }

    private Mono<Void> attemptRequest(
        ServerWebExchange exchange,
        GatewayFilterChain chain,
        int attempt
    ) {
        return chain.filter(exchange)
            .onErrorResume(throwable -> {
                if (attempt >= MAX_RETRIES || !isRetryable(throwable, exchange)) {
                    return Mono.error(throwable);
                }

                Duration backoff = calculateBackoff(attempt);
                log.warn("Retry attempt {} after {}ms for {} {}",
                    attempt + 1,
                    backoff.toMillis(),
                    exchange.getRequest().getMethod(),
                    exchange.getRequest().getPath());

                return Mono.delay(backoff)
                    .then(Mono.defer(() ->
                        attemptRequest(exchange, chain, attempt + 1)
                    ));
            });
    }

    private boolean isRetryable(Throwable throwable, ServerWebExchange exchange) {
        // Powtarza tylko metody idempotentne
        HttpMethod method = exchange.getRequest().getMethod();
        if (!Set.of(HttpMethod.GET, HttpMethod.PUT, HttpMethod.DELETE)
            .contains(method)) {
            return false;
        }

        // Sprawdza typ wyjątku
        return throwable instanceof ConnectException ||
               throwable instanceof TimeoutException ||
               throwable instanceof ServiceUnavailableException;
    }

    private Duration calculateBackoff(int attempt) {
        // Wykładniczy backoff z jitterem
        long baseBackoff = (long) (
            INITIAL_BACKOFF.toMillis() * Math.pow(BACKOFF_MULTIPLIER, attempt)
        );

        // Dodaje losowy jitter (±10%)
        double jitter = 1.0 + (Math.random() - 0.5) * 2 * JITTER_FACTOR;
        long finalBackoff = (long) (baseBackoff * jitter);

        return Duration.ofMillis(finalBackoff);
    }

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

Zaawansowane wzorce i dobre praktyki

Pytanie 10: Jak zaimplementować agregację żądań?

Agregacja łączy kilka wywołań mikroserwisów w jedną odpowiedź dla klienta, redukując opóźnienie i złożoność po stronie frontendu.

AggregationController.javajava
// Agregacja wieloserwisowa
@RestController
@RequestMapping("/api/aggregate")
@RequiredArgsConstructor
@Slf4j
public class AggregationController {

    private final WebClient.Builder webClientBuilder;
    private final CircuitBreakerRegistry circuitBreakerRegistry;

    @GetMapping("/user-dashboard/{userId}")
    public Mono<DashboardResponse> getUserDashboard(@PathVariable Long userId) {
        // Równoległe wywołania do różnych serwisów
        Mono<UserProfile> userMono = fetchUserProfile(userId);
        Mono<List<Order>> ordersMono = fetchRecentOrders(userId);
        Mono<NotificationCount> notificationsMono = fetchNotificationCount(userId);

        // Agregacja wyników
        return Mono.zip(userMono, ordersMono, notificationsMono)
            .map(tuple -> DashboardResponse.builder()
                .user(tuple.getT1())
                .recentOrders(tuple.getT2())
                .notificationCount(tuple.getT3())
                .generatedAt(Instant.now())
                .build())
            .timeout(Duration.ofSeconds(5))
            .onErrorResume(this::handleAggregationError);
    }

    private Mono<UserProfile> fetchUserProfile(Long userId) {
        return webClientBuilder.build()
            .get()
            .uri("lb://user-service/users/{id}", userId)
            .retrieve()
            .bodyToMono(UserProfile.class)
            .transform(CircuitBreakerOperator.of(
                circuitBreakerRegistry.circuitBreaker("user-service")
            ))
            .onErrorReturn(new UserProfile(userId, "Unknown", null));
    }

    private Mono<List<Order>> fetchRecentOrders(Long userId) {
        return webClientBuilder.build()
            .get()
            .uri("lb://order-service/orders?userId={id}&limit=5", userId)
            .retrieve()
            .bodyToFlux(Order.class)
            .collectList()
            .transform(CircuitBreakerOperator.of(
                circuitBreakerRegistry.circuitBreaker("order-service")
            ))
            .onErrorReturn(Collections.emptyList());
    }

    private Mono<NotificationCount> fetchNotificationCount(Long userId) {
        return webClientBuilder.build()
            .get()
            .uri("lb://notification-service/notifications/count/{id}", userId)
            .retrieve()
            .bodyToMono(NotificationCount.class)
            .transform(CircuitBreakerOperator.of(
                circuitBreakerRegistry.circuitBreaker("notification-service")
            ))
            .onErrorReturn(new NotificationCount(0, 0));
    }

    private Mono<DashboardResponse> handleAggregationError(Throwable error) {
        log.error("Dashboard aggregation failed: {}", error.getMessage());
        return Mono.just(DashboardResponse.builder()
            .error("Partial data available")
            .generatedAt(Instant.now())
            .build());
    }
}
DashboardResponse.javajava
// DTO odpowiedzi zagregowanej
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class DashboardResponse {
    private UserProfile user;
    private List<Order> recentOrders;
    private NotificationCount notificationCount;
    private Instant generatedAt;
    private String error;
}

Pytanie 11: Jak zabezpieczyć gateway za pomocą OAuth2?

Integracja OAuth2 centralizuje uwierzytelnianie na poziomie gateway, eliminując duplikację logiki w każdym mikroserwisie.

yaml
# application.yml
# Konfiguracja OAuth2 Resource Server
spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: https://auth.example.com/realms/myrealm
          jwk-set-uri: https://auth.example.com/realms/myrealm/protocol/openid-connect/certs
SecurityConfig.javajava
// Konfiguracja bezpieczeństwa gateway
@Configuration
@EnableWebFluxSecurity
public class SecurityConfig {

    @Bean
    public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) {
        return http
            // Wyłącza CSRF dla bezstanowego API
            .csrf(ServerHttpSecurity.CsrfSpec::disable)

            // Konfiguracja autoryzacji
            .authorizeExchange(exchanges -> exchanges
                // Endpointy publiczne
                .pathMatchers("/actuator/health", "/actuator/info").permitAll()
                .pathMatchers("/api/public/**").permitAll()
                .pathMatchers("/api/auth/**").permitAll()

                // Endpointy specyficzne dla ról
                .pathMatchers("/api/admin/**").hasRole("ADMIN")
                .pathMatchers(HttpMethod.DELETE, "/api/**").hasRole("ADMIN")

                // Reszta wymaga uwierzytelnienia
                .anyExchange().authenticated()
            )

            // OAuth2 Resource Server z JWT
            .oauth2ResourceServer(oauth2 -> oauth2
                .jwt(jwt -> jwt
                    .jwtAuthenticationConverter(jwtAuthenticationConverter())
                )
            )

            .build();
    }

    @Bean
    public ReactiveJwtAuthenticationConverter jwtAuthenticationConverter() {
        JwtGrantedAuthoritiesConverter grantedAuthoritiesConverter =
            new JwtGrantedAuthoritiesConverter();
        // Pobiera role z claimu "roles"
        grantedAuthoritiesConverter.setAuthoritiesClaimName("roles");
        grantedAuthoritiesConverter.setAuthorityPrefix("ROLE_");

        ReactiveJwtAuthenticationConverter converter =
            new ReactiveJwtAuthenticationConverter();
        converter.setJwtGrantedAuthoritiesConverter(
            new ReactiveJwtGrantedAuthoritiesConverterAdapter(grantedAuthoritiesConverter)
        );

        return converter;
    }
}
TokenRelayFilter.javajava
// Przekazywanie tokenu do serwisów downstream
@Component
public class TokenRelayFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        return ReactiveSecurityContextHolder.getContext()
            .map(SecurityContext::getAuthentication)
            .filter(auth -> auth instanceof JwtAuthenticationToken)
            .cast(JwtAuthenticationToken.class)
            .map(JwtAuthenticationToken::getToken)
            .map(jwt -> {
                // Przekazuje token do serwisów downstream
                ServerHttpRequest request = exchange.getRequest()
                    .mutate()
                    .header(HttpHeaders.AUTHORIZATION, "Bearer " + jwt.getTokenValue())
                    // Dodaje informacje użytkownika wyciągnięte z tokenu
                    .header("X-User-Id", jwt.getSubject())
                    .header("X-User-Email", jwt.getClaimAsString("email"))
                    .build();

                return exchange.mutate().request(request).build();
            })
            .defaultIfEmpty(exchange)
            .flatMap(chain::filter);
    }

    @Override
    public int getOrder() {
        // Po uwierzytelnieniu, przed routingiem
        return SecurityWebFiltersOrder.AUTHENTICATION.getOrder() + 1;
    }
}

Gotowy na rozmowy o Spring Boot?

Ćwicz z naszymi interaktywnymi symulatorami, flashcards i testami technicznymi.

Pytanie 12: Jakie są dobre praktyki monitoringu i obserwowalności?

Monitoring gateway jest kluczowy dla wykrywania problemów wydajności i dostępności w architekturze mikroserwisów.

yaml
# application.yml
# Konfiguracja obserwowalności
management:
  endpoints:
    web:
      exposure:
        include: health,info,metrics,prometheus,gateway
  metrics:
    tags:
      application: api-gateway
    distribution:
      percentiles-histogram:
        http.server.requests: true
      percentiles:
        http.server.requests: 0.5, 0.95, 0.99
  tracing:
    sampling:
      probability: 1.0

spring:
  cloud:
    gateway:
      metrics:
        enabled: true
        tags:
          path:
            enabled: true
MetricsFilter.javajava
// Filtr niestandardowych metryk
@Component
@RequiredArgsConstructor
@Slf4j
public class MetricsFilter implements GlobalFilter, Ordered {

    private final MeterRegistry meterRegistry;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        long startTime = System.nanoTime();
        String path = exchange.getRequest().getPath().value();
        String method = exchange.getRequest().getMethod().name();

        // Pobiera serwis docelowy z trasy
        Route route = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);
        String routeId = route != null ? route.getId() : "unknown";

        return chain.filter(exchange)
            .doOnSuccess(v -> recordMetrics(exchange, startTime, routeId, "success"))
            .doOnError(e -> recordMetrics(exchange, startTime, routeId, "error"));
    }

    private void recordMetrics(
        ServerWebExchange exchange,
        long startTime,
        String routeId,
        String outcome
    ) {
        long duration = System.nanoTime() - startTime;
        HttpStatusCode status = exchange.getResponse().getStatusCode();
        String statusCode = status != null ? String.valueOf(status.value()) : "0";

        // Timer opóźnienia
        Timer.builder("gateway.request.duration")
            .tag("route", routeId)
            .tag("method", exchange.getRequest().getMethod().name())
            .tag("status", statusCode)
            .tag("outcome", outcome)
            .register(meterRegistry)
            .record(duration, TimeUnit.NANOSECONDS);

        // Licznik żądań
        meterRegistry.counter(
            "gateway.requests.total",
            "route", routeId,
            "status", statusCode
        ).increment();

        // Logowanie wolnych żądań
        if (duration > TimeUnit.SECONDS.toNanos(1)) {
            log.warn("Slow request: {} {} - {}ms (route: {})",
                exchange.getRequest().getMethod(),
                exchange.getRequest().getPath(),
                TimeUnit.NANOSECONDS.toMillis(duration),
                routeId);
        }
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
TracingFilter.javajava
// Propagacja kontekstu tracingu
@Component
@RequiredArgsConstructor
public class TracingFilter implements GlobalFilter, Ordered {

    private final Tracer tracer;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // Tworzy lub pobiera span tracingu
        Span span = tracer.nextSpan()
            .name("gateway-request")
            .tag("http.method", exchange.getRequest().getMethod().name())
            .tag("http.url", exchange.getRequest().getURI().toString())
            .start();

        // Wstrzykuje nagłówki tracingu
        ServerHttpRequest request = exchange.getRequest()
            .mutate()
            .header("X-Trace-Id", span.context().traceId())
            .header("X-Span-Id", span.context().spanId())
            .build();

        return chain.filter(exchange.mutate().request(request).build())
            .doOnSuccess(v -> {
                HttpStatusCode status = exchange.getResponse().getStatusCode();
                span.tag("http.status_code",
                    status != null ? String.valueOf(status.value()) : "0");
                span.end();
            })
            .doOnError(e -> {
                span.tag("error", e.getMessage());
                span.end();
            });
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE + 1;
    }
}

Tabela kluczowych metryk:

text
| Metryka                           | Opis                             |
|-----------------------------------|----------------------------------|
| gateway.request.duration          | Opóźnienie per trasa/status      |
| gateway.requests.total            | Licznik żądań                    |
| resilience4j.circuitbreaker.state | Stany circuit breakera           |
| http.server.requests              | Standardowe metryki HTTP         |
| spring.cloud.gateway.routes       | Aktywne trasy                    |
Rekomendowane dashboardy

Użyj Grafany z dashboardami Spring Cloud Gateway i Resilience4j do wizualizacji metryk. Skonfiguruj alerty na opóźnieniu P99 i wskaźniku błędów.

Podsumowanie

Spring Cloud Gateway to kluczowy element nowoczesnych architektur mikroserwisów. Kluczowe punkty do zapamiętania na rozmowy:

Architektura i koncepcje:

  • ✅ Routes, Predicates i Filters tworzą model bazowy
  • ✅ Reaktywna architektura z WebFlux i Netty
  • ✅ Natywna integracja z ekosystemem Spring Cloud

Kluczowe funkcjonalności:

  • ✅ Dynamiczny routing oparty na wielu kryteriach
  • ✅ Filtry pre/post do transformacji żądań i odpowiedzi
  • ✅ Load balancing ze Spring Cloud LoadBalancer

Odporność i bezpieczeństwo:

  • ✅ Circuit breaker z Resilience4j i fallbackiem
  • ✅ Retry z wykładniczym backoffem i jitterem
  • ✅ Scentralizowane uwierzytelnianie OAuth2/JWT

Obserwowalność:

  • ✅ Metryki Micrometer z tagami per trasa
  • ✅ Rozproszony tracing z propagacją kontekstu
  • ✅ Health checks i endpointy actuator

Opanowanie Spring Cloud Gateway świadczy o głębokim zrozumieniu wzorców mikroserwisów i wyzwań skalowalności. Te kompetencje są niezbędne do projektowania solidnych i wydajnych API Gateway.

Zacznij ćwiczyć!

Sprawdź swoją wiedzę z naszymi symulatorami rozmów i testami technicznymi.

Tagi

#spring cloud gateway
#microservices
#api gateway
#routing
#technical interview

Udostępnij

Powiązane artykuły