Video in progress
What are a route, a predicate and a filter in Spring Cloud Gateway? Show how to configure a simple route.
A route is a "which request goes where" rule: it consists of an ID, a destination (uri), predicates and filters. A predicate checks whether a request matches the route (path, header, method), and a filter changes the request or response along the way.
📖 Answer
spring:
cloud:
gateway:
routes:
- id: orders
uri: lb://order-service
predicates:
- Path=/api/orders/**
- Method=GET,POST
filters:
- StripPrefix=1
- AddRequestHeader=X-Gateway, main
Here:
Path=/api/orders/**: only requests that come in on this path;StripPrefix=1:/api/orders/12reaches the service as/orders/12;lb://: the address is found through discovery, with Spring Cloud LoadBalancer. In Kubernetes you often just writehttp://order-service:8080.
The order of routes matters: the first match wins. If a more general /api/** comes before /api/orders/**, orders go to the wrong place. If needed, set the order explicitly with the order field.
The Java DSL version is more convenient for dynamic rules:
@Bean
RouteLocator routes(RouteLocatorBuilder b) {
return b.routes()
.route("orders", r -> r.path("/api/orders/**")
.filters(f -> f.stripPrefix(1))
.uri("lb://order-service"))
.build();
}
Mind the version: since Spring Cloud 2025.0 (Gateway 4.3) the property prefix changed to spring.cloud.gateway.server.webflux.*, and the old spring.cloud.gateway.* is deprecated. You can see which routes were loaded and how through /actuator/gateway/routes, which is the first place to look for "why is the request getting a 404".
Sign up to mark studied questions and save your progress.