负载均衡器过滤器
负载均衡器过滤器(LoadBalancer Filter)需要一个 serviceId
参数。LoadBalancerClient
使用该参数来选择用于路由的实例。在 Java DSL 中,需要显式地使用负载均衡器过滤器。当使用负载均衡器过滤器时,请在 org.springframework.cloud.gateway.server.mvc.handler.HandlerFunctions
中使用空的 http()
方法。
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 过滤器
可以通过使用带有 lb
方案的 URI(例如 lb://myservice
)在配置中使用 LoadBalancer 过滤器,它使用 Spring Cloud 的 LoadBalancerClient
将名称(在此示例中为 myservice
)解析为实际的主机和端口,并在同一属性中替换 URI。以下配置展示了一个 LoadBalancer 过滤器的设置:
spring:
cloud:
gateway:
mvc:
routes:
- id: api_route
uri: lb://apiservice
predicates:
- Path=/api/**
备注
默认情况下,当 ReactorLoadBalancer
无法找到服务实例时,会返回 503
。
备注
从 LoadBalancerClient
返回的 ServiceInstance
的 isSecure
值会覆盖请求 Gateway 时指定的 scheme。例如,如果请求是通过 HTTPS
进入 Gateway 的,但 ServiceInstance
表明它不安全,则下游请求将通过 HTTP
发出。相反的情况也可能适用。
提示
Gateway 支持所有 LoadBalancer 的功能。你可以在 Spring Cloud Commons 文档 中了解更多相关信息。