Master Spring Cloud Gateway: Build Routes, Predicates, and Custom Filters
Learn how to set up Spring Cloud Gateway, configure routes, predicates, and filters—including custom global filters and time-based predicates—while testing load balancing, weight distribution, and request handling in a microservices environment effectively.
Gateway Setup
Spring Cloud Gateway is the preferred gateway for microservice architectures due to its performance, flexibility, ease of use, and community support. This guide shows how to create a Gateway project, add dependencies, and start the service.
<spring-cloud.version>Greenwich.SR5</spring-cloud.version>
<spring-cloud-alibaba.version>2.1.2.RELEASE</spring-cloud-alibaba.version> <dependencies>
<!--Gateway-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>The three essential elements of a Gateway configuration are routes , predicates , and filters .
Route (route)
Routes determine which backend service a request is forwarded to, enabling dynamic request distribution and load balancing.
spring:
cloud:
gateway:
## routes
routes:
## id (unique)
- id: gateway-service-01
uri: http://localhost:8011
- id: gateway-service-02
uri: http://localhost:8012Multiple routes can be defined under routes. To decide which route is chosen, predicates are used.
Predicate (Predicate)
Predicates are conditional checks that control to which route a request is forwarded. Spring Cloud Gateway provides many built‑in predicates such as Path, Method, and Header.
Example of a path‑based predicate:
spring:
cloud:
gateway:
routes:
- id: gateway-service-01
uri: http://localhost:8011
predicates:
- Path=/api/orderService/**
- id: gateway-service-02
uri: http://localhost:8012
predicates:
- Path=/api/userService/**Predicates can be combined; they are evaluated with logical AND. Weight predicates enable traffic splitting:
spring:
cloud:
gateway:
routes:
- id: gateway-service-01
uri: http://localhost:8011
predicates:
- Path=/api/orderService/**
- id: gateway-service-02
uri: http://localhost:8012
predicates:
- Path=/api/userService/**
- Weight=userGroup,6
- id: gateway-service-03
uri: http://localhost:8013
predicates:
- Path=/api/userService/**
- Weight=userGroup,4The above configuration routes roughly 60 % of traffic to service 02 and 40 % to service 03.
Custom Predicate
A custom time‑based predicate can be created by extending AbstractRoutePredicateFactory :
/**
* Custom predicate that matches requests after a specified hour.
*/
@Component
public class MyHourRoutePredicateFactory extends AbstractRoutePredicateFactory<MyHourRoutePredicateFactory.MyConfig> {
public MyHourRoutePredicateFactory() {
super(MyHourRoutePredicateFactory.MyConfig.class);
}
@Override
public Predicate<ServerWebExchange> apply(MyConfig config) {
return exchange -> {
int hour = LocalDateTime.now().getHour();
return hour >= config.getMyHour();
};
}
@Override
public List<String> shortcutFieldOrder() {
return Arrays.asList("myHour");
}
@Data
@NoArgsConstructor
public static class MyConfig {
private int myHour;
}
}Use it in the route configuration:
spring:
cloud:
gateway:
routes:
- id: gateway-service-01
uri: http://localhost:8011
predicates:
- Path=/api/orderService/**
- MyHour=16If the current hour is before 16, the request is rejected; after 16 it is allowed.
Filter (filter)
Filters manipulate requests or responses. Spring Cloud Gateway provides over 30 built‑in filters (e.g., AddRequestHeader , RequestRateLimiter ). Example of a local filter that adds a response header:
spring:
cloud:
gateway:
routes:
- id: gateway-service-01
uri: http://localhost:8011
predicates:
- Path=/api/orderService/**
- MyHour=15
filters:
- AddResponseHeader=myKey,myValGlobal filters apply to all routes via the default-filters section:
server:
port: 8010
spring:
cloud:
gateway:
routes:
- id: gateway-service-01
uri: http://localhost:8011
predicates:
- Path=/api/orderService/**
- MyHour=15
- id: gateway-service-02
uri: http://localhost:8012
predicates:
- Path=/api/userService/**
- Weight=userGroup,6
- id: gateway-service-03
uri: http://localhost:8013
predicates:
- Path=/api/userService/**
- Weight=userGroup,4
default-filters:
- AddResponseHeader=myKey,myValCustom global filters are created by implementing GlobalFilter :
/** Global authentication filter */
@Component
@Order(-1)
public class MyGatewayFilter implements GlobalFilter {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
MultiValueMap<String, String> params = exchange.getRequest().getQueryParams();
String userName = params.getFirst("name");
if ("root".equals(userName)) {
return chain.filter(exchange);
}
exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
return exchange.getResponse().setComplete();
}
}The execution order is: default filters → local (route) filters → global filters. The order can be set via the Order annotation or by implementing the Ordered interface. Testing the gateway involves starting the gateway, an order service, and two user services, then accessing URLs such as http://localhost:8010/api/orderService/test and http://localhost:8010/api/userService/test . Weight‑based routing can be verified by repeatedly calling the user service endpoint and observing the distribution of responses.
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.
Xuanwu Backend Tech Stack
Primarily covers fundamental Java concepts, mainstream frameworks, deep dives into underlying principles, and JVM internals.
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.
