1、思考:
一般而言,当我们在项目中引入了 LoadBalancer 负载均衡启动器组件,那么SpringBoot自动配置的ClassPath类路径加载机制会扫描到 LoadBalancer 类路径下的 spring.factories 配置文件,会注册一些Bean ,但为什么网关 Gateway项目只要引入了 LoadBalancer 就拥有了负载均衡这个能力呢?两者之间是怎么产生的化学反应的呢?下面我们一起台所一下吧!
GatewayReactiveLoadBalancerClientAutoConfiguration
之所以在 Gateway 网关中引入了 LoadBalancer 组件,Gateway就拥有了负载均衡能力,关键一点在于
Gateway 网关提前做好了 LoadBalancer组件的适配工作,其主要实现是由 Gateway 网关专门为集成为LoadBalancer 而实现自动配置类 GatewayReactiveLoadBalancerClientAutoConfiguration 完成
源码如下:
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({ ReactiveLoadBalancer.class, LoadBalancerAutoConfiguration.class, DispatcherHandler.class })
@AutoConfigureAfter(LoadBalancerAutoConfiguration.class)
@EnableConfigurationProperties(GatewayLoadBalancerProperties.class)
public class GatewayReactiveLoadBalancerClientAutoConfiguration {
@Bean
@ConditionalOnBean(LoadBalancerClientFactory.class)
@ConditionalOnMissingBean(ReactiveLoadBalancerClientFilter.class)
@ConditionalOnEnabledGlobalFilter
public ReactiveLoadBalancerClientFilter gatewayLoadBalancerClientFilter(LoadBalancerClientFactory clientFactory,
GatewayLoadBalancerProperties properties) {
return new ReactiveLoadBalancerClientFilter(clientFactory, properties);
}
@Bean
@ConditionalOnBean({ ReactiveLoadBalancerClientFilter.class, LoadBalancerClientFactory.class })
@ConditionalOnMissingBean
@ConditionalOnEnabledGlobalFilter
public LoadBalancerServiceInstanceCookieFilter loadBalancerServiceInstanceCookieFilter(
LoadBalancerClientFactory loadBalancerClientFactory) {
return new LoadBalancerServiceInstanceCookieFilter(loadBalancerClientFactory);
}
}
从上面的源码可以看到,GatewayReactiveLoadBalancerClientAutoConfiguration 该自动配置类是在LoadBalancerAutoConfiguration 配置类注册完成之后才能被注册,也就意味着,一旦Gateway 网关项目没有引入 LoadBalancer 组件的话,那么该GatewayReactiveLoadBalancerClientAutoConfiguration 配置类将永远不会生效,因为两者之间存在着注册的前后依赖关系,也就意味着,一旦Bean注册的前置条件不满足,那么该Bean将无法注册生效。此外,从该配置类的 @ConditionalOnClass 注解条件也同样可以看出,上面的依赖关系,只不过
@ConditionalOnClass 的条件更多。回归到源码内容:从该配置类的内容可以看出,其内注册了两个
Bean 分别是:ReactiveLoadBalancerClientFilter、LoadBalancerServiceInstanceCookieFilter