gateway官网解读(四)

这是最后一块了, 要吐了......读官网真的不是一件人干的事情啊,尤其是我这种四级都是磕磕绊绊的人. 读完之后我会产出一篇总结.算是对我, 主要是对我老大有个交代. 

9. TLS and SSL

我现百度了一下

SSL:(Secure Socket Layer,安全套接字层),位于可靠的面向连接的网络层协议和应用层协议之间的一种协议层。SSL通过互相认证、使用数字签名确保完整性、使用加密确保私密性,以实现客户端和服务器之间的安全通讯。该协议由两层组成:SSL记录协议和SSL握手协议。

  TLS:(Transport Layer Security,传输层安全协议),用于两个应用程序之间提供保密性和数据完整性。该协议由两层组成:TLS记录协议和TLS握手协议。

https://blog.csdn.net/qq_33932782/article/details/55096383

简单来说我感觉这玩意有点像是socket的一种连接协议(我一共看了两分钟).

The gateway can listen for requests on HTTPS by following the usual Spring server configuration. The following example shows how to do so:

Example 63. application.yml

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

You can route gateway routes to both HTTP and HTTPS backends. If you are routing to an HTTPS backend, you can configure the gateway to trust all downstream certificates with the following configuration:

Example 64. application.yml

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

Using an insecure trust manager is not suitable for production. For a production deployment, you can configure the gateway with a set of known certificates that it can trust with the following configuration:

Example 65. application.yml

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

If the Spring Cloud Gateway is not provisioned with trusted certificates, the default trust store is used (which you can override by setting the javax.net.ssl.trustStore system property).

9.1. TLS Handshake

The gateway maintains a client pool that it uses to route to backends. When communicating over HTTPS, the client initiates a TLS handshake. A number of timeouts are associated with this handshake. You can configure these timeouts can be configured (defaults shown) as follows:

Example 66. application.yml

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

说的就是监控http和https的配置, 不过貌似我没用这个配置也不错...因为我把https解析放在nginx上了,加一句网关上面放了一层nginx我理解就是得给运维的小哥哥一口饭吃.开个玩笑, 留个nginx很多东西可以在ng去做,毕竟gateway属于应用范畴,指标不如nginx稳定.

10. Configuration

onfiguration for Spring Cloud Gateway is driven by a collection of RouteDefinitionLocator instances. The following listing shows the definition of the RouteDefinitionLocator interface:

Example 67. RouteDefinitionLocator.java

public interface RouteDefinitionLocator {
    Flux getRouteDefinitions();
}

By default, a PropertiesRouteDefinitionLocator loads properties by using Spring Boot’s @ConfigurationProperties mechanism.

The earlier configuration examples all use a shortcut notation that uses positional arguments rather than named ones. The following two examples are equivalent:

Example 68. 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

可以通过属性名称来过滤

11. Route Metadata Configuration

您可以使用元数据为每个路由配置其他参数,如下所示:

You can configure additional parameters for each route by using metadata, as follows:

Example 69. application.yml

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

You could acquire all metadata properties from an exchange, as follows:

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

12.1. Global timeouts

To configure Global http timeouts:
connect-timeout must be specified in milliseconds.
response-timeout must be specified as a java.time.Duration

global http timeouts example

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

12.2. Per-route timeouts

To configure per-route timeouts:
connect-timeout must be specified in milliseconds.
response-timeout must be specified in milliseconds.

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

就是jdk8的流式布局

12.4. The DiscoveryClient Route Definition Locator 结合注册中心,也不知道为啥这么重要的东西放在最后面,一如既往的坑

就是你要是用了注册中心需要spring.cloud.gateway.discovery.locator.enabled = true

12.4.1. Configuring Predicates and Filters For DiscoveryClient Routes

By default, the gateway defines a single predicate and filter for routes created with a DiscoveryClient.

