LoadBalancer 篩選器

LoadBalancer 篩選器接受 serviceId 參數。LoadBalancerClient 使用此參數來選擇路由的實例。LoadBalancer 篩選器需要在 Java DSL 中明確使用。當使用 LoadBalancer 篩選器時,請在 org.springframework.cloud.gateway.server.mvc.handler.HandlerFunctions 中使用空的 http() 方法。

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();
    }
}

在組態中使用 LoadBalancer 篩選器

LoadBalancer 篩選器可以在組態中使用,方法是使用具有 lb 方案的 URI(例如 lb://myservice),它使用 Spring Cloud LoadBalancerClient 來將名稱(在本例中為 myservice)解析為實際的主機和埠,並在同一個屬性中取代 URI。以下清單設定了 LoadBalancer 篩選器

application.yml
spring:
  cloud:
    gateway:
      mvc:
        routes:
        - id: api_route
          uri: lb://apiservice
          predicates:
          - Path=/api/**
預設情況下,當 ReactorLoadBalancer 無法找到服務實例時,會傳回 503
LoadBalancerClient 傳回的 ServiceInstanceisSecure 值會覆寫傳送到閘道的請求中指定的方案。例如,如果請求透過 HTTPS 進入閘道,但 ServiceInstance 指出它不安全,則下游請求會透過 HTTP 進行。相反的情況也可能適用。
閘道支援所有 LoadBalancer 功能。您可以在 Spring Cloud Commons 文件中閱讀有關它們的更多資訊。