Understanding Assertions and Filters in Spring Cloud Gateway (SCG)
This article provides a comprehensive overview of Spring Cloud Gateway's routing model, detailing the essential components of a route, the built‑in predicate factories, and the various gateway, default, and global filter implementations, helping developers avoid redundant work and reduce development costs.
Spring Cloud Gateway (SCG) uses routes as the fundamental unit; each route consists of predicates, filters, a target service URI, metadata, and an order for priority handling.
The RouteDefinition class illustrates these fields, including a unique id, a list of PredicateDefinition, a list of FilterDefinition, the destination uri, optional metadata, and an order value.
/**
* @author Spencer Gibb
*/
@Validated
public class RouteDefinition {
// 唯一id
private String id;
@NotEmpty
@Valid
// 断言
private List<PredicateDefinition> predicates = new ArrayList<>();
@Valid
// 过滤器
private List<FilterDefinition> filters = new ArrayList<>();
@NotNull
// 代理服务
private URI uri;
// 元数据
private Map<String, Object> metadata = new HashMap<>();
// 权重
private int order = 0;
}When configuring routes, developers often use the builder pattern, for example:
@Bean
public RouteLocator routeLocator(RouteLocatorBuilder builder) {
return builder.routes()
.route(r -> r.path("/user/**").uri("lb://user-api"))
.route(r -> r.path("/order/**").uri("lb://order-api"))
.build();
}If no explicit id, filters, or order are provided, SCG generates a UUID and defaults the order to 0; filters are optional.
SCG defines 14 built‑in predicate factories (e.g., After, Before, Between, Cookie, Header, Host, Method, Path, Query, RemoteAddr, Weight, XForwardedRemoteAddr, ReadBodyRoute, CloudFoundryRouteServiceRoute), all extending AbstractRoutePredicateFactory. Developers can inspect or extend these classes to create custom predicates.
Filters are optional components that process requests and responses. They are categorized as gateway filters (implementing GatewayFilter), default filters (configured globally via spring.cloud.gateway.default-filters), and global filters (implementing GlobalFilter and wrapped by GatewayFilterAdapter). The filter chain order is determined by the Order interface; lower values execute earlier.
Common gateway filters include AddRequestHeader, AddRequestParameter, AddResponseHeader, DedupeResponseHeader, CircuitBreaker, PrefixPath, RequestRateLimiter, RemoveRequestHeader, RemoveResponseHeader, and StripPrefix. Each serves a specific purpose such as header manipulation, rate limiting, or path rewriting.
Global filters examples are CustomGlobalFilter (a simple logging filter implementing GlobalFilter and Ordered), ForwardRoutingFilter (handles forward: scheme requests), ReactiveLoadBalancerClientFilter (performs service instance selection via a ReactorLoadBalancer), NettyRoutingFilter and NettyWriteResponseFilter (handle low‑level HTTP/HTTPS forwarding and response writing), RouteToRequestUrlFilter (combines request URL with route URI), WebsocketRoutingFilter (processes WebSocket routes), and GatewayMetricsFilter (collects performance metrics when spring-boot-starter-actuator is added).
The article emphasizes understanding the route concept—predicates, filters, target service, metadata, and order—to effectively leverage SCG's built‑in capabilities and avoid reinventing functionality.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Rare Earth Juejin Tech Community
Juejin, a tech community that helps developers grow.
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.
