Skip to content

网关参数配置整理

spring-cloud-gateway大致的整体调用流程图如下:

网关使用的是 webflux 接收请求,在 ReactorHttpHandlerAdapter 接收到请求之后,会将 netty 的请求、响应转为 http 的请求、响应并交给一个 http handler 执行后面的逻辑。

每个处理步骤说明如下:

NettyWebServer :等同于 tomcat 的网络接入,持有 ReactorHttpHandlerAdapter

ReactorHttpHandlerAdapter :处理 http 请求,持有 HttpHandler

HttpWebHandlerAdapter :是个 HttpHandler,http 的处理器,持有 WebHandler

ExceptionHandlingWebHandler :全局异常处理器,是个 WebHandler ,持有 WebHandler

org.springframework.web.server.handler.FilteringWebHandler :调用 DefaultWebFilterChain ,是个 WebHandler ,持有 DefaultWebFilterChain

DefaultWebFilterChain :是 WebFilterChain ,持有 List<WebFilter> ,每个 WebFilter等同 webmvc 的web filter。持有 WebHandler ,在 filterchain 执行完毕后调用 WebHandler

DispatcherHandler :等同 webmvc的DispatcherServlet ,是个 WebHandler

SimpleHandlerAdapter :等同 webmvc RequestMappingHandlerAdapter ,根据请求映射到对应的处理方法,对于该类功能就是调用 WebHandler 。持有 WebHandler 。是个 HandlerAdapter

org.springframework.cloud.gateway.handler.FilteringWebHandler :作用就是调起gateway的 filterchain 。是个 WebHandler

DefaultGatewayFilterChain gateway的filterchain ,即调用由 GatewayFilter 组成的gateway filter。限流、路由等功能都是在 GatewayFilter 内实现的

1. gateway接入参数

网关接入参数在 reactor.netty.ReactorNetty 类中,这些参数必须是 Java System 属性,而不是 Spring Boot 属性,所以设置的时候要在启动参数中添加 -Dxxx.xxx.xx

java
//netty默认的这些参数不建议修改设置,如果要修改建议修改下面这个参数,其余参数不要修改


public static final String IO_WORKER_COUNT = "reactor.netty.ioWorkerCount";
//此参数默认值是cpu工作线程数的2倍(但最小是4),最大不要超过4倍
 -Dreactor.netty.ioWorkerCount=x
//要启用Reactor Netty访问日志,请设置
 -Dreactor.netty.http.server.accessLogEnabled =true

测试启用Reactor Netty访问日志:

启动参数添加 -Dreactor.netty.http.server.accessLogEnabled = true之后,参考如下logback.xml配置:

xml
<!-- netty reactor 日志输出-->
<appender name="accessLog" class="ch.qos.logback.core.FileAppender">
    <file>${logPath}/accessLog.log</file>
    <encoder>
        <pattern>%msg%n</pattern>
        <charset>utf8</charset>
    </encoder>
</appender>
<appender name="async" level="info" additivity="false" class="ch.qos.logback.classic.AsyncAppender">
<appender-ref ref="accessLog"/>
</appender>
<root level="${logbackLoglevel}">
<appender-ref ref="async"/>
</root>

日志输出结果如下:

2. gateway接出参数

网关请求发出是通过 org.springframework.cloud.gateway.filter.NettyRoutingFilter 过滤器中执行。

NettyRoutingFilter 部分代码:

