Careeroza
Routes and Predicates
Routes in application.yml
A route has an id, a destination uri, predicates (conditions to match) and optional filters. lb:// means "look the name up in the registry and load-balance":
api-gateway application.yml
application.yml
server:
port: 8080
spring:
application:
name: api-gateway
cloud:
gateway:
routes:
- id: product-service
uri: lb://product-service
predicates:
- Path=/api/products/**,/api/categories/**
- id: order-service
uri: lb://order-service
predicates:
- Path=/api/orders/**
- id: user-service
uri: lb://user-service
predicates:
- Path=/api/users/**,/api/cart/**
- id: payment-service
uri: lb://payment-service
predicates:
- Path=/api/payments/**
- Method=GET,POST
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/Example output
$ curl localhost:8080/api/products/7
HTTP/1.1 200 OK
{"id":7,"name":"boAt Rockerz 450","price":1499.00,"stock":120,"category":"Audio"}
$ curl localhost:8080/api/orders/1001
HTTP/1.1 200 OK
{"orderId":1001,"status":"CREATED","total":2998.00}
$ curl localhost:8080/api/unknown
HTTP/1.1 404 Not FoundCommon Predicates
| Predicate | Matches when | Example |
|---|---|---|
Path | URL path matches a pattern | Path=/api/orders/** |
Method | HTTP method | Method=GET,POST |
Header | Header matches a regex | Header=X-Client, android|ios |
Query | Query parameter present / matches | Query=version, v2 |
Host | Host header | Host=**.shopease.in |
After / Before / Between | Time window | Open a sale route at a fixed time |
Weight | Split traffic by percentage | 90% v1, 10% v2 (canary) |
Routes in Java
The same routes can be built with the Java DSL. Handy when routes need logic or are generated:
@Configuration
class GatewayRoutes {
@Bean
RouteLocator shopEaseRoutes(RouteLocatorBuilder builder) {
return builder.routes()
.route("product-service", r -> r
.path("/api/products/**", "/api/categories/**")
.uri("lb://product-service"))
.route("order-service-v2-canary", r -> r
.path("/api/orders/**")
.and().weight("orders", 10) // 10% of order traffic
.uri("lb://order-service-v2"))
.route("order-service", r -> r
.path("/api/orders/**")
.and().weight("orders", 90) // 90% of order traffic
.uri("lb://order-service"))
.build();
}
}Example
Check what the gateway loaded (needs management.endpoints.web.exposure.include: gateway):
curl -s localhost:8080/actuator/gateway/routes | jq ".[].route_id"Example output
"product-service" "order-service-v2-canary" "order-service" "user-service" "payment-service"