LoadBalancer Filter

LoadBalancer 过滤器采用 serviceId 参数。LoadBalancerClient 使用它来选择一个用于路由的实例。LoadBalancer 过滤器需要在 Java DSL 中明确使用。在使用 LoadBalancer 过滤器时,请在 org.springframework.cloud.gateway.server.mvc.handler.HandlerFunctions 中使用空的 http() 方法。

The LoadBalancer Filter takes a serviceId parameter. The LoadBalancerClient uses this to choose an instance for routing. The LoadBalancer filter needs to be explicitly used in the Java DSL. When using the LoadBalancer Filter, use the empty http() method in org.springframework.cloud.gateway.server.mvc.handler.HandlerFunctions.

RouteConfiguration.java
import static org.springframework.cloud.gateway.server.mvc.filter.LoadBalancerFilterFunctions.lb;
import static org.springframework.cloud.gateway.server.mvc.handler.GatewayRouterFunctions.route;
import static org.springframework.cloud.gateway.server.mvc.handler.HandlerFunctions.http;

@Configuration
class RouteConfiguration {

    @Bean
    public RouterFunction<ServerResponse> gatewayRouterFunctionsAddReqHeader() {
		return route("api_route")
				.GET("/api/**", http())
					.filter(lb("apiservice"))
					.build();
    }
}

Using The LoadBalancer Filter In Configuration

LoadBalancer 过滤器可通过使用带有 lb 方案的 URI 在配置中使用(例如 lb://myservice),它使用 Spring Cloud LoadBalancerClient 将名称(本示例中的 myservice)解析为实际主机和端口,并替换同一属性中的 URI。以下清单配置了一个 LoadBalancer 过滤器:

The LoadBalancer Filter may be used in configuration by using a URI with the lb scheme (such as lb://myservice), it uses the Spring Cloud LoadBalancerClient to resolve the name (myservice in this example) to an actual host and port and replaces the URI in the same attribute. The following listing configures a LoadBalancer Filter:

application.yml
spring:
  cloud:
    gateway:
      mvc:
        routes:
        - id: api_route
          uri: lb://apiservice
          predicates:
          - Path=/api/**

默认情况下,当 ReactorLoadBalancer 找不到服务实例时,将返回 503

By default, when a service instance cannot be found by the ReactorLoadBalancer, a 503 is returned.

LoadBalancerClient 返回的 ServiceInstanceisSecure 值会覆盖发送到网关的请求中指定 的方案。例如,如果请求通过 HTTPS 进入网关,但 ServiceInstance 指示它不安全,则下游请求是通过 HTTP 进行的。相反的情况也可能适用。

The isSecure value of the ServiceInstance returned from the LoadBalancerClient overrides the scheme specified in the request made to the Gateway. For example, if the request comes into the Gateway over HTTPS but the ServiceInstance indicates it is not secure, the downstream request is made over HTTP. The opposite situation can also apply.

网关支持所有 LoadBalancer 功能。您可以在 Spring Cloud Commons documentation 中阅读有关它们更多信息。

Gateway supports all the LoadBalancer features. You can read more about them in the Spring Cloud Commons documentation.