场景
在spring cloud gateway中,新增了负载均衡策略(修改同理),大多情况是使用“service.ribbon.NFLoadBalancerRuleClassName=IRule.class”进行配置,这种方式只针对单个服务,因为我们服务比较多,单个服务配置太过繁琐,所以想通过修改Ribbon的默认配置达到目的。
方案
通过查找文档:Spring Cloud Netflix
发现@RibbonClients标签,是对Ribbon的默认配置修改。
支持修改下列配置
返回值 | 方法名 | 默认值 |
---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
使用格式如下,也可以参考org.springframework.cloud.netflix.ribbon.RibbonClientConfiguration中的方法。
@Bean
public 返回类型 方法名() {
return new 默认值对象();//可以用继承实现类型
}
实现如下:
- 新建默认配置,设置ribbonRule方法设置默认负载规则。
import com.lizz.loadbalancer.VersionRoundRobinRule; import com.netflix.client.config.IClientConfig; import com.netflix.loadbalancer.IRule; import org.springframework.beans.factory.annotation.Configurable; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * @description: 调整ribbon默认配置 * 原始默认org.springframework.cloud.netflix.ribbon.RibbonClientConfiguration * @author: lizz */ @Configuration(proxyBeanMethods = false) public class RibbonConfiguration { @RibbonClientName private String name = "client"; @Bean public IRule ribbonRule() { //自定义负载规则 return new VersionRoundRobinRule(); } @Bean @ConditionalOnMissingBean public IClientConfig ribbonClientConfig() { DefaultClientConfigImpl config = new DefaultClientConfigImpl(); config.loadProperties(this.name); config.set(CommonClientConfigKey.ConnectTimeout, DEFAULT_CONNECT_TIMEOUT); config.set(CommonClientConfigKey.ReadTimeout, DEFAULT_READ_TIMEOUT); config.set(CommonClientConfigKey.GZipPayload, DEFAULT_GZIP_PAYLOAD); config.set(CommonClientConfigKey.ServerListRefreshInterval, 5000); return config; } }
- 使用@RibbonClients启用Ribbon默认配置
注意:import com.lizz.gateway.config.RibbonConfiguration; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.ribbon.RibbonClients; /** * 程序启动类 * * @author: lizz */ @SpringBootApplication @RibbonClients(defaultConfiguration = RibbonConfiguration.class) public class GatewayApplication { public static void main(String[] args) { SpringApplication.run(GatewayApplication.class, args); } }
- RibbonClients设置的必须为@Configuration类
- 该@Configuration类不能被@ComponentScan引用,不能与@SpringBootApplication类在同一个包下。否则将作为共享方法使用,无法针对单个服务配置。