gateway官方文档解读(二)

6. GatewayFilter Factories

Route filters allow the modification of the incoming HTTP request or outgoing HTTP response in some manner. Route filters are scoped to a particular route. Spring Cloud Gateway includes many built-in GatewayFilter Factories.

google原话

路由过滤器允许以某种方式修改传入的HTTP请求或传出的HTTP响应。 路由过滤器适用于特定路由。 Spring Cloud Gateway包括许多内置的GatewayFilter工厂。

简单来说Filter主要作用就是对request或者response做重构用的,其实也可以把业务层做在这里面,比如token验证就一个做成一个pre的filter

6.1. The AddRequestHeader GatewayFilter Factory

The AddRequestHeader GatewayFilter factory takes a name and value parameter. The following example configures an AddRequestHeader GatewayFilter:

Example 13. application.yml

spring:
  cloud:
    gateway:
      routes:
      - id: add_request_header_route
        uri: https://example.org
        filters:
        - AddRequestHeader=X-Request-red, blue

This listing adds X-Request-red:blue header to the downstream request’s headers for all matching requests.

Example 14. application.yml

spring:
  cloud:
    gateway:
      routes:
      - id: add_request_header_route
        uri: https://example.org
        predicates:
        - Path=/red/{segment}
        filters:
        - AddRequestHeader=X-Request-Red, Blue-{segment}

这是一个标准格式了, 一个路由(id,url:目标,断言:条件,filter)

6.2. The AddRequestParameter GatewayFilter Factory

6.3. The AddResponseHeader GatewayFilter Factory

6.4. The DedupeResponseHeader GatewayFilter Factory

6.5. The Hystrix GatewayFilter Factory

spring:
  cloud:
    gateway:
      routes:
      - id: hystrix_route
        uri: lb://backing-service:8088
        predicates:
        - Path=/consumingserviceendpoint
        filters:
        - name: Hystrix
          args:
            name: fallbackcmd
            fallbackUri: forward:/incaseoffailureusethis
        - RewritePath=/consumingserviceendpoint, /backingserviceendpoint

This will forward to the /incaseoffailureusethis URI when the Hystrix fallback is called. Note that this example also demonstrates (optional) Spring Cloud Netflix Ribbon load-balancing (defined the lb prefix on the destination URI).

The primary scenario is to use the fallbackUri to an internal controller or handler within the gateway app. However, you can also reroute the request to a controller or handler in an external application, as follows:

Example 23. application.yml

hystrix.command.fallbackcmd.execution.isolation.thread.timeoutInMilliseconds: 5000

综上呢gateway又秀了一波filter, 同时也明确了filter和rotes和prediscates的场景区别, rotes和prediscates主要处理的路由映射关系,我猜测负载均衡限流应该也在这,filter主要是对request和response的修改以及监控,简单的讲二者都是拿着七层协议玩耍,前者是怎么分配以及所有不需要改变内容的,后者是你需要改动内容的,这么看权限校验是应该放在rotes和prediscates里面更合适. 当然filter也能实现,但是貌似不符合理念.随着后面的解读我们会进一步深入确认

6.6. Spring Cloud CircuitBreaker GatewayFilter Factory 断路器

The Spring Cloud CircuitBreaker GatewayFilter factory uses the Spring Cloud CircuitBreaker APIs to wrap Gateway routes in a circuit breaker. Spring Cloud CircuitBreaker supports two libraries that can be used with Spring Cloud Gateway, Hystrix and Resilience4J. Since Netflix has placed Hystrix in maintenance-only mode, we suggest that you use Resilience4J.

To enable the Spring Cloud CircuitBreaker filter, you need to place either spring-cloud-starter-circuitbreaker-reactor-resilience4j or spring-cloud-starter-netflix-hystrix on the classpath. The following example configures a Spring Cloud CircuitBreaker GatewayFilter:

Example 24. application.yml

spring:
  cloud:
    gateway:
      routes:
      - id: circuitbreaker_route
        uri: https://example.org
        filters:
        - CircuitBreaker=myCircuitBreaker

To configure the circuit breaker, see the configuration for the underlying circuit breaker implementation you are using.

