一 介绍
当同时引入Spring Cloud Ribbon和Spring Cloud Eurek依赖时,会触发Eureka中实现的对Ribbon的自动化配置。Ribbon的自动化配置将会发生变化。
二 EurekaRibbonClientConfiguration源码解读
@Configuration
public class EurekaRibbonClientConfiguration {
private static final Log log = LogFactory.getLog(EurekaRibbonClientConfiguration.class);
@Value("${ribbon.eureka.approximateZoneFromHostname:false}")
private boolean approximateZoneFromHostname = false;
@RibbonClientName
private String serviceId = "client";
@Autowired(required = false)
private EurekaClientConfig clientConfig;
@Autowired(required = false)
private EurekaInstanceConfig eurekaConfig;
@Autowired
private PropertiesFactory propertiesFactory;
public EurekaRibbonClientConfiguration() {
}
public EurekaRibbonClientConfiguration(EurekaClientConfig clientConfig,
String serviceId, EurekaInstanceConfig eurekaConfig,
boolean approximateZoneFromHostname) {
this.clientConfig = clientConfig;
this.serviceId = serviceId;
this.eurekaConfig = eurekaConfig;
this.approximateZoneFromHostname = approximateZoneFromHostname;
}
@Bean
@ConditionalOnMissingBean
public IPing ribbonPing(IClientConfig config) {
if (this.propertiesFactory.isSet(IPing.class, serviceId)) {
return this.propertiesFactory.get(IPing.class, config, serviceId);
}
//IPing的实现由NIWSDiscoveryPing来完成
NIWSDiscoveryPing ping = new NIWSDiscoveryPing();
ping.initWithNiwsConfig(config);
return ping;
}
@Bean
@ConditionalOnMissingBean
public ServerList<?> ribbonServerList(IClientConfig config, Provider<EurekaClient> eurekaClientProvider) {
if (this.propertiesFactory.isSet(ServerList.class, serviceId)) {
return this.propertiesFactory.get(ServerList.class, config, serviceId);
}
//discoveryServerList的维护机制由DiscoveryEnabledNIWSServerList来完成
DiscoveryEnabledNIWSServerList discoveryServerList = new DiscoveryEnabledNIWSServerList(
config, eurekaClientProvider);
//serverList的维护机制有DomainExtractingServerList来完成
DomainExtractingServerList serverList = new DomainExtractingServerList(
discoveryServerList, config, this.approximateZoneFromHostname);
return serverList;
}
@Bean
public ServerIntrospector serverIntrospector() {
return new EurekaServerIntrospector();
}
......
}
}
三 Spring Cloud Ribbon和Spring Cloud Eureka结合后配置说明
1 配置更简单
不再需要通过类似hello-service.ribbon.listOfServers参数来指定具体的服务实例清单,因为Eureka将会为我们维护所有的实例清单。
2 Spring Cloud Ribbon默认实现了区域亲和策略。
只需要在服务实例的元数据中增加zone参数来指定自己所在的区域。
eureka.instance.metadataMap.zone=shanghai
3 通过配置ribbon.eureka.enabled=false将服务的维护实例回归到<client>.ribbon.listOfServers参数配置。