1、在使用spring-cloud-netflix-ribbon的时候我们可以使用如下的配置方式来进行配置
#配置order-service 服务的地址
order-service.ribbon.listOfServers=http://localhost:7071,http://localhost:7072#请求连接超时时间,实现原理是通过设置请求的http.connection.timeout
ribbon.ConnectTimeout=1800#请求处理的超时时间,实现原理是通过设置请求的http.socket.timeout来实现的
ribbon.ReadTimeout=500#是否对所有操作请求都进行重试
order-service.ribbon.OkToRetryOnAllOperations=false#切换实例的重试次数
order-service.ribbon.MaxAutoRetriesNextServer=3#对当前实例的重试次数
order-service.ribbon.maxAutoRetries=2
这种配置方式就是在配置名称=order-service 的ribbonClient
当然我们也可以通过@RibbonClient来进行配置:
@Configuration
@RibbonClients(value = {@RibbonClient(name = "order-service", configuration = {MyRibbonClientConfiguration.OrderRibbonClientConfiguration.class}),@RibbonClient(name = "product-service",configuration = {MyRibbonClientConfiguration.OrderRibbonClientConfiguration.class})},defaultConfiguration = {MyRibbonClientConfiguration.OrderRibbonClientConfiguration.class}
)
public class MyRibbonClientConfiguration {@Configurationpublic class OrderRibbonClientConfiguration {public static final int DEFAULT_CONNECT_TIMEOUT = 1000;public static final int DEFAULT_READ_TIMEOUT = 1000;public static final boolean DEFAULT_GZIP_PAYLOAD = true;@RibbonClientNameprivate String name = "client";@Autowiredprivate PropertiesFactory propertiesFactory;@Bean@ConditionalOnMissingBeanpublic 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);return config;}@Bean@ConditionalOnMissingBeanpublic 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;}@Bean@ConditionalOnMissingBeanpublic IPing ribbonPing(IClientConfig config) {if (this.propertiesFactory.isSet(IPing.class, name)) {return this.propertiesFactory.get(IPing.class, config, name);}return new DummyPing();}@Bean@ConditionalOnMissingBean@SuppressWarnings("unchecked")public ServerList<Server> ribbonServerList(IClientConfig config) {if (this.propertiesFactory.isSet(ServerList.class, name)) {return this.propertiesFactory.get(ServerList.class, config, name);}ConfigurationBasedServerList serverList = new ConfigurationBasedServerList();serverList.initWithNiwsConfig(config);return serverList;}}
}
2、配置注意点:
#开启使用 http client 进行请求发送,注意不开启的话超时时间将会失效。 # !!!!注意单独是用ribbon的时候只有开启ribbon.http.client.enabled 或者ribbon.restclient.enabled的时候如下功能才生效: # 1、ConnectTimeout # 2、ReadTimeout # 3、重试相关的功能#ribbon.http.client.enabled=true #ribbon.restclient.enabled=true