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.发一个请求给网关,网关要将请求路由到指定的服务。路由有id,目的地uri,断言的集合,匹配了断言就能到达指定位置。
-
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.就是java里的断言函数,匹配请求里的任何信息,包括请求头等。根据请求头路由哪个服务。
-
Filter: These are instances of Spring Framework GatewayFilter that have been constructed with a specific factory. Here, you can modify requests and responses before or after sending the downstream request.过滤器请求和响应都可以被修改。
网关配置允许跨域
@Configuration
public class GuliCorsConfiguration {
@Bean
public CorsWebFilter corsWebFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.addAllowedOrigin("*");
corsConfiguration.setAllowCredentials(true);
source.registerCorsConfiguration("/**", corsConfiguration);
return new CorsWebFilter(source);
}
}
{segment}的作用
spring:
cloud:
gateway:
routes:
- id: host_route
uri: https://example.org
predicates:
- Path=/red/{segment},/blue/{segment}
访问gateway-host/red/xxx
或者gateway-host/blue/xxx
的话,这个请求会转发到https://example.org
,相当于https://example.org/red/xxx
或https://example.org/blue/xxx
,
Route Predicate Factories
例子
Cookie | - Cookie=mycookie,mycookievalue | cookie的名字是mycookie值是mycookievalue(可以是正则表达式) |
After/Before/Between | - After=2017-01-20T17:42:47.789-07:00[America/Denver] | 匹配指定时间之后/之前/之间的请求 |
Header | - Header=X-Request-Id, \d+ | 匹配header中键是X-Request-Id的值是一个或者多个数字的 |
Host | - Host=**.somehost.org,**.anotherhost.org | 匹配www.somehost.org or beta.somehost.org or www.anotherhost.org . |
Method | - Method=GET,POST | This route matches if the request method was a GET or a POST |
Path | - Path=/red/{segment},/blue/{segment} | This route matches if the request path was, for example: /red/1 or /red/1/ or /red/blue or /blue/green If matchTrailingSlash is set to false, then request path /red/1/` will not be matched. |
Query | - Query=red, gree. | 匹配查询参数,键 red 为必须的参数,值gree是可选参数可以为正则表达式 |
RemoteAddr | - RemoteAddr=192.168.1.1/24 | This route matches if the remote address of the request was, for example, 192.168.1.10 . |
Weight | - Weight=group1, 8 - Weight=group1, 2 | The weights are calculated per group. The following example configures a weight route predicate: This route would forward ~80% of traffic to weighthigh.org and ~20% of traffic to weighlow.org |
GatewayFilter Factories
AddRequestHeader | - AddRequestHeader=X-Request-red, blue | 添加请求头 X-Request-red:blue |
AddRequestParameter | - AddRequestParameter=red, blue | 添加请求参数 red=blue |
AddResponseHeader | - AddResponseHeader=X-Response-Red, Blue | ![]() |
DedupeResponseHeader | - DedupeResponseHeader= Access-Control-Allow-Credentials Access-Control-Allow-Origin | This removes duplicate values of Access-Control-Allow-Credentials and Access-Control-Allow-Origin response headers in cases when both the gateway CORS logic and the downstream logic add them.删除重复的Access-Control-Allow-Credentials Access-Control-Allow-Origin请求头 |
PrefixPath | - PrefixPath=/mypath | This will prefix /mypath to the path of all matching requests. So a request to /hello would be sent to /mypath/hello |
PreserveHostHeader | - PreserveHostHeader | 会保留原始请求的host 头信息,并原封不动的转发出去,而不是被gateway的http客户端重置。 |
RedirectTo | - RedirectTo=302, https://acme.org | 在Location中加入重定向地址 状态码需要是300类的 301 代表永久性转移 302 代表暂时性转移 |
RemoveRequestHeader / RemoveResponseHeader | - RemoveRequestHeader=X-Request-Foo -RemoveResponseHeader=X-Response-Foo | 删除X-Request-Foo请求头 / 响应头 |
RemoveRequestParameter | - RemoveRequestParameter=red | 删除请求参数red |
RewriteResponseHeader | - RewriteResponseHeader=X-Response-Foo, , password=[^&]+, password=*** | RewriteResponseHeader GatewayFilter Factory的作用是修改响应返回的header内容,需要配置响应返回的header的name ,匹配规则regexp 和替换词replacement ,也是支持java的正则表达式。如果响应的header X-Response-Foo 的内容是/42?user=ford&password=omg!what&flag=true ,这个内容会修改为/42?user=ford&password=***&flag=true 。 |
RewritePath | - RewritePath=/red/?(?<segment>.*), /$\{segment} | For a request path of /red/blue , this sets the path to /blue before making the downstream request |
SaveSession | - SaveSession | 强制执行WebSession::save 方法,如果你将Spring Secutiry 于Spring Session 集成使用,并想确保安全信息都传到下游机器,你就需要配置这个filter。 |
SetPath | ![]() | For a request path of /red/blue , this sets the path to /blue before making the downstream request. |
. | ||
StripPrefix* | ![]() | When a request is made through the gateway to /name/blue/red , the request made to nameservice looks like nameservice/red . |
**ReactiveLoadBalancerClientFilter*8 | uri: lb://service | 在注册中心中找到名字是service的服务,然后将请求负载均衡到此服务 |
编程的方式定义 Route
// static imports from GatewayFilters and RoutePredicates
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) { // ①
return builder.routes() // ②
.route(r -> r.host("**.abc.org").and().path("/image/png") // ③
.filters(f -> f.addResponseHeader("X-TestHeader", "foobar")) // ④
.uri("http://httpbin.org:80") // ⑤
)
.build();
}