Master Spring Cloud Gateway: Routing, Metrics, and Advanced Configurations
This tutorial explains how to use Spring Cloud Gateway for unified API routing, metrics collection, metadata handling, timeout settings, fluent Java route definitions, service‑discovery routing, and troubleshooting techniques in microservice architectures.
1. Introduction
Spring Cloud Gateway is a gateway in the Spring Cloud ecosystem that provides a unified API routing management for microservice architectures. It offers unified routing, powerful rule configuration, dynamic service discovery, and integrated authentication/authorization.
What will be covered
Routing metrics
Routing metadata configuration and usage
Routing timeout settings
Fluent Java API for defining routes
Service discovery based routing
Troubleshooting
2. Practical Examples
2.1 Routing Metrics
Enable metrics by adding spring.cloud.gateway.metrics.enabled: true and include spring-boot-starter-actuator . Access metrics via /actuator/metrics/{metric} , e.g., spring.cloud.gateway.requests and spring.cloud.gateway.routes.count . Metrics appear after a route has been invoked.
2.2 Routing Metadata Configuration
Metadata adds extra information to a route, accessible at runtime. Example configuration:
<code>spring:
cloud:
gateway:
routes:
- id: demo-service-01
uri: http://localhost:8088
predicates:
- name: Path
args:
a: /api-x/**
metadata:
api-key: aaaabbbbccccdddd
algorithm: SM4
padding: PKCS7Padding
mode: ECB
</code>Retrieve metadata via RoutePredicateHandlerMapping and a custom filter that reads exchange.getAttribute(GATEWAY_ROUTE_ATTR) .
<code>@Component
public class CustomGatewayFilterFactory extends AbstractGatewayFilterFactory<Config> {
@Override
public GatewayFilter apply(Config config) {
return (exchange, chain) -> {
Route r = exchange.getAttribute(GATEWAY_ROUTE_ATTR);
Map<String,Object> metadata = r.getMetadata();
System.out.println(metadata);
// example modification of query param
ServerHttpRequest request = exchange.getRequest();
URI uri = request.getURI();
String idNo = request.getQueryParams().getFirst("idNo");
idNo = idNo + "-new";
String query = "idNo=" + idNo;
URI newUri = UriComponentsBuilder.fromUri(uri).replaceQuery(query).build(true).toUri();
return chain.filter(exchange.mutate().request(request.mutate().uri(newUri).build()).build());
};
}
public static class Config {}
}
</code>Configure the filter in the route:
<code>spring:
cloud:
gateway:
default-filters:
- StripPrefix=1
routes:
- id: demo-service-01
uri: http://localhost:8088
predicates:
- name: Path
args:
a: /api-x/**
filters:
- name: Custom
</code>When the route is called, the filter prints metadata such as {mode=ECB, padding=PKCS7Padding, api-key=aaaabbbbccccdddd, algorithm=SM4} .
2.3 Routing Timeout Configuration
Global HTTP timeouts are set under spring.cloud.gateway.httpclient :
<code>spring:
cloud:
gateway:
httpclient:
connect-timeout: 3000
response-timeout: 1s
</code>If the upstream response exceeds the timeout, a 504 GATEWAY_TIMEOUT exception is thrown.
Per‑route timeouts can be defined in the route’s metadata :
<code>spring:
cloud:
gateway:
routes:
- id: demo-service-01
uri: http://localhost:8088
predicates:
- name: Path
args:
a: /api-x/**
metadata:
response-timeout: 1000
connect-timeout: 2000
</code>2.4 Fluent Java API for Defining Routes
Routes can be defined programmatically with RouteLocatorBuilder :
<code>@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
return builder.routes()
.route("rce01", spec -> spec
.path("/api-x/**")
.filters(f -> f.addRequestHeader("token", "123123").stripPrefix(1))
.metadata("connect-timeout", "2000")
.uri("http://localhost:8088"))
.build();
}
</code>2.5 Service Discovery Based Routing
Enable discovery‑based routing:
<code>spring:
cloud:
gateway:
discovery:
locator:
enabled: true
lowerCaseServiceId: true
</code>With a DiscoveryClient (e.g., Eureka or Nacos) on the classpath, routes can be accessed via /serviceId/** . The default predicates include PathRoutePredicateFactory and a RewritePathGatewayFilterFactory that removes the serviceId segment.
2.6 Troubleshooting
Increase log levels for detailed debugging:
<code>logging:
level:
web: debug
'[org.springframework.cloud.gateway]': debug
'[org.springframework.http.server.reactive]': debug
'[org.springframework.web.reactive]': debug
'[org.springframework.boot.autoconfigure.web]': debug
'[reactor.netty]': debug
'[redisratelimiter]': debug
</code>Enable wiretap for request/response inspection:
<code>spring:
cloud:
gateway:
httpserver:
wiretap: true
httpclient:
wiretap: true
</code>The article concludes with a reminder that the content aims to help readers work effectively with Spring Cloud Gateway.
Spring Full-Stack Practical Cases
Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.