Backend Development 14 min read

Spring Cloud Gateway: Overview, Usage, Configuration, and Performance

This article introduces Spring Cloud Gateway as a high‑performance, reactive API gateway for microservice architectures, explains why it is chosen, details Maven and YAML configuration, demonstrates routing predicates and filters with code examples, and evaluates its performance impact compared to alternatives.

Rare Earth Juejin Tech Community
Rare Earth Juejin Tech Community
Rare Earth Juejin Tech Community
Spring Cloud Gateway: Overview, Usage, Configuration, and Performance

Spring Cloud Gateway (Gateway) is an API gateway in the Spring ecosystem that handles HTTP requests and responses, serves as the entry point for microservice architectures, and is built on Spring Framework 5 and Spring Boot 2.x using a reactive programming model for high performance and reliability.

It is chosen for its flexible routing and filtering capabilities, seamless integration with Spring Boot, ease of use, and non‑intrusive nature.

Request routing : routes client requests to appropriate microservice instances based on URI and HTTP method.

Filters : custom filters can implement authentication, rate‑limiting, logging, etc.

Load balancing : integrates with Spring Cloud load balancer to distribute traffic.

Response transformation : can convert responses to different formats such as JSON or XML.

Failover : automatically forwards requests to backup instances when a service fails.

To use Gateway, add the Maven dependency:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>

and configure the Spring Boot Maven plugin for packaging:

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <includeSystemScope>true</includeSystemScope>
            </configuration>
            <executions>
                <execution>
                    <goals>
                        <goal>repackage</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

Gateway can be configured via YAML files (preferred) or Java beans. Example YAML routing configuration:

server:
  port: 8000
spring:
  application:
    name: xxx-gateway
  cloud:
    gateway:
      routes:
        - id: service-a
          uri: http://127.0.0.1:8080
          order: 1
          predicates:
            - Path=/a/**
          filters:
            - StripPrefix=1
        - id: service-bcd
          uri: http://127.0.0.1:8081
          predicates:
            - Path=/b/**,/c/**,/d/**

Java‑based configuration example:

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("service-a", r -> r.order(1)
                .path("/a/**")
                .filters(f -> f.stripPrefix(1))
                .uri("http://127.0.0.1:8080"))
            .route("service-bcd", r -> r.path("/b/**")
                .or().path("/c/**")
                .or().path("/d/**")
                .uri("http://127.0.0.1:8081"))
            .build();
    }
}

Route predicates include time‑based predicates (After, Before, Between) and request‑based predicates such as Cookie, Header, Host, Method, and Path, each with YAML examples.

Common route filters demonstrated are AddRequestHeader, AddRequestParameter, AddResponseHeader, PrefixPath, RedirectTo, RewritePath, StripPrefix, and Retry (with detailed retry arguments). Global filters can be applied using spring.cloud.gateway.default-filters .

SSL configuration can be set in server.ssl for HTTPS listening, and downstream HTTPS trust can be configured via spring.cloud.gateway.httpclient.ssl with either insecure trust manager (for internal networks) or specific trusted certificates.

CORS can be globally configured under spring.cloud.gateway.globalcors.cors-configurations .

A custom logging filter example shows how to record client IP, request method, path, and X‑Forwarded‑For header:

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Slf4j
public class LoggingFilter implements GlobalFilter {
    @Override
    public Mono
filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String ip = request.getRemoteAddress() != null ? request.getRemoteAddress().getAddress().getHostAddress() : "Unknown";
        log.info("Request from IP: {}, Method: {}, Path: {}", ip, request.getMethodValue(), request.getPath());
        String realIp = request.getHeaders().getFirst("X-Forwarded-For");
        log.info("X-Forwarded-For: {}", realIp);
        return chain.filter(exchange);
    }
}

The article also presents a performance comparison table showing that Spring Cloud Gateway adds about 34 % latency compared with the original service, which is lower than the 60 % overhead of Netflix Zuul.

References to several Chinese tutorials and documentation are listed at the end.

API gatewaySpring BootRoutingCORSsslSpring Cloud GatewayFilters
Rare Earth Juejin Tech Community
Written by

Rare Earth Juejin Tech Community

Juejin, a tech community that helps developers grow.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.