1.当Ribbon和Eureka配合使用时,会自动将虚拟主机名映射成网络地址。
很多场景下,可能根据需要自定义Ribbon的配置,例如修改Ribbon的负载均衡规则等。可以使用java代码或属性自定义Ribbon的配置,两种方式是等价的
使用JAVA自定义Ribbon配置:
在 spring cloud 中,Ribbon的默认配置如下(格式BeanType beanName:ClassName):
- IClientConfig ribbonClientConfig:DefaultClientConfigImpl
- IRule ribbonRule:ZoneAvoidanceRule
- IPing ribbonPing:NoOpPing
- ServerList ribbonServerList:ConfigurationBasedServerList
- ServerListFilter ribbonServerListFilter:ZonePreferenceServerListFilter
- ILoadBalancer ribbonBalancer:ZoneAwareLoadBalancer
我们来查看默认的配置代码:
@Bean
@ConditionalOnMissingBean
public IRule ribbonRule(IClientConfig config) {
ZoneAvoidanceRule rule = new ZoneAvoidanceRule();
rule.initWithNiwsConfig(config);
return rule;
}
对应关系:BeanType:IRule beanName:ribbonRule ClassName:ZoneAvoidanceRule
以上代码添加了@ConditionalOnMissingBean,就是当用户没有指定同名Bean的时候使用初始化该Bean,否则不初始化。
我们可以自定义一个配置类覆盖默认配置,如下:
@Configuration
public class RibbonConfiguration{
@Bean
public IRule ribbonRule(){
return new RandomRule();
}
}
上面的配置是针对全局的配置,如果只想自定义一个Ribbon客户端的配置,那么该配配置类不能包含在主程序应用上下文的@ComponentScan中,单个配置入下:
@Configuration
@RibbonClient(name="HELLO-SERVICE",configuration=RibbonConfiguration.class)
public class test{}
使用属性自定义Ribbon配置:
这种方式比使用JAVA配置更简单。
<client>.ribbon