网关gateway路由以及过滤器

一、路由

1、两种配置用法

1、快捷配置

spring:
  cloud:
    gateway:
      routes:
      - id: hwk-test-microservice
        uri: https://sougou.com/
        predicates:
          - Cookie=mycookie,mycookievalue
          - Path=/hwk-test-microservice/**
        filters:
          - StripPrefix=1

2、展开式配置

spring:
  cloud:
    gateway:
      routes:
      - id: hwk-test-microservice
        uri: https://sougou.com/
        predicates:
          - Path=/hwk-test-microservice/**
          - name: Cookie
	        args:
	          name: mycookie
	          regexp: mycookievalue
        filters:
          - StripPrefix=1
     

2、路由断言

1、After

在配置时间之后的请求会路由

spring:
  cloud:
    gateway:
      routes:
      - id: hwk-test-microservice
        uri: http://www.baidu.com
        predicates:
          - After=2019-09-15T20:58:18.786182+08:00[Asia/Shanghai]
          - Path=/hwk-test-microservice/**
        filters:
          - StripPrefix=1
    

2、Before

在配置时间之前的请求会路由

spring:
  cloud:
    gateway:
      routes:
      - id: hwk-test-microservice
        uri: http://www.baidu.com
        predicates:
          - Before=2019-09-15T20:58:18.786182+08:00[Asia/Shanghai]
          - Path=/hwk-test-microservice/**
        filters:
          - StripPrefix=1
     

3、Between

在配置时间之间的请求会被路由

pring:
  cloud:
    gateway:
      routes:
      - id: hwk-test-microservice
        uri: http://www.baidu.com
        predicates:
          - Between=2019-09-15T20:58:18.786182+08:00[Asia/Shanghai], 2019-09-16T20:58:18.786182+08:00[Asia/Shanghai]
          - Path=/hwk-test-microservice/**
        filters:
          - StripPrefix=1
      

4、Cookie

根据cookie中是否有该cookie匹配路由

spring:
  cloud:
    gateway:
      routes:
      - id: hwk-test-microservice
        uri: https://sougou.com/
        predicates:
          - Cookie=mycookie,mycookievalue
          - Path=/hwk-test-microservice/**
        filters:
          - StripPrefix=1

5、Header

根据header中是否有该header匹配路由

spring:
  cloud:
    gateway:
      routes:
      - id: hwk-test-microservice
        uri: https://sougou.com/
        predicates:
          - Header=X-Request-Id, \d+
          - Path=/hwk-test-microservice/**
        filters:
          - StripPrefix=1
      

6、Host

根据请求域名进行路由匹配

spring:
  cloud:
    gateway:
      routes:
      - id: hwk-test-microservice
        uri: https://sougou.com/
        predicates:
          - Host=localhost:10100,**.anotherhost.org
          - Path=/hwk-test-microservice/**
        filters:
          - StripPrefix=1
     

7、Method

根据请求类型进行路由匹配

spring:
  cloud:
    gateway:
      routes:
      - id: hwk-test-microservice
        uri: https://sougou.com/
        predicates:
          - Method=GET,POST
          - Path=/hwk-test-microservice/**
        filters:
          - StripPrefix=1
      

8、Path

常规路径配置进行路由匹配,matchOptionalTrailingSeparator匹配尾部分隔符,默认true

spring:
  cloud:
    gateway:
      routes:
      - id: hwk-test-microservice
        uri: https://sougou.com/
        predicates:
          - Path=/hwk-test-microservice/**,/hwk-test1-microservice/**
        filters:
          - StripPrefix=1

9、Query

根据query参数进行路由匹配

spring:
  cloud:
    gateway:
      routes:
      - id: hwk-test-microservice
        uri: https://sougou.com/
        predicates:
          - Query=red, gree.
          - Path=/hwk-test-microservice/**
        filters:
          - StripPrefix=1

10、Weight

监听器初始化权重属性,过滤器根据权重过滤出待匹配权重路由,核心处理器根据匹配路由跳转

spring:
  cloud:
    gateway:
      routes:
      - id: hwk-test-microservice
        uri: https://sougou.com/
        predicates:
          - Weight=group1, 8
          - Path=/hwk-test-microservice/**
        filters:
          - StripPrefix=1
      - id: hwk-test1-microservice
        uri: http://www.baidu.com
        predicates:
          - Weight=group1, 2
          - Path=/hwk-test-microservice/**
        filters:
          - StripPrefix=1
      - id: hwk-test2-microservice
        uri: http://www.baidu.com
        predicates:
          - Weight=group1, 9
          - Path=/hwk-test-microservice/**
        filters:
          - StripPrefix=1

11 、RemoteAddr

根据远程请求ip+子网掩码进行路由匹配,大于子网掩码的ip能正常访问

spring:
  cloud:
    gateway:
      routes:
      - id: hwk-test-microservice
        uri: http://www.baidu.com
        predicates:
          - RemoteAddr=192.168.3.1/27
          - Path=/hwk-test-microservice/**
        filters:
          - StripPrefix=1
      

12 、XForwardedRemoteAddr

根据远程请求头部代理ip+子网掩码进行路由匹配,大于子网掩码的ip能正常访问,新版本增加

spring:
  cloud:
    gateway:
      routes:
      - id: hwk-test-microservice
        uri: http://www.baidu.com
        predicates:
          - XForwardedRemoteAddr=192.168.3.1/27
          - Path=/hwk-test-microservice/**
        filters:
          - StripPrefix=1

二、过滤器

1、路由过滤器

1、AddRequestHeader

请求头部增加设置header

spring:
  cloud:
    gateway:
      routes:
      - id: hwk-test-microservice
        uri: http://www.baidu.com
        predicates:
          - Path=/hwk-test-microservice/**
        filters:
          - StripPrefix=1
          - AddRequestHeader=X-Request-red, blue

2、AddRequestParameter

地址增加请求参数

spring:
  cloud:
    gateway:
      routes:
      - id: hwk-test-microservice
        uri: http://www.baidu.com
        predicates:
          - Path=/hwk-test-microservice/**
        filters:
          - StripPrefix=1
          - AddRequestParameter=red, blue

3、AddResponseHeader

返回头部增加header

spring:
  cloud:
    gateway:
      routes:
      - id: hwk-test-microservice
        uri: http://www.baidu.com
        predicates:
          - Path=/hwk-test-microservice/**
        filters:
          - StripPrefix=1
          - AddResponseHeader=X-Response-Red, Blue

4、DedupeResponseHeader

头部重复header消除,需要有策略,没有设置策略,默认保留第一个

spring:
  cloud:
    gateway:
      routes:
      - id: hwk-test-microservice
        uri: http://www.baidu.com
        predicates:
          - Path=/hwk-test-microservice/**
        filters:
          - StripPrefix=1
          - DedupeResponseHeader=Access-Control-Allow-Credentials Access-Control-Allow-Origin

5、Spring Cloud CircuitBreaker

springcloud断路器,这部分可以展开调研

spring:
  cloud:
    gateway:
      routes:
      - id: circuitbreaker_route
        uri: lb://backing-service:8088
        predicates:
        - Path=/consumingServiceEndpoint
        filters:
        - name: CircuitBreaker
          args:
            name: myCircuitBreaker
            fallbackUri: forward:/inCaseOfFailureUseThis
        - RewritePath=/consumingServiceEndpoint, /backingServiceEndpoint

6、FallbackHeaders

在断路器fallback地址头部增加异常细节,需要和断路器结合使用

spring:
  cloud:
    gateway:
      routes:
      - id: ingredients
        uri: lb://ingredients
        predicates:
        - Path=//ingredients/**
        filters:
        - name: CircuitBreaker
          args:
            name: fetchIngredients
            fallbackUri: forward:/fallback
      - id: ingredients-fallback
        uri: http://localhost:9994
        predicates:
        - Path=/fallback
        filters:
        - name: FallbackHeaders
          args:
            executionExceptionTypeHeaderName: Test-Header

7、MapRequestHeader

将第一个header的值赋值给第二个header

spring:
  cloud:
    gateway:
      routes:
      - id: hwk-test-microservice
        uri: http://www.baidu.com
        predicates:
          - Path=/hwk-test-microservice/**
        filters:
          - StripPrefix=1
          - MapRequestHeader=X-Request-Blue, X-Request-Red

8、PrefixPath

给请求路径加前缀

spring:
  cloud:
    gateway:
      routes:
      - id: hwk-test-microservice
        uri: http://www.baidu.com
        predicates:
          - Path=/hwk-test-microservice/**
        filters:
          - StripPrefix=1
          - PrefixPath=/mypath

9、PreserveHostHeader

此筛选器设置路由筛选器检查的请求属性,以确定是否应发送原始主机标头,而不是HTTP客户端确定的主机标头

spring:
  cloud:
    gateway:
      routes:
      - id: hwk-test-microservice
        uri: http://www.baidu.com
        predicates:
          - Path=/hwk-test-microservice/**
        filters:
          - StripPrefix=1
          - PreserveHostHeader

10、RequestRateLimiter

网关限流,需要实现KeyResolver,默认实现PrincipalNameKeyResolver

@Bean
KeyResolver userKeyResolver() {
    return exchange -> Mono.just(exchange.getRequest().getQueryParams().getFirst("user"));
}
spring:
  cloud:
    gateway:
      routes:
      - id: hwk-test-microservice
        uri: http://www.baidu.com
        predicates:
          - Path=/hwk-test-microservice/**
        filters:
          - StripPrefix=1
          - name: RequestRateLimiter
	        args:
	          rate-limiter: "#{@redisRateLimiter}"
	          key-resolver: "#{@userKeyResolver}"

11、RedirectTo

重定向到指定地址以及状态码

spring:
  cloud:
    gateway:
      routes:
      - id: hwk-test-microservice
        uri: http://www.baidu.com
        predicates:
          - Path=/hwk-test-microservice/**
        filters:
          - StripPrefix=1
          - RedirectTo=302, https://www.baidu.com/

12、RemoveRequestHeader

移除请求头header

spring:
  cloud:
    gateway:
      routes:
      - id: hwk-test-microservice
        uri: http://www.baidu.com
        predicates:
          - Path=/hwk-test-microservice/**
        filters:
          - StripPrefix=1
          - RemoveRequestHeader=X-Request-Foo

13、RemoveResponseHeader

移除返回头header

spring:
  cloud:
    gateway:
      routes:
      - id: hwk-test-microservice
        uri: http://www.baidu.com
        predicates:
          - Path=/hwk-test-microservice/**
        filters:
          - StripPrefix=1
          - RemoveResponseHeader=X-Request-Foo

14、RemoveRequestParameter

移除请求参数

spring:
  cloud:
    gateway:
      routes:
      - id: hwk-test-microservice
        uri: http://www.baidu.com
        predicates:
          - Path=/hwk-test-microservice/**
        filters:
          - StripPrefix=1
          - RemoveRequestParameter=red

15、RequestHeaderSize

请求头header的value值总体不能超过指定size,超过了,会在返回的请求头header里增加errorMessage信息

spring:
  cloud:
    gateway:
      routes:
      - id: hwk-test-microservice
        uri: http://www.baidu.com
        predicates:
          - Path=/hwk-test-microservice/**
        filters:
          - StripPrefix=1
          - RequestHeaderSize=1000B

16、RewritePath

路径重写,支持正则

spring:
  cloud:
    gateway:
      routes:
      - id: hwk-test-microservice
        uri: http://www.baidu.com
        predicates:
          - Path=/hwk-test-microservice/**
        filters:
          - StripPrefix=1
          - RewritePath=/hwk-test-microservice/?(?<segment>.*), /$\{segment}

17、RewriteLocationResponseHeader

重写返回头部的location信息

spring:
  cloud:
    gateway:
      routes:
      - id: rewritelocationresponseheader_route
        uri: http://example.org
        filters:
        - RewriteLocationResponseHeader=AS_IN_REQUEST, Location, ,

18、RewriteResponseHeader

替换返回头部header的值

spring:
  cloud:
    gateway:
      routes:
      - id: hwk-test-microservice
        uri: http://www.baidu.com
        predicates:
          - Path=/hwk-test-microservice/**
        filters:
          - StripPrefix=1
          - RewriteResponseHeader=X-Response-Red, password=[^&]+, password=***

19、SaveSession

保存WebSession,与spring security结合使用

spring:
  cloud:
    gateway:
      routes:
      - id: hwk-test-microservice
        uri: http://www.baidu.com
        predicates:
          - Path=/hwk-test-microservice/**
        filters:
          - StripPrefix=1
          - SaveSession

20、SecureHeaders

spring:
  cloud:
    gateway:
      routes:
      - id: hwk-test-microservice
        uri: http://www.baidu.com
        predicates:
          - Path=/hwk-test-microservice/**
        filters:
          - StripPrefix=1

21、SetPath

根据模版设置path

spring:
  cloud:
    gateway:
      routes:
      - id: hwk-test-microservice
        uri: http://www.baidu.com
        predicates:
          - Path=/hwk-test-microservice/{segment}
        filters:
          - SetPath=/{segment}

22、SetRequestHeader

替换原有请求header为新给定值,不是添加

spring:
  cloud:
    gateway:
      routes:
      - id: hwk-test-microservice
        uri: http://www.baidu.com
        predicates:
          - Path=/hwk-test-microservice/**
        filters:
          - SetRequestHeader=X-Request-Red, Blue

23、SetResponseHeader

替换原有返回header为新给定值,不是添加

spring:
  cloud:
    gateway:
      routes:
      - id: hwk-test-microservice
        uri: http://www.baidu.com
        predicates:
          - Path=/hwk-test-microservice/**
        filters:
          - SetResponseHeader=X-Response-Red, Blue

24、SetStatus

设置返回状态为指定状态

spring:
  cloud:
    gateway:
      set-status:
        original-status-header-name: original-http-status
spring:
  cloud:
    gateway:
      routes:
      - id: hwk-test-microservice
        uri: http://www.baidu.com
        predicates:
          - Path=/hwk-test-microservice/**
        filters:
          - SetStatus=UNAUTHORIZED
spring:
  cloud:
    gateway:
      routes:
      - id: hwk-test-microservice
        uri: http://www.baidu.com
        predicates:
          - Path=/hwk-test-microservice/**
        filters:
          - SetStatus=401

25、StripPrefix

去掉指定数量的地址前缀

spring:
  cloud:
    gateway:
      routes:
      - id: hwk-test-microservice
        uri: http://www.baidu.com
        predicates:
          - Path=/hwk-test-microservice/**
        filters:
          - StripPrefix=2

26、Retry

指定时间间隔重新请求

spring:
  cloud:
    gateway:
      routes:
      - id: hwk-test-microservice
        uri: http://www.baidu.com
        predicates:
          - Path=/hwk-test-microservice/**
        filters:
          - StripPrefix=2
          -   name: Retry
	          args:
	            retries: 3
	            statuses: INTERNAL_SERVER_ERROR
	            methods: GET
	            backoff:
	              firstBackoff: 10ms
	              maxBackoff: 50ms
	              factor: 2
	              basedOnPreviousValue: false
      - id: hwk-test-microservice
        uri: http://www.baidu.com
        predicates:
          - Path=/hwk-test-microservice/**
        filters:
 	      - Retry=3,INTERNAL_SERVER_ERROR,GET,10ms,50ms,2,false

27、RequestSize

请求内容最大大小,content-length

spring:
  cloud:
    gateway:
      routes:
      - id: hwk-test-microservice
        uri: http://www.baidu.com
        predicates:
          - Path=/hwk-test-microservice/**
        filters:
          - StripPrefix=1
          - name: RequestSize
            args:
              maxSize: 5000000

28、SetRequestHostHeader

设置请求头host

spring:
  cloud:
    gateway:
      routes:
      - id: hwk-test-microservice
        uri: http://www.baidu.com
        predicates:
          - Path=/hwk-test-microservice/**
        filters:
          - name: SetRequestHostHeader
            args:
              host: example.org

29、ModifyRequestBody

修改请求体

@Bean
public RouteLocator routes(RouteLocatorBuilder builder) {
    return builder.routes()
        .route("rewrite_request_obj", r -> r.host("*.rewriterequestobj.org")
            .filters(f -> f.prefixPath("/httpbin")
                .modifyRequestBody(String.class, Hello.class, MediaType.APPLICATION_JSON_VALUE,
                    (exchange, s) -> return Mono.just(new Hello(s.toUpperCase())))).uri(uri))
        .build();
}

static class Hello {
    String message;

    public Hello() { }

    public Hello(String message) {
        this.message = message;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}

30、ModifyResponseBody

修改返回体

@Bean
public RouteLocator routes(RouteLocatorBuilder builder) {
    return builder.routes()
        .route("rewrite_response_upper", r -> r.host("*.rewriteresponseupper.org")
            .filters(f -> f.prefixPath("/httpbin")
                .modifyResponseBody(String.class, String.class,
                    (exchange, s) -> Mono.just(s.toUpperCase()))).uri(uri))
        .build();
}

31、default

全局增加过滤,所有route都生效

spring:
  cloud:
    gateway:
      default-filters:
      - AddResponseHeader=X-Response-Default-Red, Default-Blue
      - PrefixPath=/httpbin

2、全局过滤器

1、Netty Routing Filter

Gateway最后一个执行的过滤器,主要的操作是通过Netty实现的HttpClient 请求其他微服务的Http 服务
在这里插入图片描述

2、Netty Write Response Filter

如果ServerWebExchangeUtils.CLIENT_RESPONSE_CONN_ATTR连接存在,则对返回执行过滤
在这里插入图片描述

3、RouteToRequestUrl Filter

如果ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR有值匹配,则执行路由替换为请求地址过滤
在这里插入图片描述

4、Websocket Routing Filter

如果ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR有值匹配,则执行ws请求过滤
在这里插入图片描述

spring:
  cloud:
    gateway:
      routes:
      # SockJS route
      - id: websocket_sockjs_route
        uri: http://localhost:3001
        predicates:
        - Path=/websocket/info/**
      # Normal Websocket route
      - id: websocket_route
        uri: ws://localhost:3001
        predicates:
        - Path=/websocket/**

5、ReactiveLoadBalancerClientFilter

通过ReactorLoadBalancer解析uri服务为真实host+端口
若无法找到服务,则默认报错503,可以改为官方配置404,spring.cloud.gateway.loadbalancer.use404=true

spring:
  cloud:
    gateway:
      routes:
      - id: hwk-test-microservice
        uri: lb://hwk-test-microservice
        predicates:
        - Path=/hwk-test-microservice/**

6、Gateway Metrics Filter

针对路由请求的监控过滤
在这里插入图片描述

7、Forward Routing Filter

转发路由网关过滤器。其根据 forward:// 前缀( Scheme )过滤处理,将请求转发到当前网关实例本地接口。
在这里插入图片描述

spring:
  application:
      name: juejin-gateway
  cloud:
    gateway:
      routes:
      - id: forward_sample
        uri: forward:///globalfilters
        order: 10000
        predicates:
        - Path=/globalfilters
        filters:
        - PrefixPath=/application/gateway

在这里插入图片描述

8、Forward Path Filter

使请求request path从一个地址重定向到另一个地址过滤

9、Marking An Exchange As Routed

通过ServerWebExchangeUtils.isAlreadyRouted和ServerWebExchangeUtils.setAlreadyRouted来设置和判定过滤器是否执行

3、头部过滤器

在向下游发送请求之前,头部过滤器应用于请求,例如在NettyRoutingFilter中。

1、Forwarded Headers Filter

Forwarded Headers筛选器创建要发送到下游服务的Forwarded标头,它将当前请求的主机标头、scheme和端口添加到任何现有的Forwarded标头。
RFC 7239(June 2014)提出了一个标准化的Forwarded头部,来携带反向代理的基本信息,用于替代X-Forwarded系列及X-Real-IP等非标准化的头部。而ForwardedHeadersFilter便是提供了Forwarded头部的转发支持,目前经过gateway的请求会带上一个转发信息的Forwarded(host,proto,for)。

2、RemoveHopByHop Headers Filter

RemoveHopByHop标头筛选器从转发的请求中删除标头。
默认删除Connection、Keep-Alive、Proxy-Authenticate、Proxy-Authorization、TE、Trailer、Transfer-Encoding、Upgrade

spring.cloud.gateway.filter.remove-hop-by-hop.headers 

3、XForwarded Headers Filter

XForwarded Headers筛选器创建各种X-Forwarded-*标头以发送到下游服务。

创建单个标头,默认true
spring.cloud.gateway.x-forwarded.for-enabled
spring.cloud.gateway.x-forwarded.host-enabled
spring.cloud.gateway.x-forwarded.port-enabled
spring.cloud.gateway.x-forwarded.proto-enabled
spring.cloud.gateway.x-forwarded.prefix-enabled

附加多个标头,默认true
spring.cloud.gateway.x-forwarded.for-append
spring.cloud.gateway.x-forwarded.host-append
spring.cloud.gateway.x-forwarded.port-append
spring.cloud.gateway.x-forwarded.proto-append
spring.cloud.gateway.x-forwarded.prefix-append
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值