这段话意思大概就是hystrix 已经不维护了,建议用Resilience4J,不管用哪个都需要指定circitBreaker

  • Resilience4J Documentation

  • Hystrix Documentation

  • Example 25. application.yml

    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

    The following listing does the same thing in Java:

    Example 26. Application.java

    @Bean
    public RouteLocator routes(RouteLocatorBuilder builder) {
        return builder.routes()
            .route("circuitbreaker_route", r -> r.path("/consumingServiceEndpoint")
                .filters(f -> f.circuitBreaker(c -> c.name("myCircuitBreaker").fallbackUri("forward:/inCaseOfFailureUseThis"))
                    .rewritePath("/consumingServiceEndpoint", "/backingServiceEndpoint")).uri("lb://backing-service:8088")
            .build();
    }

    二者是等效的,可以用代码或者配置

  • This example forwards to the /inCaseofFailureUseThis URI when the circuit breaker fallback is called. Note that this example also demonstrates the (optional) Spring Cloud Netflix Ribbon load-balancing (defined by the lb prefix on the destination URI).

    The primary scenario is to use the fallbackUri to define an internal controller or handler within the gateway application. However, you can also reroute the request to a controller or handler in an external application, as follows:

这里面说一下rewritePath

RewritePath Filter 重写请求路径 https://www.jianshu.com/p/c8ac84e820cc

spring:
  cloud:
    gateway:
      routes:
      - id: host_route
        uri: http://localhost:8001
        predicates:
        - Path=/{path}
        filters:
        # 访问localhost:8080/test, 请求会转发到localhost:8001/app/test
        - RewritePath=/test, /app/test

这个filter比较灵活的就是可以进行正则匹配替换,如下的例子就是当请求localhost:8080/test时,匹配所有以/开头的路径,然后在前面加上/app,所以现在请求变成了localhost:8080/app/test。然后转发时的url变成了localhost:8001/app/test 。在测试的时候,这个filter是没办法使用模板进行匹配的。可能是因为它是用的正则进行匹配替换,所以没办法使用模板吧

6.6.1. Tripping The Circuit Breaker On Status Codes

Example 28. application.yml

spring:
  cloud:
    gateway:
      routes:
      - id: circuitbreaker_route
        uri: lb://backing-service:8088
        predicates:
        - Path=/consumingServiceEndpoint
        filters:
        - name: CircuitBreaker
          args:
            name: myCircuitBreaker
            fallbackUri: forward:/inCaseOfFailureUseThis
            statusCodes:
              - 500
              - "NOT_FOUND"

6.7. The FallbackHeaders GatewayFilter Factory

6.8. The MapRequestHeader GatewayFilter Factory

6.9. The PrefixPath GatewayFilter Factory

6.10. The PreserveHostHeader GatewayFilter Factory

6.11. The RequestRateLimiter GatewayFilter Factory

6.11.1. The Redis RateLimiter

redis限流猛一看有点懵逼啊....

直接上google后的原文

Redis的实现基于Stripe所做的工作。它需要使用spring-boot-starter-data-redis-active Spring Boot启动器。

使用的算法是令牌桶算法。

redis-rate-limiter.replenishRate属性是您希望用户每秒允许多少个请求,而没有任何丢弃的请求。这是令牌桶被填充的速率。

redis-rate-limiter.burstCapacity属性是允许用户在一秒钟内执行的最大请求数。这是令牌桶可以容纳的令牌数。将此值设置为零将阻止所有请求。

redis-rate-limiter.requestedTokens属性是一个请求要花费多少个令牌。这是每个请求从存储桶中获取的令牌数,默认为1。

通过在replenishRate和burstCapacity中设置相同的值可以实现稳定的速率。通过将burstCapacity设置为高于replenishRate,可以允许临时突发。在这种情况下,速率限制器需要在两次突发之间保留一段时间(根据replenishRate),因为两个连续的突发将导致请求丢弃(HTTP 429-太多请求)。以下清单配置了redis-rate-limiter:

通过将replenishRate设置为所需的请求数,将requestTokens设置为以秒为单位的时间跨度并将burstCapacity设置为replenishRate和requestedToken的乘积,例如1,可以达到以下1个请求的速率限制。设置replenishRate = 1,requestedTokens = 60和burstCapacity = 60将导致限制为每分钟1个请求。

Example 36. application.yml

spring:
  cloud:
    gateway:
      routes:
      - id: requestratelimiter_route
        uri: https://example.org
        filters:
        - name: RequestRateLimiter
          args:
            redis-rate-limiter.replenishRate: 10
            redis-rate-limiter.burstCapacity: 20
            redis-rate-limiter.requestedTokens: 1

The following example configures a KeyResolver in Java:

Example 37. Config.java

@Bean
KeyResolver userKeyResolver() {
    return exchange -> Mono.just(exchange.getRequest().getQueryParams().getFirst("user"));
}

这定义了每个用户10的请求速率限制。 允许20个突发,但是在下一秒中,只有10个请求可用。 KeyResolver是一个简单的获取用户请求参数的参数(请注意,不建议在生产环境中使用此参数)。

您还可以将速率限制器定义为实现RateLimiter接口的Bean。 在配置中,可以使用SpEL按名称引用Bean。 #{@ myRateLimiter}是一个SpEL表达式,它引用名为myRateLimiter的bean。 以下清单定义了一个速率限制器,该限制器使用前面清单中定义的KeyResolver:

xample 38. application.yml

spring:
  cloud:
    gateway:
      routes:
      - id: requestratelimiter_route
        uri: https://example.org
        filters:
        - name: RequestRateLimiter
          args:
            rate-limiter: "#{@myRateLimiter}"
            key-resolver: "#{@userKeyResolver}"

6.12. The RedirectTo GatewayFilter Factory 重定向

Example 39. application.yml

spring:
  cloud:
    gateway:
      routes:
      - id: prefixpath_route
        uri: https://example.org
        filters:
        - RedirectTo=302, https://acme.org

This will send a status 302 with a Location:https://acme.org header to perform a redirect.

6.13. The RemoveRequestHeader GatewayFilter Factory

6.14. RemoveResponseHeader GatewayFilter Factory

6.15. The RemoveRequestParameter GatewayFilter Factory

6.16. The RewritePath GatewayFilter Factory 重定向

Example 43. application.yml

spring:
  cloud:
    gateway:
      routes:
      - id: rewritepath_route
        uri: https://example.org
        predicates:
        - Path=/red/**
        filters:
        - RewritePath=/red(?<segment>/?.*), $\{segment}

For a request path of /red/blue, this sets the path to /blue before making the downstream request. Note that the $ should be replaced with $\ because of the YAML specification.

6.17. RewriteLocationResponseHeader GatewayFilter Factory

................

剩下的6.*我实在是没有勇气翻译下去了

但是讲的都是filter的一些配置用法

--------------------总之还是挺牛逼的, 后续有时间的话我会整理一下内容,估计悬啊, 因为我个人一般都是喜欢看得见摸得着的,gateway好像是有全局filter和自定义filter.话不多少,走起--------------------

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值