Spring Cloud Gateway (一)
Spring Cloud Gateway 核心配置
- Route: The basic building block of the gateway. It is defined by an ID, a destination URI, a collection of predicates, and a collection of filters. A route is matched if the aggregate predicate is true.
- Predicate: This is a Java 8 Function Predicate. The input type is a Spring Framework ServerWebExchange. This lets you match on anything from the HTTP request, such as headers or parameters.
- Filter: These are instances of GatewayFilter that have been constructed with a specific factory. Here, you can modify requests and responses before or after sending the downstream request.
Spring Cloud Gateway 配置运行
例子展示以上几个核心配置
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
</dependencies>
@SpringBootApplication
public class MainApplication {
public static void main(String[] args) {
SpringApplication.run(MainApplication.class, args);
}
}
# application.yml
spring:
cloud:
gateway:
routes:
- id: header_route
uri: https://docs.spring.io/
predicates:
- Header=X-Request-Id, \d+
filters:
- StripPrefix=1
以上基本配置用到了 route, predicate, filter
当后台解析匹配到地址 http://localhost:8080/this_is_filter_path/spring-cloud-gateway/docs/current/reference/html/#glossary
请求头包含 X-Request-Id=数字
,且请求地址排除域名后第一层路径 /this_is_filter_path
如下图展示的demo正常结果 将会重定向到 https://docs.spring.io/spring-cloud-gateway/docs/current/reference/html/
# application.yml spring.cloud.gateway.routes.predicates
predicates:
- Header=X-Request-Id, \d+
此处默认匹配到的断言器
org.springframework.cloud.gateway.handler.predicate.HeaderRoutePredicateFactory
# application.yml spring.cloud.gateway.routes.filters
filters:
- StripPrefix=1
此处默认匹配到的过滤器
org.springframework.cloud.gateway.filter.factory.StripPrefixGatewayFilterFactory
Spring Cloud Gateway 提供了很多内置的断言器及过滤器
Spring Cloud Gateway 官网罗列了几个特征:
- Built on Spring Framework 5, Project Reactor and Spring Boot 2.0
- Able to match routes on any request attribute.
- Predicates and filters are specific to routes.
- Circuit Breaker integration.
- Spring Cloud DiscoveryClient integration
- Easy to write Predicates and Filters
- Request Rate Limiting
- Path Rewriting
Spring Cloud Gateway 工作流程
Clients make requests to Spring Cloud Gateway. If the Gateway Handler Mapping determines that a request matches a route
, it is sent to the Gateway Web Handler
. This handler runs the request through a filter chain
that is specific to the request. The reason the filters are divided by the dotted line is that filters can run logic both before and after the proxy request
is sent. All “pre” filter logic is executed. Then the proxy request is made. After the proxy request is made, the “post” filter logic is run.