Spring Cloud Gateway(譯)(Part 3)

7. Global Filters

GlobalFilter 接口具有與GatewayFilter相同的簽名. 這些特殊 filters有條件的應(yīng)用與所有路由.

此接口及其用法可能會(huì)在將來的里程碑版本中更改.

7.1. Combined Global Filter and GatewayFilter Ordering

當(dāng)請(qǐng)求與路由匹配時(shí), filtering web handler 將所有的GlobalFilter 和特定于路由的GatewayFilter 添加到filter鏈中. 該組合的過濾器鏈由 org.springframework.core.Ordered 接口排序, 你可以通過重寫getOrder() 方法來設(shè)置.

由于 Spring Cloud Gateway 有“pre” 和 “post” 兩個(gè)階段,filter 執(zhí)行邏輯(參考 How it Works), 因此具有最高優(yōu)先級(jí)的filter 在 “pre”-phase 是第一個(gè)儒陨,在 “post”-phase 是最后一個(gè).

下面是一個(gè) filter chain 的示例:

Example 56. ExampleConfiguration.java

@Bean
public GlobalFilter customFilter() {
    return new CustomGlobalFilter();
}

public class CustomGlobalFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("custom global filter");
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -1;
    }
}

7.2. Forward Routing Filter

ForwardRoutingFilterServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR 的 exchange 屬性中查找URI. 如果 URL 有 forward scheme (例如 forward:///localendpoint), 則使用 Spring DispatcherHandler 處理請(qǐng)求. 請(qǐng)求的 URL 路徑會(huì)被 forward URL 覆蓋. 未經(jīng)修改的原始URL會(huì)被添加到ServerWebExchangeUtils.GATEWAY_ORIGINAL_REQUEST_URL_ATTR 屬性的列表中.

7.3. The LoadBalancerClient Filter

LoadBalancerClientFilter在exchange中名為ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR 的 屬性中查找URI. 如果 URL 包含 scheme lb (例如 lb://myservice), 它使用 Spring Cloud LoadBalancerClient 將名稱(本例中為myservice)解析為實(shí)際的主機(jī)和端口倦卖,并替換同一屬性中的URI. 未經(jīng)修改的原始URL會(huì)被添加到ServerWebExchangeUtils.GATEWAY_ORIGINAL_REQUEST_URL_ATTR 屬性的列表中. filter 還會(huì)在 ServerWebExchangeUtils.GATEWAY_SCHEME_PREFIX_ATTR 屬性中查找其是否等于lb. 如果是, 則應(yīng)用相同的規(guī)則. 下面是LoadBalancerClientFilter`的配置示例:

Example 57. application.yml

spring:
  cloud:
    gateway:
      routes:
      - id: myRoute
        uri: lb://service
        predicates:
        - Path=/service/**

默認(rèn)情況下, 當(dāng)LoadBalancer找不到ServiceInstance 時(shí), 將返回 503 . 你可以通過設(shè)置spring.cloud.gateway.loadbalancer.use404=true將Gateway配置為返回 404 .

LoadBalancerClientFilter 使用阻塞的 LoadBalancerClient 引擎. 我們建議你使用 ReactiveLoadBalancerClientFilter 替代. 你可以通過將spring.cloud.loadbalancer.ribbon.enabledfalse 來切換成ReactiveLoadBalancerClientFilter .

7.4. The ReactiveLoadBalancerClientFilter

ReactiveLoadBalancerClientFilter 在 exchange中的名為 ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR屬性中查找URI. 如果URL 是lb scheme (比如 lb://myservice), 則它使用 Spring Cloud ReactorLoadBalancer 來根據(jù)名稱 (本示例中為myservice) 解析成實(shí)際的主機(jī)和端口稀并,并替換URI中的相同屬性. 未經(jīng)修改的原始URL會(huì)被添加到 ServerWebExchangeUtils.GATEWAY_ORIGINAL_REQUEST_URL_ATTR 屬性列表中. 該 filter還會(huì)在 ServerWebExchangeUtils.GATEWAY_SCHEME_PREFIX_ATTR 屬性中查找其是否等 lb. 如果有, 則適用相同的規(guī)則. 下面是ReactiveLoadBalancerClientFilter的配置示例:

Example 58. application.yml

spring:
  cloud:
    gateway:
      routes:
      - id: myRoute
        uri: lb://service
        predicates:
        - Path=/service/**

默認(rèn)情況下, 當(dāng)ReactorLoadBalancer找不到ServiceInstance 時(shí), 將返回 503 . 你可以通過設(shè)置spring.cloud.gateway.loadbalancer.use404=true將Gateway配置為返回 404 .

7.5. The Netty Routing Filter

如果 exchange 中名 ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR 屬性中的url的scheme是 http or https scheme. 則執(zhí)行Netty routing filter揍愁, 并使用 Netty HttpClient 發(fā)出下游代理請(qǐng)求. 請(qǐng)求的響應(yīng)會(huì)放在 exchange 中名為 ServerWebExchangeUtils.CLIENT_RESPONSE_ATTR 屬性中送淆, 以便后面的filter做進(jìn)一步的處理 . (還有一個(gè)實(shí)驗(yàn)性的 WebClientHttpRoutingFilter 執(zhí)行相同的功能辫红,但不需要Netty.)

7.6. The Netty Write Response Filter

如果NettyWriteResponseFilter 發(fā)現(xiàn)exchange的名為ServerWebExchangeUtils.CLIENT_RESPONSE_ATTR屬性中存在Netty HttpClientResponse 類型的實(shí)例锐帜,它在所有其他過濾器執(zhí)行完成后運(yùn)行瘾敢,將代理響應(yīng)寫回到gateway客戶端的響應(yīng)中. (還有一個(gè)實(shí)驗(yàn)性的WebClientWriteResponseFilter 執(zhí)行相同的功能 拍冠,但不需要Netty.)

7.7. The RouteToRequestUrl Filter

如果exchange的ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR存在Route 對(duì)象, 則RouteToRequestUrlFilter 會(huì)執(zhí)行. 它基于請(qǐng)求URI創(chuàng)建一個(gè)新URI尿这,但使用 Route 對(duì)象的URL屬性進(jìn)行更新. 新的URI會(huì)更新 exchange 的ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR 屬性中.

如果URI有scheme前綴, 例如lb:ws://serviceid, lb scheme 會(huì)從URI中截取出來放到 ServerWebExchangeUtils.GATEWAY_SCHEME_PREFIX_ATTR屬性中, 方便后面的filter chain使用.

7.8. The Websocket Routing Filter

如果exchange 的 ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR 屬性中含有 ws or wss scheme, websocket routing rilter 則會(huì)執(zhí)行. 它使用Spring WebSocket 基礎(chǔ)模塊來向下游轉(zhuǎn)發(fā)websocket請(qǐng)求.

你可是在URI前面加上lb前綴來實(shí)現(xiàn) websockets 負(fù)載均衡, 例如 lb:ws://serviceid.

下面是websocket routing filter的配置示例:

Example 59. application.yml

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/**

7.9. The Gateway Metrics Filter

若想啟用 gateway metrics , 需要添加spring-boot-starter-actuator 作為項(xiàng)目依賴項(xiàng).然后庆杜,默認(rèn)情況下, gateway metrics filter 會(huì)自動(dòng)啟動(dòng)射众,若想關(guān)閉,只要將 spring.cloud.gateway.metrics.enabled設(shè)置為 false. 該filter會(huì)添加一個(gè)名為a gateway.requests 時(shí)間度量, 包含如下tags:

  • routeId: 路由 ID.
  • routeUri: API路由到的URI.
  • outcome: 結(jié)果, 按 HttpStatus.Series 分類.
  • status: 返回給客戶端HTTP status .
  • httpStatusCode: 返回給客戶端HTTP status code.
  • httpMethod: 請(qǐng)求的HTTP 方法.

然后可以從 /actuator/metrics/gateway.requests 中抓取這些指標(biāo)晃财,并且可以輕松地將它們與Prometheus集成以創(chuàng)建 Grafana dashboard.

若要啟用 prometheus endpoint, 添加micrometer-registry-prometheus作為項(xiàng)目依賴項(xiàng).

7.10. Marking An Exchange As Routed

filter方法有一個(gè)參數(shù)ServerWebExchange, 在路由轉(zhuǎn)發(fā)到下游的時(shí)候通過設(shè)置exchange 的gatewayAlreadyRouted 屬性標(biāo)識(shí)為"已路由". 一旦請(qǐng)求被標(biāo)識(shí)為"已路由", 其他路由filters就不會(huì)再次去匹配路由請(qǐng)求, 實(shí)質(zhì)上會(huì)跳過該filter. 你可以使用多種便捷的方法將exchange標(biāo)記為"已路由"叨橱,或者檢查exchange是否已經(jīng)路由.

  • ServerWebExchangeUtils.isAlreadyRouted 接收一個(gè)ServerWebExchange 實(shí)例參數(shù)并檢查是否“routed”.
  • ServerWebExchangeUtils.setAlreadyRouted接收一個(gè) ServerWebExchange 實(shí)例參數(shù)并并將它設(shè)置為 “routed”.

8. HttpHeadersFilters

HttpHeadersFilters 在將請(qǐng)求發(fā)送到下游之前先應(yīng)用于請(qǐng)求, 例如NettyRoutingFilter.

8.1. Forwarded Headers Filter

Forwarded Headers Filter 創(chuàng)建一個(gè) Forwarded header 然后發(fā)送到下游服務(wù). 它將當(dāng)前請(qǐng)求的 Host header, scheme 和 port 添加到現(xiàn)有的 Forwarded header.

8.2. RemoveHopByHop Headers Filter

RemoveHopByHop Headers Filter 從轉(zhuǎn)發(fā)的請(qǐng)求中刪除headers. 默認(rèn)被刪除的 headers 列表來自 IETF.

The default removed headers are:

  • Connection
  • Keep-Alive
  • Proxy-Authenticate
  • Proxy-Authorization
  • TE
  • Trailer
  • Transfer-Encoding
  • Upgrade

要更改此設(shè)置,設(shè)置 spring.cloud.gateway.filter.remove-non-proxy-headers.headers 屬性為要?jiǎng)h除的header names 列表.

8.3. XForwarded Headers Filter

XForwarded Headers Filter 創(chuàng)建各種X-Forwarded-* headers 以發(fā)送到下游服務(wù). 它使用當(dāng)前請(qǐng)求的 Host header, scheme, port 和 path 來創(chuàng)建各種頭.

可以通過以下boolean屬性(默認(rèn)為true)創(chuàng)建創(chuàng)建獨(dú)立的headers:

  • 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

可以通過以下boolean屬性(默認(rèn)為true)控制追加多個(gè)headers :

  • 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

9. TLS and SSL

網(wǎng)關(guān)可以通過Spring server configuration來偵聽HTTPS上的請(qǐng)求 . 如下所示:

Example 60. application.yml

server:
  ssl:
    enabled: true
    key-alias: scg
    key-store-password: scg1234
    key-store: classpath:scg-keystore.p12
    key-store-type: PKCS12

網(wǎng)關(guān)路由可以路由到HTTP和HTTPS后端. 如果路由到HTTPS后端, 你可以將網(wǎng)關(guān)配置為信任所有具有證書的下游服務(wù).如下所示:

Example 61. application.yml

spring:
  cloud:
    gateway:
      httpclient:
        ssl:
          useInsecureTrustManager: true

不建議在生產(chǎn)環(huán)境使用不安全的信任管理器断盛。對(duì)于生產(chǎn)部署罗洗,可以使用一組已知證書配置網(wǎng)關(guān),這些證書可以通過以下方式進(jìn)行配置. 如下所示:

Example 62. application.yml

spring:
  cloud:
    gateway:
      httpclient:
        ssl:
          trustedX509Certificates:
          - cert1.pem
          - cert2.pem

如果Spring Cloud Gateway未配置受信任證書钢猛,則使用默認(rèn)信任庫(可以使用系統(tǒng)屬性javax.net.ssl.trustStore覆蓋)伙菜。

9.1. TLS Handshake

網(wǎng)關(guān)維護(hù)一個(gè)用于路由到后端的client池。當(dāng)通過HTTPS通信時(shí)命迈,客戶端啟動(dòng)一個(gè)TLS握手贩绕,其中可能會(huì)有很多超時(shí)。這些超時(shí)可以如下配置(顯示默認(rèn)值):

Example 63. application.yml

spring:
  cloud:
    gateway:
      httpclient:
        ssl:
          handshake-timeout-millis: 10000
          close-notify-flush-timeout-millis: 3000
          close-notify-read-timeout-millis: 0

10. Configuration

Spring Cloud Gateway 的配置由RouteDefinitionLocator 實(shí)例的集合驅(qū)動(dòng). 下面顯示 RouteDefinitionLocator 借口:

Example 64. RouteDefinitionLocator.java

public interface RouteDefinitionLocator {
    Flux<RouteDefinition> getRouteDefinitions();
}

默認(rèn)情況下 , PropertiesRouteDefinitionLocator 使用Spring Boot的 @ConfigurationProperties` 機(jī)制加載屬性.

較早的配置示例均使用shortcut notation壶愤,shortcut notation使用位置參數(shù)而不是命名參數(shù)淑倾。

以下兩個(gè)示例是等效的:

Example 65. application.yml

spring:
  cloud:
    gateway:
      routes:
      - id: setstatus_route
        uri: https://example.org
        filters:
        - name: SetStatus
          args:
            status: 401
      - id: setstatusshortcut_route
        uri: https://example.org
        filters:
        - SetStatus=401

對(duì)于網(wǎng)關(guān)的大部分用法,配置文件方式是夠用的征椒,但一些生產(chǎn)用例更建議從外部源(如數(shù)據(jù)庫)加載配置. 未來的里程碑版本將有基于Spring Data Repositories(例如 Redis, MongoDB, and Cassandra) 的RouteDefinitionLocator實(shí)現(xiàn) .

11. Route Metadata Configuration

你可以通過使用metadata為每一個(gè)路由配置額外的參數(shù), 如下所示:

Example 66. application.yml

spring:
  cloud:
    gateway:
      routes:
      - id: route_with_metadata
        uri: https://example.org
        metadata:
          optionName: "OptionValue"
          compositeObject:
            name: "value"
          iAmNumber: 1

你可以從exchange中獲取所有的metadata 屬性, 如下所示:

Route route = exchange.getAttribute(GATEWAY_ROUTE_ATTR);
// get all metadata properties
route.getMetadata();
// get a single metadata property
route.getMetadata(someKey);

12. Http timeouts configuration

可以為所有路由配置Http超時(shí)(響應(yīng)和連接)娇哆,并為每個(gè)特定路由覆蓋Http超時(shí)。

12.1. Global timeouts

配置全局 http 超時(shí):
connect-timeout 必須是毫秒為單位.
response-timeout 必須是 java.time.Duration 對(duì)象

全局 http 超時(shí)示例

spring:
  cloud:
    gateway:
      httpclient:
        connect-timeout: 1000
        response-timeout: 5s

12.2. Per-route timeouts

配置單個(gè)路由的 timeouts:
connect-timeout 必須以毫秒為單位
response-timeout 必須以毫秒為單位

per-route http timeouts configuration via configuration

      - id: per_route_timeouts
        uri: https://example.org
        predicates:
          - name: Path
            args:
              pattern: /delay/{timeout}
        metadata:
          response-timeout: 200
          connect-timeout: 200

per-route timeouts configuration using Java DSL

import static org.springframework.cloud.gateway.support.RouteMetadataUtils.CONNECT_TIMEOUT_ATTR;
import static org.springframework.cloud.gateway.support.RouteMetadataUtils.RESPONSE_TIMEOUT_ATTR;

      @Bean
      public RouteLocator customRouteLocator(RouteLocatorBuilder routeBuilder){
         return routeBuilder.routes()
               .route("test1", r -> {
                  return r.host("*.somehost.org").and().path("/somepath")
                        .filters(f -> f.addRequestHeader("header1", "header-value-1"))
                        .uri("http://someuri")
                        .metadata(RESPONSE_TIMEOUT_ATTR, 200)
                        .metadata(CONNECT_TIMEOUT_ATTR, 200);
               })
               .build();
      }

12.3. Fluent Java Routes API

為了可以更簡單在Java中配置勃救,在 RouteLocatorBuilder bean 中定義了一個(gè) fluent API. 如下所示:

Example 67. GatewaySampleApplication.java

// static imports from GatewayFilters and RoutePredicates
@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder, ThrottleGatewayFilterFactory throttle) {
    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")
            )
            .route(r -> r.path("/image/webp")
                .filters(f ->
                        f.addResponseHeader("X-AnotherHeader", "baz"))
                .uri("http://httpbin.org:80")
                .metadata("key", "value")
            )
            .route(r -> r.order(-1)
                .host("**.throttle.org").and().path("/get")
                .filters(f -> f.filter(throttle.apply(1,
                        1,
                        10,
                        TimeUnit.SECONDS)))
                .uri("http://httpbin.org:80")
                .metadata("key", "value")
            )
            .build();
}

這種樣式還允許使用更多的自定義斷言. 由 RouteDefinitionLocator beans定義的斷言使用邏輯 and組合. 通過使用fluent Java API, 可以在Predicate 類上使用 and(), or(), and negate() 運(yùn)算符.

12.4. The DiscoveryClient Route Definition Locator

可以將網(wǎng)關(guān)配置為基于使用兼容 DiscoveryClient 注冊中心注冊的服務(wù)來創(chuàng)建路由.

要啟用此功能迂尝,請(qǐng)?jiān)O(shè)置 spring.cloud.gateway.discovery.locator.enabled=true ,并確保DiscoveryClient 實(shí)現(xiàn)位于classpath上并已啟用如 Netflix Eureka, Consul, or Zookeeper) .

12.4.1. Configuring Predicates and Filters For DiscoveryClient Routes

默認(rèn)情況下剪芥,網(wǎng)關(guān)為通過 DiscoveryClient創(chuàng)建的路由定義單個(gè)斷言和過濾器.

默認(rèn)斷言是使用 /serviceId/**定義的path斷言, 其中serviceIdDiscoveryClient中服務(wù)的ID.

默認(rèn)過濾器是使用正則表達(dá)式 /serviceId/(?.*) 和替換的/${remaining}進(jìn)行重寫. 只是在請(qǐng)求被發(fā)送到下游之前從路徑中截取掉 service ID .

可以通過設(shè)置spring.cloud.gateway.discovery.locator.predicates[x] and spring.cloud.gateway.discovery.locator.filters[y]來實(shí)現(xiàn)自定義DiscoveryClient 路由使用的斷言and/or過濾器. 當(dāng)你這樣做時(shí),如果你想實(shí)現(xiàn)相同的功能, 需要確保包括前面顯示的默認(rèn)predicates和filters. 如下所示:

Example 68. application.properties

spring.cloud.gateway.discovery.locator.predicates[0].name: Path
spring.cloud.gateway.discovery.locator.predicates[0].args[pattern]: "'/'+serviceId+'/**'"
spring.cloud.gateway.discovery.locator.predicates[1].name: Host
spring.cloud.gateway.discovery.locator.predicates[1].args[pattern]: "'**.foo.com'"
spring.cloud.gateway.discovery.locator.filters[0].name: Hystrix
spring.cloud.gateway.discovery.locator.filters[0].args[name]: serviceId
spring.cloud.gateway.discovery.locator.filters[1].name: RewritePath
spring.cloud.gateway.discovery.locator.filters[1].args[regexp]: "'/' + serviceId + '/(?<remaining>.*)'"
spring.cloud.gateway.discovery.locator.filters[1].args[replacement]: "'/${remaining}'"

13. Reactor Netty Access Logs

要想開啟 Reactor Netty access logs, 需要設(shè)置-Dreactor.netty.http.server.accessLogEnabled=true.

必須是Java System Property而不是Spring Boot property

logging 模塊也可以通過配置單獨(dú)輸出一個(gè)access log文件琴许,下面是logback的配置例子:

Example 69. logback.xml

    <appender name="accessLog" class="ch.qos.logback.core.FileAppender">
        <file>access_log.log</file>
        <encoder>
            <pattern>%msg%n</pattern>
        </encoder>
    </appender>
    <appender name="async" class="ch.qos.logback.classic.AsyncAppender">
        <appender-ref ref="accessLog" />
    </appender>

    <logger name="reactor.netty.http.server.AccessLog" level="INFO" additivity="false">
        <appender-ref ref="async"/>
    </logger>

14. CORS Configuration

我們可以通過配置網(wǎng)關(guān)來控制CORS行為. “global” CORS 配置是URL 模式到 Spring Framework CorsConfiguration的映射税肪,如下所示:

Example 70. application.yml

spring:
  cloud:
    gateway:
      globalcors:
        cors-configurations:
          '[/**]':
            allowedOrigins: "https://docs.spring.io"
            allowedMethods:
            - GET

在前面的示例中,對(duì)于所有GET請(qǐng)求的路徑榜田,允許來自docs.spring.io的請(qǐng)求中的CORS請(qǐng)求益兄。

要為沒有被gateway route predicate處理的請(qǐng)求提供相同的CORS 配置, 需要設(shè)置 spring.cloud.gateway.globalcors.add-to-simple-url-handler-mapping 屬性為 true. 當(dāng)你嘗試支持CORS預(yù)檢請(qǐng)求并且您的路由謂詞未評(píng)估為true時(shí), 這很有用箭券,因?yàn)?HTTP 方法是 options.

15. Actuator API

/gateway actuator endpoint 允許你監(jiān)視Spring Cloud Gateway應(yīng)用并與之交互. 為了可遠(yuǎn)程訪問净捅,必須在應(yīng)用程序配置文件中 暴露HTTP or JMX . 如下所示:

Example 71. application.properties

management.endpoint.gateway.enabled=true # default value
management.endpoints.web.exposure.include=gateway

15.1. Verbose Actuator Format

Spring Cloud Gateway已經(jīng)支持一種新的,更詳細(xì)的格式. 它為每個(gè)路由添加了更多詳細(xì)信息, 您可以查看與每個(gè)路由關(guān)聯(lián)的predicates 和 filters 以及任何可用的配置. 以下是/actuator/gateway/routes配置示例:

[
  {
    "predicate": "(Hosts: [**.addrequestheader.org] && Paths: [/headers], match trailing slash: true)",
    "route_id": "add_request_header_test",
    "filters": [
      "[[AddResponseHeader X-Response-Default-Foo = 'Default-Bar'], order = 1]",
      "[[AddRequestHeader X-Request-Foo = 'Bar'], order = 1]",
      "[[PrefixPath prefix = '/httpbin'], order = 2]"
    ],
    "uri": "lb://testservice",
    "order": 0
  }
]

默認(rèn)情況下啟用此功能辩块。 要禁用它蛔六,請(qǐng)?jiān)O(shè)置以下屬性:

Example 72. application.properties

spring.cloud.gateway.actuator.verbose.enabled=false

在未來的版本中荆永,它將默認(rèn)為 true .

15.2. Retrieving Route Filters

本節(jié)詳細(xì)介紹如何檢索 route filters, 包括:

15.2.1. Global Filters

要檢索 應(yīng)用于所有路由的 global filters , 發(fā)起一個(gè)get請(qǐng)求 /actuator/gateway/globalfilters. 返回的結(jié)果類似于以下內(nèi)容 :

{
  "org.springframework.cloud.gateway.filter.LoadBalancerClientFilter@77856cc5": 10100,
  "org.springframework.cloud.gateway.filter.RouteToRequestUrlFilter@4f6fd101": 10000,
  "org.springframework.cloud.gateway.filter.NettyWriteResponseFilter@32d22650": -1,
  "org.springframework.cloud.gateway.filter.ForwardRoutingFilter@106459d9": 2147483647,
  "org.springframework.cloud.gateway.filter.NettyRoutingFilter@1fbd5e0": 2147483647,
  "org.springframework.cloud.gateway.filter.ForwardPathFilter@33a71d23": 0,
  "org.springframework.cloud.gateway.filter.AdaptCachedBodyGlobalFilter@135064ea": 2147483637,
  "org.springframework.cloud.gateway.filter.WebsocketRoutingFilter@23c05889": 2147483646
}

返回結(jié)果包含已就緒的global filters的詳細(xì)信息 . 對(duì)于每個(gè) global filter, 過濾器對(duì)象都有一個(gè)字符串表示形式(例如, org.springframework.cloud.gateway.filter.LoadBalancerClientFilter@77856cc5以及過 filter chain中的相應(yīng) order ) .

15.2.2. Route Filters

要檢索應(yīng)用于路由的 GatewayFilter factories , 發(fā)起一個(gè)get請(qǐng)求 /actuator/gateway/routefilters. 返回結(jié)果類似于以下內(nèi)容 :

{
  "[AddRequestHeaderGatewayFilterFactory@570ed9c configClass = AbstractNameValueGatewayFilterFactory.NameValueConfig]": null,
  "[SecureHeadersGatewayFilterFactory@fceab5d configClass = Object]": null,
  "[SaveSessionGatewayFilterFactory@4449b273 configClass = Object]": null
}

響應(yīng)包含應(yīng)用于任何特定路由的GatewayFilter工廠的詳細(xì)信息. 對(duì)于每個(gè)工廠,都有一個(gè)對(duì)應(yīng)對(duì)象的字符串表示形式 (例如, [SecureHeadersGatewayFilterFactory@fceab5d configClass = Object]). 請(qǐng)注意国章, null 值是由于端點(diǎn)控制器的實(shí)現(xiàn)不完整所致具钥,因?yàn)樗噲D設(shè)置對(duì)象在 filter chain中的順序, 而該順序不適用于GatewayFilter 工廠對(duì)象.

15.3. Refreshing the Route Cache

如果要清理路由的緩存,請(qǐng)POST請(qǐng)求 /actuator/gateway/refresh. 該請(qǐng)求將返回一個(gè)沒有body的200返回碼 .

15.4. Retrieving the Routes Defined in the Gateway

要檢索網(wǎng)關(guān)中定義的路由液兽,發(fā)送GET請(qǐng)求 /actuator/gateway/routes. 返回結(jié)果如下所示 :

[{
  "route_id": "first_route",
  "route_object": {
    "predicate": "org.springframework.cloud.gateway.handler.predicate.PathRoutePredicateFactory$$Lambda$432/1736826640@1e9d7e7d",
    "filters": [
      "OrderedGatewayFilter{delegate=org.springframework.cloud.gateway.filter.factory.PreserveHostHeaderGatewayFilterFactory$$Lambda$436/674480275@6631ef72, order=0}"
    ]
  },
  "order": 0
},
{
  "route_id": "second_route",
  "route_object": {
    "predicate": "org.springframework.cloud.gateway.handler.predicate.PathRoutePredicateFactory$$Lambda$432/1736826640@cd8d298",
    "filters": []
  },
  "order": 0
}]

返回結(jié)果中包含網(wǎng)關(guān)中所有定義的路由信息,下面表格中描述了返回結(jié)果信息 :

Path Type Description
route_id String The route ID.
route_object.predicate Object The route predicate.
route_object.filters Array The GatewayFilter factories applied to the route.
order Number The route order.

15.5. Retrieving Information about a Particular Route

要獲取單個(gè)路由的信息,發(fā)送GET請(qǐng)求 /actuator/gateway/routes/{id} ( 如 , /actuator/gateway/routes/first_route). 返回結(jié)果如下所示 :

{
  "id": "first_route",
  "predicates": [{
    "name": "Path",
    "args": {"_genkey_0":"/first"}
  }],
  "filters": [],
  "uri": "https://www.uri-destination.org",
  "order": 0
}]

下面表格中描述了返回結(jié)果信息 :

Path Type Description
id String The route ID.
predicates Array The collection of route predicates. Each item defines the name and the arguments of a given predicate.
filters Array The collection of filters applied to the route.
uri String The destination URI of the route.
order Number The route order.

15.6. Creating and Deleting a Particular Route

要?jiǎng)?chuàng)建一個(gè)路由挣棕,發(fā)送 POST 請(qǐng)求 /gateway/routes/{id_route_to_create} 參數(shù)為 JSON body 驮樊,具體route數(shù)據(jù)結(jié)構(gòu) (參見 Retrieving Information about a Particular Route).

要?jiǎng)h除一個(gè)路由,發(fā)送 DELETE請(qǐng)求 /gateway/routes/{id_route_to_delete}.

15.7. Recap: The List of All endpoints

下表總結(jié)了 Spring Cloud Gateway actuator endpoints ( 注意柑晒,每個(gè) endpoint 都需要/actuator/gateway 作為基本路徑):

ID HTTP Method Description
globalfilters GET Displays the list of global filters applied to the routes.
routefilters GET Displays the list of GatewayFilter factories applied to a particular route.
refresh POST Clears the routes cache.
routes GET Displays the list of routes defined in the gateway.
routes/{id} GET Displays information about a particular route.
routes/{id} POST Adds a new route to the gateway.
routes/{id} DELETE Removes an existing route from the gateway.
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末欧瘪,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子敦迄,更是在濱河造成了極大的恐慌恋追,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,919評(píng)論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件罚屋,死亡現(xiàn)場離奇詭異苦囱,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)脾猛,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,567評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門撕彤,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人猛拴,你說我怎么就攤上這事羹铅。” “怎么了愉昆?”我有些...
    開封第一講書人閱讀 163,316評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵职员,是天一觀的道長。 經(jīng)常有香客問我跛溉,道長焊切,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,294評(píng)論 1 292
  • 正文 為了忘掉前任芳室,我火速辦了婚禮专肪,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘堪侯。我一直安慰自己嚎尤,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,318評(píng)論 6 390
  • 文/花漫 我一把揭開白布伍宦。 她就那樣靜靜地躺著芽死,像睡著了一般乏梁。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上收奔,一...
    開封第一講書人閱讀 51,245評(píng)論 1 299
  • 那天掌呜,我揣著相機(jī)與錄音,去河邊找鬼坪哄。 笑死质蕉,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的翩肌。 我是一名探鬼主播模暗,決...
    沈念sama閱讀 40,120評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼念祭!你這毒婦竟也來了兑宇?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,964評(píng)論 0 275
  • 序言:老撾萬榮一對(duì)情侶失蹤粱坤,失蹤者是張志新(化名)和其女友劉穎隶糕,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體站玄,經(jīng)...
    沈念sama閱讀 45,376評(píng)論 1 313
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡枚驻,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,592評(píng)論 2 333
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了株旷。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片再登。...
    茶點(diǎn)故事閱讀 39,764評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖晾剖,靈堂內(nèi)的尸體忽然破棺而出锉矢,到底是詐尸還是另有隱情,我是刑警寧澤齿尽,帶...
    沈念sama閱讀 35,460評(píng)論 5 344
  • 正文 年R本政府宣布沽损,位于F島的核電站,受9級(jí)特大地震影響循头,放射性物質(zhì)發(fā)生泄漏绵估。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,070評(píng)論 3 327
  • 文/蒙蒙 一贷岸、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧磷雇,春花似錦偿警、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,697評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽盒使。三九已至,卻和暖如春七嫌,著一層夾襖步出監(jiān)牢的瞬間少办,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,846評(píng)論 1 269
  • 我被黑心中介騙來泰國打工诵原, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留英妓,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,819評(píng)論 2 370
  • 正文 我出身青樓绍赛,卻偏偏與公主長得像蔓纠,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子吗蚌,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,665評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容