文章目录
Spring Cloud Gateway介绍
废话不多说,看官方文档的介绍
This project provides an API Gateway built on top of the Spring Ecosystem, including: Spring 5, Spring Boot 2 and Project Reactor. Spring Cloud Gateway aims to provide a simple, yet effective way to route to APIs and provide cross cutting concerns to them such as: security, monitoring/metrics, and resiliency.
有道翻译一下:
这个项目提供了一个建在Spring生态系统之上的API网关,包括:Spring 5, Spring Boot 2和project Reactor。Spring Cloud Gateway旨在提供一种简单而有效的方式来路由到api,并为它们提供交叉关注,例如:安全性、监视/度量和弹性。
工作原理如下:
Gateway实际上提供了一个在路由上的控制功能,大体包含两个大功能:
- Route
- Filter
- Forward
我们可以通过Route去匹配请求的uri,而每个Router下可以配置一个Filter Chain,我们可以通过Filter去修饰请求和响应及一些类似鉴权等中间动作,通过Forward可以控制重定向和请求转发(实际上Filter也可以做到,只不过这里分开说清晰一点)。在路由控制上,Gateway表现的非常灵活,它有两种配置方式:
- Yml or Properties File
- Code
主要名词如下:
- Route: 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 aggregate predicate is true.
- Predicate: This is a Java 8 Function Predicate. The input type is a Spring Framework ServerWebExchange. This allows developers to match on anything from the HTTP request, such as headers or parameters.
- Filter: These are instances Spring Framework GatewayFilter constructed in with a specific factory. Here, requests and responses can be modified before or after sending the downstream request.
Route 作为Gateway中的基本元素,它有自己的ID、URI和一个Predicate集合、Filter集合。Predicate的作用是判断请求的Uri是否匹配当前的Route,Filter则是匹配通过之后对请求和响应的处理及修饰,那么在Gateway中Route基本结构如下
Gateway{
Route1 {
String id;
String path;
List<Predicate> predicates;
List<Filter> filters;
};
Route2 {
String id;
String path;
List<Predicate> predicates;
List<Filter> filters;
};
...
...
}
Route中的ID作为它的唯一标识,path的作用是正则匹配请求路径,Predicate则是在path匹配的情况下进一步去更加细致的匹配请求路径,如一下例子:
spring:
cloud:
gateway:
routes:
- id: before_route
uri: http://example.org
predicates:
- Before=2017-01-20T17:42:47.789-07:00[America/Denver]
只匹配在Jan 20, 2017 17:42
发起的请求
spring:
cloud:
gateway:
routes:
- id: cookie_route
uri: http://example.org
predicates:
- Cookie=chocolate, “”
只匹配请求中携带chocolate
且值为ch.p
的请求
更多例子这里就不一一展开,有兴趣的可以去看下官方文档: 传送门