java
Flux<HttpClientResponse> responseFlux = getHttpClient(route, exchange)
        .headers(headers -> {
            headers.add(httpHeaders);
            // Will either be set below, or later by Netty
            headers.remove(HttpHeaders.HOST);
            if (preserveHost) {
                String host = request.getHeaders().getFirst(HttpHeaders.HOST);
                headers.add(HttpHeaders.HOST, host);
            }
        }).request(method).uri(url).send((req, nettyOutbound) -> {
				...
            //省略

            protected HttpClient getHttpClient (Route route, ServerWebExchange exchange){
                Object connectTimeoutAttr = route.getMetadata().get(CONNECT_TIMEOUT_ATTR);
                if (connectTimeoutAttr != null) {
                    Integer connectTimeout = getInteger(connectTimeoutAttr);
                    return this.httpClient.tcpConfiguration((tcpClient) -> tcpClient
                            .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeout));
                }
                return httpClient;
            }


            //构造函数
	public NettyRoutingFilter(HttpClient httpClient,
                    ObjectProvider < List < HttpHeadersFilter >> headersFiltersProvider,
                    HttpClientProperties properties) {
                this.httpClient = httpClient;
                this.headersFiltersProvider = headersFiltersProvider;
                this.properties = properties;
            }

在发出请求时需要获取一个 HttpClient 对象,此对象时在初始化这个过滤器的Bean通过构造参数传进来的。初始化这个过滤器的Bean代码在 org.springframework.cloud.gateway.config.GatewayAutoConfigurationl类中:

java

@Bean
public HttpClientProperties httpClientProperties() {
    return new HttpClientProperties();
}

@Bean
public NettyRoutingFilter routingFilter(HttpClient httpClient,
                                        ObjectProvider<List<HttpHeadersFilter>> headersFilters,
                                        HttpClientProperties properties) {
    return new NettyRoutingFilter(httpClient, headersFilters, properties);
}

由源码可以看出,传入的 HttpClient 配置使用的是 HttpClientProperties 这个类中的配置,具体位置在 org.springframework.cloud.gateway.config.HttpClientProperties,故接出的参数就可以直接在配置文件中配置此类中的参数,参数的具体键值可在此类中查找。

yaml
#参数解释
spring.cloud.gateway.httpclient.connect-timeout=2000   #全局的TCP连接超时时间默认时间是45秒,所以也就是发生网络故障的时候,连接时间要等待45秒,而网络连接是同步阻塞的 ,The connect timeout in millis, the default is 45s. 所以就会导致请求非常慢,从网关就卡死了 (毫秒级参数)
spring.cloud.gateway.httpclient.response-timeout=30000  #全局的响应超时时间,网络链接后,后端服务多久不返回网关就报错 The response timeout (毫秒级参数)
spring.cloud.gateway.httpclient.pool.max-idle-time=1000 #这个参数的作用就是Spring cloud gateway的空闲连接超时回收时间
spring.cloud.gateway.httpclient.max-header-size   #设置最大响应头大小
spring.cloud.gateway.httpclient.max-initial-line-length  #最大初始行长度
spring.cloud.gateway.httpclient.pool.acquire-timeout    #仅对于FIXED类型,等待获取的最长时间(毫秒)。默认是PoolResources.DEFAULT_POOL_ACQUIRE_TIMEOUT。
spring.cloud.gateway.httpclient.pool.max-connections #仅适用于FIXED类型,即在现有连接上启动挂起获取之前的最大连接数(默认是PoolResources.DEFAULT_POOL_MAX_CONNECTION)
spring.cloud.gateway.httpclient.pool.max-idle-time #通道关闭后的时间(毫秒)。如果为空,则没有最长空闲时间。
spring.cloud.gateway.httpclient.pool.max-life-time #关闭通道的持续时间。如果为空,则没有最长生存时间。
spring.cloud.gateway.httpclient.pool.name #通道池映射名称默认为proxy。
spring.cloud.gateway.httpclient.pool.type #HttpClient要使用的池类型,默认为ELASTIC。
spring.cloud.gateway.httpclient.proxy.host  #Netty HttpClient代理配置的主机名
spring.cloud.gateway.httpclient.proxy.non-proxy-hosts-pattern #已配置主机列表的正则表达式(Java)。应该绕过代理直接到达
spring.cloud.gateway.httpclient.proxy.password #Netty HttpClient代理配置的密码。
spring.cloud.gateway.httpclient.proxy.port        #Netty HttpClient的代理配置端口。
spring.cloud.gateway.httpclient.proxy.username        #Netty HttpClient代理配置的用户名。
spring.cloud.gateway.httpclient.ssl.close-notify-flush-timeout    #SSL close_notify 刷新超时时间。默认为3000毫秒。
spring.cloud.gateway.httpclient.ssl.close-notify-read-timeout #SSL关闭通知读取超时。默认为0毫秒。
spring.cloud.gateway.httpclient.ssl.default-configuration-type    #默认ssl配置类型。默认为TCP。
spring.cloud.gateway.httpclient.ssl.handshake-timeout    #SSL握手超时。默认为10000毫秒
spring.cloud.gateway.httpclient.ssl.key-password    #密钥密码,默认值与keyStorePassword相同。
spring.cloud.gateway.httpclient.ssl.key-store        #Netty HttpClient的密钥库路径。
spring.cloud.gateway.httpclient.ssl.key-store-password        #密钥库密码。
spring.cloud.gateway.httpclient.ssl.key-store-provider #Netty HttpClient的密钥库提供程序,可选字段。
spring.cloud.gateway.httpclient.ssl.key-store-type    #Netty HttpClient的密钥库类型,默认为JKS。
spring.cloud.gateway.httpclient.ssl.trusted-x509-certificates #用于验证远程终结点的证书的受信任证书。
spring.cloud.gateway.httpclient.ssl.use-insecure-trust-manager    #安装netty UnsecureTrustManagerFactory。这是不安全的,不适合生产。
spring.cloud.gateway.httpclient.websocket.max-frame-payload-length    #最大帧有效载荷长度。
spring.cloud.gateway.httpclient.websocket.proxy-ping #代理ping帧到下游服务,默认为true。
spring.cloud.gateway.httpclient.wiretap	false    #启用Netty HttpClient的窃听调试。

注意:网关的接入接触默认的参数都是根据服务器的配置计算的,一般情况下不建议手动修改。

3. Ribbon参数配置

网关中的ribbon的负载均衡策略无法在Yaml中直接配置,需要在运维平台的服务治理模块的网关拓扑图菜单下找到对应的服务去设置,具体使用参考运维平台的配置手册。

其他可以在Yaml中配置的参数:

yaml
# ribbon请求连接的超时时间
ribbon.ConnectTimeout=2000
  # ribbon请求处理的超时时间
ribbon.ReadTimeout=5000
  #也可以为每个Ribbon客户端设置不同的超时时间, 通过服务名称进行指定:
ribbon-config-demo.ribbon.ConnectTimeout=2000
ribbon-config-demo.ribbon.ReadTimeout=5000
  # ribbon同步实例节点信息到本地的时间间隔
ribbon.ServerListRefreshInterval=5000

当我们在 RestTemplate 上添加 @LoadBalanced 注解后,就可以用服务名称来调用接口了,当有多个服务的时候,还能做负载均衡。这是因为 Eureka 中的服务信息已经被拉取到了客户端本地,如果我们不想和 Eureka 集成,可以通过下面的配置方法将其禁用。

yaml
# 禁用 Eureka
ribbon.eureka.enabled=false
#此参数一般不设置,因为平台代码中用到了@LoadBalanced注解

4. Hystrix参数

网关中关于hystrix的参数配置已经提出,可以在运维平台的服务治理模块去添加熔断配置,具体使用参照运维平台配置手册。

核心业务中的hystrix参数配置如下:

yaml
### hystrix 配置 
### hystrix.command.default中的default为默认CommandKey,如果要限制具体的服务可将default设置为具体的服务的 spring.application.name 的值
### 这些配置生效的对象是从此服务发出去的请求,而非此服务的接入请求
hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 10000  #发出请求的超时时间,默认1000ms
  threadpool:
    default:
      coreSize: 10  #并发执行的最大线程数,默认10
      maxQueueSize: 10   #BlockingQueue的最大队列数,当设为-1,会使用SynchronousQueue,值为正时使用LinkedBlcokingQueue。该设置只会在初始化时有效,之后不能修改threadpool的queue size,除非reinitialising thread executor。默认-1。

其他参数:

yaml
hystrix.command.default.circuitBreaker.errorThresholdPercentage #错误比率阀值,如果错误率>=该值,circuit会被打开,并短路所有请求触发fallback。默认50
hystrix.command.default.circuitBreaker.forceOpen #强制打开熔断器,如果打开这个开关,那么拒绝所有request,默认false
hystrix.command.default.circuitBreaker.forceClosed #强制关闭熔断器 如果这个开关打开,circuit将一直关闭且忽略circuitBreaker.errorThresholdPercentage
hystrix.command.default.execution.isolation.strategy #隔离策略,默认是Thread, 可选Thread|Semaphore
hystrix.command.default.execution.timeout.enabled #执行是否启用超时,默认启用true
hystrix.command.default.execution.isolation.thread.interruptOnTimeout #发生超时是是否中断,默认true
hystrix.command.default.execution.isolation.semaphore.maxConcurrentRequests #最大并发请求数,默认10,该参数当使用ExecutionIsolationStrategy.SEMAPHORE策略时才有效。如果达到最大并发请求数,请求会被拒绝。理论上选择semaphore size的原则和选择thread size一致,但选用semaphore时每次执行的单元要比较小且执行速度快(ms级别),否则的话应该用thread。semaphore应该占整个容器(tomcat)的线程池的一小部分。

  #Fallback相关的属性
  #这些参数可以应用于Hystrix的THREAD和SEMAPHORE策略
hystrix.command.default.fallback.isolation.semaphore.maxConcurrentRequests #如果并发数达到该设置值,请求会被拒绝和抛出异常并且fallback不会被调用。默认10
hystrix.command.default.fallback.enabled #当执行失败或者请求被拒绝,是否会尝试调用             											hystrixCommand.getFallback() #默认true


  #Circuit Breaker相关的属性
hystrix.command.default.circuitBreaker.enabled #用来跟踪circuit的健康性,如果未达标则让request短路。默认true
hystrix.command.default.circuitBreaker.requestVolumeThreshold #一个rolling window内最小的请求数。如果设为20,那么当一个rolling window的时间内(比如说1个rolling window是10秒)收到19个请求,即使19个请求都失败,也不会触发circuit break。默认20
hystrix.command.default.circuitBreaker.sleepWindowInMilliseconds #触发短路的时间值,当该值设为5000时,则当触发circuit break后的5000毫秒内都会拒绝request,也就是5000毫秒后才会关闭circuit。默认5000

  #Metrics相关参数
hystrix.command.default.metrics.rollingStats.timeInMilliseconds #设置统计的时间窗口值的,毫秒值,circuit break 的打开会根据1个rolling window的统计来计算。若rolling window被设为10000毫秒,则rolling window会被分成n个buckets,每个bucket包含success,failure,timeout,rejection的次数的统计信息。默认10000
hystrix.command.default.metrics.rollingStats.numBuckets #设置一个rolling window被划分的数量,若numBuckets=10,rolling window=10000,那么一个bucket的时间即1秒。必须符合rolling window % numberBuckets == 0。默认10
hystrix.command.default.metrics.rollingPercentile.enabled #执行时是否enable指标的计算和跟踪,默认true
hystrix.command.default.metrics.rollingPercentile.timeInMilliseconds #设置rolling percentile window的时间,默认60000
hystrix.command.default.metrics.rollingPercentile.numBuckets #设置rolling percentile window的numberBuckets。逻辑同上。默认6
hystrix.command.default.metrics.rollingPercentile.bucketSize #如果bucket size=100,window=10s,若这10s里有500次执行,只有最后100次执行会被统计到bucket里去。增加该值会增加内存开销以及排序的开销。默认100
hystrix.command.default.metrics.healthSnapshot.intervalInMilliseconds #记录health 快照(用来统计成功和错误绿)的间隔,默认500ms

  #Request Context 相关参数
hystrix.command.default.requestCache.enabled #默认true,需要重载getCacheKey(),返回null时不缓存
hystrix.command.default.requestLog.enabled #记录日志到HystrixRequestLog,默认true

  #Collapser Properties 相关参数
hystrix.collapser.default.maxRequestsInBatch #单次批处理的最大请求数,达到该数量触发批处理,默认Integer.MAX_VALUE
hystrix.collapser.default.timerDelayInMilliseconds #触发批处理的延迟,也可以为创建批处理的时间+该值,默认10
hystrix.collapser.default.requestCache.enabled #是否对HystrixCollapser.execute() and HystrixCollapser.queue()的cache,默认true


  #ThreadPool 相关参数

  #线程数默认值10适用于大部分情况(有时可以设置得更小),如果需要设置得更大,那有个基本得公式可以follow:
  #requests per second at peak when healthy × 99th percentile latency in seconds + some breathing room
  #每秒最大支撑的请求数 (99%平均响应时间 + 缓存值)
  #比如:每秒能处理1000个请求,99%的请求响应时间是60ms,那么公式是:1000 (0.060+0.012)
  #基本得原则时保持线程池尽可能小,他主要是为了释放压力,防止资源被阻塞。
  #当一切都是正常的时候,线程池一般仅会有1到2个线程激活来提供服务

hystrix.threadpool.default.coreSize #并发执行的最大线程数,默认10
hystrix.threadpool.default.maxQueueSize #BlockingQueue的最大队列数,当设为-1,会使用SynchronousQueue,值为正时使用LinkedBlcokingQueue。该设置只会在初始化时有效,之后不能修改threadpool的queue size,除非reinitialising thread executor。默认-1。
hystrix.threadpool.default.queueSizeRejectionThreshold #即使maxQueueSize没有达到,达到queueSizeRejectionThreshold该值后,请求也会被拒绝。因为maxQueueSize不能被动态修改,这个参数将允许我们动态设置该值。if maxQueueSize == -1,该字段将不起作用
hystrix.threadpool.default.keepAliveTimeMinutes #如果corePoolSize和maxPoolSize设成一样(默认实现)该设置无效。如果通过plugin(https://github.com/Netflix/Hystrix/wiki/Plugins)使用自定义实现,该设置才有用,默认1.
hystrix.threadpool.default.metrics.rollingStats.timeInMilliseconds #线程池统计指标的时间,默认10000
hystrix.threadpool.default.metrics.rollingStats.numBuckets #将rolling window划分为n个buckets,默认10

服务间feign调用hystrix熔断配置

yaml
feign:
  hystrix:
    enabled: true
hystrix:
  command:
    default:
      circuitBreaker:
        errorThresholdPercentage: 20 #错误比率
        requestVolumeThreshold: 5  #最小请求数
      execution:
        isolation: SEMAPHORE
        thread:
          timeoutInMilliseconds: 3000  #发出请求的超时时间,默认1000ms
logging:
  config: classpath:logback-prod.xml
  level:
    root: info
    com.dcits.demo: info
    com.netflix.loadbalancer.DynamicServerListLoadBalancer: debug
#强制关闭SpringCloud-Feign-Ribbon重试机制,测试过程中发现有时feign会自己启用ribbon的重试机制导致服务未能真正熔断
ribbon:
  ConnectTimeout: 50000 # 连接超时时间(ms)
  ReadTimeout: 50000 # 通信超时时间(ms)
  OkToRetryOnAllOperations: false # 关闭启用ribbon的重试所有操作
  MaxAutoRetriesNextServer: 0 # 同一服务不同实例的重试次数 默认为1
  MaxAutoRetries: 0 # 同一实例的重试次数 默认为0

如何验证熔断是否生效,在微服务启动类添加注解 @EnableCircuitBreaker ,启动服务调用之后服务IP+port+/lhdmon/hystrix.stream,可查看熔断器是否打开, isCircuitBreakerOpen:true 时熔断器打开,服务被熔断。

若/lhdmon/hystrix.stream不能访问,需要确认是否引入了spring-boot-starter-actuator.jar,引入了此jar包没有覆盖健康探测路径,访问/actuator/hystrix.stream。

5. 网关熔断配置

网关目前的熔断配置中的参数有如下几种:

页面配置对应 hystrix 原生的配置属性解释说明
超时时间execution.isolation.thread.timeoutInMilliseconds 接口访问的超时时间
最大请求数execution.isolation.semaphore.maxConcurrentRequests 最大请求数(默认10秒内超过20个请求次数) hystrix ExecutionIsolationStrategy 分为 SEMAPHORE THREAD 模式,针对 SEMAPHORE 模式才真正根据此属性进行限制,而如果是 THREAD 模式,则返回一个都放行的 TryableSemaphoreNoOp 实例
恢复时间circuitBreaker.sleepWindowInMilliseconds 熔断之后探测熔断是否恢复的时间窗口
错误率circuitBreaker.errorThresholdPercentage 统计请求的失败数达到多少后跳闸(默认10秒内超过50%的请求失败)
最小请求数circuitBreaker.requestVolumeThreshold 在一个bucket时间窗口内,此属性用于设置使熔断判断逻辑开始工作的最小请求数。(而不是最小失败请求数) 例如,如果值是20,那么如果在滚动窗口中只接收到19个请求(比如一个10秒的窗口),即便所有19个请求都失败了,熔断判断逻辑也不会被触发。

hystrix两种模式隔离策略解释:

(1) THREAD 线程池隔离:

​ 它在单独的线程上执行,并发请求受线程池中线程数的限制。

请求通过每次都开启一个单独线程运行。它的隔离是通过线程池,即每个隔离粒度都是个线程池,互相不干扰。线程池隔离方式,等于多了一层的保护措施,可以通过hytrix直接设置超时,超时后直接返回。

(2) SEMAPHORE 信号量隔离:

​ 它在调用线程上执行,并发请求受到信号量的限制。

​ 每次调用线程,当前请求通过计算信号量进行限制,当信号量大于了最大请求数(maxConcurrentRequests)时,进行限制,调用fallback接口快速返回。

网关默认的hysrix熔断设置是信号量模式,线程池模式对资源的消耗比较大,不建议使用。可通过过下配置修改:

yaml
hystrix:
  command:
    default:
      execution:
        isolation:
          strategy: SEMAPHORE   #THREAD为线程池模式,SEMAPHORE为信号量模式