Ribbon - 負載均衡流程提過了propertiesFactory.isSet,這個主要是用於修改某個服務的負載均衡。spring
@Bean @ConditionalOnMissingBean public IRule ribbonRule(IClientConfig config) { if (this.propertiesFactory.isSet(IRule.class, name)) { return this.propertiesFactory.get(IRule.class, config, name); } ZoneAvoidanceRule rule = new ZoneAvoidanceRule(); rule.initWithNiwsConfig(config); return rule; }
調用isSet的時候,會判斷getClassName是否有找到對應的配置文件,若是有,則使用配置文件對應的規則。segmentfault
public PropertiesFactory() { classToProperty.put(ILoadBalancer.class, "NFLoadBalancerClassName"); classToProperty.put(IPing.class, "NFLoadBalancerPingClassName"); classToProperty.put(IRule.class, "NFLoadBalancerRuleClassName"); classToProperty.put(ServerList.class, "NIWSServerListClassName"); classToProperty.put(ServerListFilter.class, "NIWSServerListFilterClassName"); } public boolean isSet(Class clazz, String name) { return StringUtils.hasText(getClassName(clazz, name)); } public String getClassName(Class clazz, String name) { if (this.classToProperty.containsKey(clazz)) { String classNameProperty = this.classToProperty.get(clazz); String className = environment .getProperty(name + "." + NAMESPACE + "." + classNameProperty); return className; } return null; }
我本地的配置,這樣就把輪詢改成隨機了。負載均衡
eureka-provider: ribbon: NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule
首先要寫一個@Configurable,裏面包含了對應要重寫的規則。這個@Configurable不能被spring掃描到。dom
@Configurable public class CustomerConfiguration { // 定義負載均衡策略 @Bean public IRule ribbonRule() { return new RandomRule(); } }
而後在ConsumerApplication(也能夠在其餘能被掃描的地方)加上@RibbonClient註解。@RibbonClient(value = "eureka-provider", configuration = a.b.c.CustomerConfiguration.class)。
啓動後,對於eureka-provider的負載均衡策略,就是RandomRule。
那爲何CustomerConfiguration不能掃描呢,Ribbon - 負載均衡流程中提過整個流程,這邊針對這個CustomerConfiguration被掃描的狀況下大概講一下。
ide
@RibbonClients(defaultConfiguration= a.b.c.CustomerConfiguration.class),經過RibbonClients註解配置全局。
Ribbon - 初始化提過@RibbonClients的處理,他會經過RibbonClientConfigurationRegistrar把@RibbonClients的配置最終保存在SpringClientFactory中,而後AnnotationConfigApplicationContext調用refresh的時候,就會注入CustomerConfiguration,而後加載咱們自定義的IRule等其餘bean信息。
this