1:Ribbon是什么
Ribbon是一个开源的客户端负载均衡器,由Netflix发布,是SpringCloud-Netflix中重要的一环,通过它将Netflix的中间层服务连接在一起。
Ribbon客户端组件提供一系列完善的配置项,如连接超时、重试等。简单的说,就是在配置文件中列出Load Balancer后面所有的服务,Ribbon会自动的基于某种规则(如简单轮询,随机连接等)去连接这些服务,也很容易实现自定义的负载均衡算法。
2:Ribbon能干什么
Ribbon是在客户端来实现负载均衡的访问服务,主要的功能点:
- 服务发现,发现依赖服务的列表
- 服务选择规则,在多个服务中如何选择一个有效服务
- 服务监听,检测失效的服务,高效剔除失效服务
3:代码实例
加入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-ribbon</artifactId>
</dependency>
官方的HelloWorld具体示例参看:
https://github.com/Netflix/ribbon/wiki/Getting-Started
4:参数配置
4.1:概述
对于Ribbon参数的key以及value类型的定义,可以通过com.netflix.client.config.CommonClientConfigKey查看
如果你没有配置任何属性,则ribbon会使用com.netflix.client.config.DefaultClientConfigImpl里的值
4.2:配置方式
Ribbon的参数配置通常有二种方式:全局配置以及指定客户端配置
- 全局配置的方式很简单只需要使用ribbon.=格式进行配置即可。
其中,代表了Ribbon客户端配置的参数名,则代表了对应参数的值。
比如,可以向下面这样配置Ribbon的超时时间:
ibbon.ConnectTimeout=250
全局配置可以作为默认值进行设置,当指定客户端配置了相应的key的值时,将覆盖全局配置的内容 - 指定客户端的配置方式
.ribbon.=的格式进行配置
表示服务名,比如没有服务治理框架的时候(如Eureka),需要指定实例清单,如:userService.ribbon.listOfServers=localhost:8080
4.3:配置示例my.properties:
# Max number of retries on the same server (excluding the first try)
hello-client.ribbon.MaxAutoRetries=1
# Max number of next servers to retry (excluding the first server)
hello-client.ribbon.MaxAutoRetriesNextServer=1
# Whether all operations can be retried for this client
hello-client.ribbon.OkToRetryOnAllOperations=true
# Interval to refresh the server list from the source
hello-client.ribbon.ServerListRefreshInterval=2000
# Connect timeout used by Apache HttpClient
hello-client.ribbon.ConnectTimeout=3000
# Readtimeout used by Apache HttpClient
hello-client.ribb