Reference: https: //cloud.spring.io/spring-cloud-static/Greenwich.SR2/single/spring-cloud.html#_global_filters
Global Filters | effect |
---|---|
Combined Global Filter and GatewayFilter Ordering | To sort the execution order filter |
Forward Routing Filter | Forward for local, i.e. the request is forwarded within the Gateway Service, instead of forwarding to downstream services |
LoadBalancerClient Filter | Integration Ribbon load balancing |
Netty Routing Filter | Netty use of HttpClient forward http, https request |
Netty Write Response Filter | The response to the write back to the gateway proxy client side |
RouteToRequestUrl Filter | Converted from the original request in acquiring Gateway url to be used to forward the request url |
Websocket Routing Filter | Use Spring Web Socket forwards the request Websocket |
Gateway Metrics Filter | Integration of monitoring functions provide monitoring indicators |
Marking An Exchange As Routed | Prevent duplicate routing and forwarding |
Combined Global Filter and GatewayFilter Ordering
When a Gateway receives a request, Filtering Web Handler processor will all GlobalFilter instances and all the configured routing GatewayFilter instance to a filter chain. All of the filter chain according to the filter will org.springframework.core.Ordered sorted annotation number specified size.
Spring Cloud Gateway distinguishes between "pre" and "post" phase filter logic execution, so a higher priority will be executed first filter in the "pre" stage, the lowest priority of the last filter in the "post" phase carried out.
- The lower the number the more forward execution
Sample code:
@Bean
@Order(-1)
public GlobalFilter a() {
return (exchange, chain) -> {
log.info("first pre filter");
return chain.filter(exchange).then(Mono.fromRunnable(() -> {
log.info("third post filter");
}));
};
}
@Bean
@Order(0)
public GlobalFilter b() {
return (exchange, chain) -> {
log.info("second pre filter");
return chain.filter(exchange).then(Mono.fromRunnable(() -> {
log.info("second post filter");
}));
};
}
@Bean
@Order(1)
public GlobalFilter c() {
return (exchange, chain) -> {
log.info("third pre filter");
return chain.filter(exchange).then(Mono.fromRunnable(() -> {
log.info("first post filter");
}));
};
}
Return result:
first pre filter
second pre filter
third pre filter
first post filter
second post filter
third post filter
Forward Routing Filter
When a request comes in, ForwardRoutingFilter will view a URL, the URL for the exchange property ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR value, if the scheme is the url Forward (eg: forward: // localendpoint), then the Filter will be used Spirngd of DispatcherHandler to deal with this request. Part of the request URL path, the path will be overwritten in the Forward URL. But not modified the original URL, it will be appended to the ServerWebExchangeUtils.GATEWAY_ORIGINAL_REQUEST_URL_ATTR property.
PS: The so-called url scheme is simply part of the url protocol, such as http, https, ws so on. Custom scheme is typically used to identify the url of behavior, such as app developers commonly use to jump page url scheme
LoadBalancerClient Filter
The Filter is used to integrate Ribbon, the core is to parse the scheme is lb of url, in order to get the name of micro-services, and then get the actual address of the call through the Ribbon.
When a request comes in, LoadBalancerClientFilter will view a URL, the URL for the property exchange of ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR value, if the scheme is the url LB , (for example: lb: // myservice), then the Filter will use the Spring Cloud of LoadBalancerClient to the myservice resolved to actual host and port, and replace the original ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR attribute. The original will be appended to the url ServerWebExchangeUtils.GATEWAY_ORIGINAL_REQUEST_URL_ATTR property. The filter also view ServerWebExchangeUtils.GATEWAY_SCHEME_PREFIX_ATTR properties, if the value of the property is found LB , will perform the same logic.
Sample configuration:
spring:
cloud:
gateway:
routes:
- id: myRoute
uri: lb://service
predicates:
- Path=/service/**
By default, if not by LoadBalancer find the specified service instance, it will return 503 (as configured above example, if the LoadBalancer not find instance named service, it will return 503); use the configuration: spring.cloud.gateway = to true .loadbalancer.use404 , allowed to return to 404.
LoadBalancer returned ServiceInstance of isSecure value, override request scheme. For example, if the request is a hit on a Gateway using HTTPS, but ServiceInstance the isSecure is false, then the downstream micro-services is received HTTP request, and vice versa. Further, if the route is specified GATEWAY_SCHEME_PREFIX_ATTR property, the prefix will be stripped, and the URL of the routing scheme will cover ServiceInstance configuration.
Netty Routing Filter
When a request comes in, NettyRoutingFilter will see a URL, which is the exchange of property ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR value, if the scheme is the url http or HTTPS , then use the Filter Netty's HttpClient to send proxy requests to the downstream services. Obtained in response to the exchange of ServerWebExchangeUtils.CLIENT_RESPONSE_ATTR properties for later use in the Filter. (With an experimental filter: WebClientHttpRoutingFilter can perform the same function, but need Netty)
Netty Write Response Filter
NettyWriteResponseFilter for writeback gateway proxy response the client side, so that the filter will be executed after execution is completed in all the other filters, and the exchange is performed in the condition ServerWebExchangeUtils.CLIENT_RESPONSE_CONN_ATTR value of the property is not empty, the value Netty's Connection instance. (With an experimental filter: WebClientWriteResponseFilter can perform the same function, but need Netty)
RouteToRequestUrl Filter
The original request from the url filter is used in Gateway be acquired into the forwarding request url used. When a request comes in, RouteToRequestUrlFilter obtains from the exchange ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR value of the property, the value is a Route object. If the object is not empty, then, RouteToRequestUrlFilter will be based on the request URL and Route to create a new URL object in the URL. The new URL will be placed exchange of ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR property.
If the URL with prefix scheme, e.g. LB: WS: // servicelD , the LB scheme stripped from the URL, and placed ServerWebExchangeUtils.GATEWAY_SCHEME_PREFIX_ATTR , it is convenient to use a filter behind.
Websocket Routing Filter
The role of the filter NettyRoutingFilter similar. When a request comes in, WebsocketRoutingFilter will view a URL, which is the exchange ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR value of the property, if the scheme is the url ws or WSS , then the use Spring Web Socket Filter Websocket forwards the request to the downstream.
In addition, if the request needs Websocket load balancing, you can add a prefix to the URL to lb load balancing, for example lb: WS: // serviceid .
Sample configuration:
spring:
cloud:
gateway:
routes:
# SockJS route
- id: websocket_sockjs_route
uri: http://localhost:3001
predicates:
- Path=/websocket/info/**
# Normwal Websocket route
- id: websocket_route
uri: ws://localhost:3001
predicates:
- Path=/websocket/**
Gateway Metrics Filter
Want to enable Gateway Metrics Filter, to be added to the project in spring-boot-starter-actuator -dependent, then the configuration in the configuration file spring.cloud.gateway.metrics.enabled is true. The filter is added named gateway.requests timing metric (timer metric), which contains the following tags:
- routeId: Routing ID
- routeUri: API will be routed to the URI
- outcome: Sort by HttpStatus.Series
- status: Http Status returned to the client
- httpStatusCode: returned to the requesting client's Http Status
- httpMethod: Http request method used by
these indicators exposed /actuator/metrics/gateway.requests endpoint, and can be easily integrated with Prometheus to create a Grafana dashboard.
PS: Prometheus is a monitoring tool, Grafana is a visual monitoring tool; Spring Boot Actuator can be integrated with these two tools.
Marking An Exchange As Routed
Once a complete strip down request filter chain is responsible for forwarding the request to the downstream of the filter will add one to the exchange gatewayAlreadyRouted property, so that the exchange labeled as the routed (routed). Once the request is marked as the routed , other routing filter will not route the request again, but skip.
Understanding of the above all the built-in global filters, we know that the request will be forwarded by different protocols of different filters downstream. It is responsible for adding this gatewayAlreadyRouted property is ultimately responsible for forwarding filter filters requests:
- http, https requests by the NettyRoutingFilter or WebClientHttpRoutingFilter add this property
- forward requests by the ForwardRoutingFilter add this property
- websocket requests by the WebsocketRoutingFilter add this property
of these filters call a method to exchange marked the routed , or exchange is to check whether the routed :- ServerWebExchangeUtils.isAlreadyRouted: checking whether the exchange is routed state
- ServerWebExchangeUtils.setAlreadyRouted: routed to the exchange state
simply, by Gateway is gatewayAlreadyRouted represents this forwarding request has passed, without additional filters duplicate routes, thereby preventing duplicate routing forwarding attributes.
These filters have a corresponding global configuration class, interested can view the source code:
- org.springframework.cloud.gateway.config.GatewayAutoConfiguration
- org.springframework.cloud.gateway.config.GatewayMetricsAutoConfiguration
- org.springframework.cloud.gateway.config.GatewayLoadBalancerClientAutoConfiguration