再引入Spring Cloud Ribbon组件的时候会自动化构建下面这些接口的实现。
针对一些个性化设置需求,我们可以方便替换上述实现。只需要在Spring Boot应用中创建对应的实现就能覆盖默认的配置实现。如下:
根据属性文件配置Ribbon
配置属性的格式如下:
<clientName>.<nameSpace>.<propertyName>=<value>
<clientName>:这是调用ribbon的客户端名称(服务名称),如果此值为没有配置,则此条属性会作用到所有的客户端。
<nameSpace>:默认值为 “ribbon”
<propertyName>:所有的可用的属性都在com.netflix.client.conf.CommonClientConfigKey。
如果没有配置任何属性Ribbon会默认使用com.netflix.client.config.DefaultClientConfigImpl里的值,反之会替换成你配置的值。
下面是对客户端名称为HELLO-SERVICE配置属性的demo
# Max number of retries on the same server (excluding the first try)
HELLO-SERVICE.ribbon.MaxAutoRetries=1
# Max number of next servers to retry (excluding the first server)
HELLO-SERVICE.ribbon.MaxAutoRetriesNextServer=1
# Whether all operations can be retried for this client
HELLO-SERVICE.ribbon.OkToRetryOnAllOperations=true
# Interval to refresh the server list from the source
HELLO-SERVICE.ribbon.ServerListRefreshInterval=2000
# Connect timeout used by Apache HttpClient
HELLO-SERVICE.ribbon.ConnectTimeout=3000
# Read timeout used by Apache HttpClient
HELLO-SERVICE.ribbon.ReadTimeout=3000
# Initial list of servers, can be changed via Archaius dynamic property at runtime
HELLO-SERVICE.listOfServers=localhost:8080,localhost:8081,localhost:8082
注:HELLO-SERVICE.listOfServers的作用是在没有引入Eureka依赖的时候需要手动指定HELLO-SERVICE服务的实例清单。
通过配置文件指定Ribbon组件
使用以下属性值可以配置ribbon组合接口使用哪个具体的实现类,比如:
<clientName>.<nameSpace>.NFLoadBalancerClassName=xx
<clientName>.<nameSpace>.NFLoadBalancerRuleClassName=com.netflix.loadbalancer.WeightedResponseTimeRule #例子
<clientName>.<nameSpace>.NFLoadBalancerPingClassName=xx
<clientName>.<nameSpace>.NIWSServerListClassName=xx
<clientName>.<nameSpace>.NIWSServerListFilterClassName=xx
关于每个属性可以配置的实现类,可以通过这篇博文查看https://blog.csdn.net/hry2015/article/details/78357990
同时引入Spring Cloud Eureka 依赖和Spring Cloud Ribbon依赖
在与Spring Cloud Eureka结合使用时不再需要类似HELLO-SERVICE.listOfServers的参数来指定具体的服务实例清单,因为Eureka会为我们维护所有的实例清单,而对于Ribbon参数的配置依然可以使用上面介绍的方式进行配置。另外,由于Spring Cloud Ribbon默认实现了区域亲和策略,我们可以通过Eureka实例的元数据配置来实现区域化的实例配置方法,比如将处于不同机房的实例配置成不同的区域值:
eureka:
instance:
metadata-map:
zone: shanghai
重试机制
由于Spring Cloud Eureka在触发保护机制或者剔除失效服务的延迟性,导致某些故障服务的实例仍然存在于服务实例清单,并调用这些服务实例,我们可以加上重试机制。
对于重试机制,并不建议开启,避免因为服务接口没做幂等性导致的隐患。
参考:《Spring Cloud微服务实战》——翟永超