Master Spring Cloud Gateway: From Setup to Advanced Routing & Filters
Spring Cloud Gateway provides a powerful, reactive API gateway for Spring Boot applications, offering dynamic routing, predicates, and a variety of filters such as rate limiting, retries, and circuit breaking, with detailed examples of configuration via YAML and Java beans, integration with Eureka, and practical code snippets.
Gateway Overview
Spring Cloud Gateway is an API gateway built on the Spring ecosystem, leveraging Spring Framework 5, Spring Boot 2, and Project Reactor. It offers simple routing, powerful filters (circuit breaker, rate limiting, retry, etc.), dynamic route matching, and integration with Spring Cloud service discovery.
Key Features
Built on Spring Framework 5, Project Reactor, and Spring Boot 2.0
Dynamic routing based on any request attribute
Configurable predicates and filters per route
Hystrix circuit breaker integration
Spring Cloud service discovery support
Easy-to-write predicates and filters
Request rate limiting
Path rewrite support
Related Concepts
Route : The basic module of the gateway, consisting of an ID, target URI, predicates, and filters. A route matches when its predicate evaluates to true.
Predicate : A Java 8 Function<ServerWebExchange, Boolean> that can match any part of an HTTP request (headers, parameters, etc.).
Filter : An instance of GatewayFilter that can modify the request before or after routing.
Creating the api-gateway Module
Add the gateway starter dependency to pom.xml:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>Configuring Routes via YAML
In application.yml:
server:
port: 9201
service-url:
user-service: http://localhost:8201
spring:
cloud:
gateway:
routes:
- id: path_route
uri: ${service-url.user-service}/user/{id}
predicates:
- Path=/user/{id}After starting Eureka, user-service, and the gateway, a request to http://localhost:9201/user/1 is routed to http://localhost:8201/user/1.
Configuring Routes via Java Bean
Create a configuration class that defines a RouteLocator bean:
@Configuration
public class GatewayConfig {
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
return builder.routes()
.route("path_route2", r -> r.path("/user/getByUsername")
.uri("http://localhost:8201/user/getByUsername"))
.build();
}
}After restarting the gateway, http://localhost:9201/user/getByUsername?username=macro is routed to the user service.
Route Predicates
Gateway predicates match specific request attributes. Common predicates include:
After
spring:
cloud:
gateway:
routes:
- id: after_route
uri: ${service-url.user-service}
predicates:
- After=2019-09-24T16:30:00+08:00[Asia/Shanghai]Before
spring:
cloud:
gateway:
routes:
- id: before_route
uri: ${service-url.user-service}
predicates:
- Before=2019-09-24T16:30:00+08:00[Asia/Shanghai]Between
spring:
cloud:
gateway:
routes:
- id: between_route
uri: ${service-url.user-service}
predicates:
- Between=2019-09-24T16:30:00+08:00[Asia/Shanghai],2019-09-25T16:30:00+08:00[Asia/Shanghai]Cookie
spring:
cloud:
gateway:
routes:
- id: cookie_route
uri: ${service-url.user-service}
predicates:
- Cookie=username,macroTest with curl http://localhost:9201/user/1 --cookie "username=macro".
Header
spring:
cloud:
gateway:
routes:
- id: header_route
uri: ${service-url.user-service}
predicates:
- Header=X-Request-Id,\d+Test with curl http://localhost:9201/user/1 -H "X-Request-Id:123".
Host
spring:
cloud:
gateway:
routes:
- id: host_route
uri: ${service-url.user-service}
predicates:
- Host=**.macrozheng.comTest with
curl http://localhost:9201/user/1 -H "Host:www.macrozheng.com".
Method
spring:
cloud:
gateway:
routes:
- id: method_route
uri: ${service-url.user-service}
predicates:
- Method=GETGET requests match; POST requests do not.
Path
spring:
cloud:
gateway:
routes:
- id: path_route
uri: ${service-url.user-service}/user/{id}
predicates:
- Path=/user/{id}Query
spring:
cloud:
gateway:
routes:
- id: query_route
uri: ${service-url.user-service}/user/getByUsername
predicates:
- Query=usernameRemoteAddr
spring:
cloud:
gateway:
routes:
- id: remoteaddr_route
uri: ${service-url.user-service}
predicates:
- RemoteAddr=192.168.1.1/24Weight
spring:
cloud:
gateway:
routes:
- id: weight_high
uri: http://localhost:8201
predicates:
- Weight=group1,8
- id: weight_low
uri: http://localhost:8202
predicates:
- Weight=group1,2Route Filters
Filters can modify requests and responses. Common built‑in filters:
AddRequestParameter
spring:
cloud:
gateway:
routes:
- id: add_request_parameter_route
uri: http://localhost:8201
filters:
- AddRequestParameter=username,macro
predicates:
- Method=GETStripPrefix
spring:
cloud:
gateway:
routes:
- id: strip_prefix_route
uri: http://localhost:8201
predicates:
- Path=/user-service/**
filters:
- StripPrefix=2PrefixPath
spring:
cloud:
gateway:
routes:
- id: prefix_path_route
uri: http://localhost:8201
predicates:
- Method=GET
filters:
- PrefixPath=/userHystrix
Add the Hystrix starter dependency and a fallback controller, then configure:
spring:
cloud:
gateway:
routes:
- id: hystrix_route
uri: http://localhost:8201
predicates:
- Method=GET
filters:
- name: Hystrix
args:
name: fallbackcmd
fallbackUri: forward:/fallbackRequestRateLimiter
Requires Redis. Define KeyResolver beans and configure the filter:
spring:
redis:
host: localhost
password: 123456
port: 6379
cloud:
gateway:
routes:
- id: requestratelimiter_route
uri: http://localhost:8201
filters:
- name: RequestRateLimiter
args:
redis-rate-limiter.replenishRate: 1
redis-rate-limiter.burstCapacity: 2
key-resolver: "#{@ipKeyResolver}"
predicates:
- Method=GETRetry
spring:
cloud:
gateway:
routes:
- id: retry_route
uri: http://localhost:8201
predicates:
- Method=GET
filters:
- name: Retry
args:
retries: 1
statuses: BAD_GATEWAY
backoff:
firstBackoff: 10ms
maxBackoff: 50ms
factor: 2
basedOnPreviousValue: falseIntegration with Service Registry (Eureka)
Add the Eureka client dependency and enable discovery‑based routing:
spring:
cloud:
gateway:
discovery:
locator:
enabled: true
lower-case-service-id: true
eureka:
client:
service-url:
defaultZone: http://localhost:8001/eureka/With this configuration, a request to http://localhost:9201/user-service/user/1 is automatically routed to the user-service instance.
Using Filters with Eureka
When routing to a service discovered via Eureka, the URI must use the lb scheme to enable load‑balancing:
spring:
cloud:
gateway:
routes:
- id: prefixpath_route
uri: lb://user-service
predicates:
- Method=GET
filters:
- PrefixPath=/userAccessing http://localhost:9201/1 is routed to http://localhost:8201/user/1.
Modules Used in the Demo Project
springcloud-learning
├── eureka-server // Eureka registration center
├── user-service // Provides CRUD APIs for User objects
└── api-gateway // Demonstrates Spring Cloud GatewaySource Code
https://github.com/macrozheng/springcloud-learning
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.
macrozheng
Dedicated to Java tech sharing and dissecting top open-source projects. Topics include Spring Boot, Spring Cloud, Docker, Kubernetes and more. Author’s GitHub project “mall” has 50K+ stars.
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.