The default predicate is a path predicate defined with the pattern /serviceId/**, where serviceId is the ID of the service from the DiscoveryClient.

The default filter is a rewrite path filter with the regex /serviceId/(?.*) and the replacement /${remaining}. This strips the service ID from the path before the request is sent downstream.

If you want to customize the predicates or filters used by the DiscoveryClient routes, set spring.cloud.gateway.discovery.locator.predicates[x] and spring.cloud.gateway.discovery.locator.filters[y]. When doing so, you need to make sure to include the default predicate and filter shown earlier, if you want to retain that functionality. The following example shows what this looks like:

Example 71. 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 + '/(?.*)'"
spring.cloud.gateway.discovery.locator.filters[1].args[replacement]: "'/${remaining}'"

最想要的居然他大爷的就这么点

12.4.1。为DiscoveryClient路由配置谓词和过滤器
默认情况下,网关为使用DiscoveryClient创建的路由定义单个谓词和过滤器。

默认谓词是使用/ serviceId / **模式定义的路径谓词,其中serviceId是来自DiscoveryClient的服务的ID。

缺省过滤器是带有正则表达式/serviceId/(?.*)和替换项/ $ {remaining}的重写路径过滤器。这会在向下游发送请求之前从路径中剥离服务ID。

如果要自定义DiscoveryClient路由使用的谓词或过滤器,请设置spring.cloud.gateway.discovery.locator.predicates [x]和spring.cloud.gateway.discovery.locator.filters [y]。这样做时,如果要保留该功能,则需要确保包括前面显示的默认谓词和过滤器。下面的示例显示其外观:

让我平复一下吐槽的心情: 意思就是你可以接入网关, 通过spring.cloud.gateway.discovery.locator.enabled = true 开启, 他连个yml都没舍得给写, 我了去了.开启以后呢你可以根据之前的写若干的断言和过滤器....现在想想貌似这个也有原因,接入网关好像也的确不这么写, 我们一会再说

13. Reactor Netty Access Logs

我用的log4j2不是back, 我就不多说了哈

14. CORS Configuration 跨域

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

I

15. Actuator API 健康 检测

The /gateway actuator endpoint lets you monitor and interact with a Spring Cloud Gateway application. To be remotely accessible, the endpoint has to be enabled and exposed over HTTP or JMX in the application properties. The following listing shows how to do so:

Example 74. application.properties

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

15.1. Verbose Actuator Format

/actuator/gateway/routes

 /actuator/gateway/globalfilters

16. Troubleshooting 常见问题

这个日志级别会比较牛逼, 可以监听server和client日志

请分别为HttpServer和HttpClient设置spring.cloud.gateway.httpserver.wiretap = true或spring.cloud.gateway.httpclient.wiretap = true。不过好像是从G版的SR3才开始

17. Developer Guide 也不知道为啥在这整了个指南

17.1. Writing Custom Route Predicate Factories 路由工厂

In order to write a Route Predicate you will need to implement RoutePredicateFactory. There is an abstract class called AbstractRoutePredicateFactory which you can extend.

MyRoutePredicateFactory.java

public class MyRoutePredicateFactory extends AbstractRoutePredicateFactory {

    public MyRoutePredicateFactory() {
        super(Config.class);
    }

    @Override
    public Predicate apply(Config config) {
        // grab configuration from Config object
        return exchange -> {
            //grab the request
            ServerHttpRequest request = exchange.getRequest();
            //take information from the request to see if it
            //matches configuration.
            return matches(config, request);
        };
    }

    public static class Config {
        //Put the configuration properties for your filter here
    }

}

17.2. Writing Custom GatewayFilter Factories

PostGatewayFilterFactory.java

public class PostGatewayFilterFactory extends AbstractGatewayFilterFactory {

    public PostGatewayFilterFactory() {
        super(Config.class);
    }

    @Override
    public GatewayFilter apply(Config config) {
        // grab configuration from Config object
        return (exchange, chain) -> {
            return chain.filter(exchange).then(Mono.fromRunnable(() -> {
                ServerHttpResponse response = exchange.getResponse();
                //Manipulate the response in some way
            }));
        };
    }

    public static class Config {
        //Put the configuration properties for your filter here
    }

}

17.2.1. Naming Custom Filters And References In Configuration

17.3. Writing Custom Global Filters

To write a custom global filter, you must implement GlobalFilter interface. This applies the filter to all requests.

The following examples show how to set up global pre and post filters, respectively:

@Bean
public GlobalFilter customGlobalFilter() {
    return (exchange, chain) -> exchange.getPrincipal()
        .map(Principal::getName)
        .defaultIfEmpty("Default User")
        .map(userName -> {
          //adds header to proxied request
          exchange.getRequest().mutate().header("CUSTOM-REQUEST-HEADER", userName).build();
          return exchange;
        })
        .flatMap(chain::filter);
}

@Bean
public GlobalFilter customGlobalPostFilter() {
    return (exchange, chain) -> chain.filter(exchange)
        .then(Mono.just(exchange))
        .map(serverWebExchange -> {
          //adds header to response
          serverWebExchange.getResponse().getHeaders().set("CUSTOM-RESPONSE-HEADER",
              HttpStatus.OK.equals(serverWebExchange.getResponse().getStatusCode()) ? "It worked": "It did not work");
          return serverWebExchange;
        })
        .then();
}

总结起来呢 就是他建议你如果用单一的校验,就用工厂模式17.1那种,如果是全局的呢就用17.2

18. Building a Simple Gateway by Using Spring MVC or Webflux

19. Configuration properties

To see the list of all Spring Cloud Gateway related configuration properties, see the appendix.

重点是第19个, 我找到了我翻遍百度没找到的配置清单.......想哭

你可能感兴趣的:(gateway,gateway)