gateway笔记

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/xxxhttps://example.org/blue/xxx,

Route Predicate Factories

例子

在这里插入图片描述

Cookie- Cookie=mycookie,mycookievaluecookie的名字是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,POSTThis 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/24This 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=/mypathThis 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的正则表达式。

如果响应的headerX-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 SecutirySpring 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*8uri: 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();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值