Skip to content

Commit 48f8614

Browse files
committed
add readme in spring cloud consul & ribbon sample
1 parent 5a7e683 commit 48f8614

File tree

6 files changed

+292
-5
lines changed

6 files changed

+292
-5
lines changed
Lines changed: 229 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,229 @@
1+
# SpringCloud集成Consul+Ribbon框架-实现注册中心和负载均衡
2+
3+
### Consul注册中心部分请参考如下教程
4+
- ##### [SpringCloud集成Consul框架-实现注册中心;](https://github.com/ipipman/JavaSpringBootSamples/tree/master/springcloud-consul-register-sample "SpringCloud集成Consul框架-实现注册中心")
5+
6+
### 什么是Ribbon?
7+
Ribbon是Netflix公司开源的基于客户端的负载均衡组件,可以简单理解成类似于Nginx的负载均衡模块的功能,它是Spring Cloud中非常重要的模块。在为分布式场景中,Ribbon与注册中心配合,为客户端调用远程服务提供了Load Balance负载均衡策略;
8+
9+
#### 主流的Load Balance方案分为两类
10+
> - 一种是集中式Load Balance,即在服务的消费方和提供方直接使用独立的LB设施(如ngixn、h5),由该设施方负责把访问请求通过某种策略转发至服务端。
11+
> - 另一种是进程内的Load Balance,将LB逻辑集成到消费方,消费方从服务注册中心获取有哪些服务地址可用,然后自己再从这些地址中选择出一个合适的服务器地址。Ribbon和Dubbo LoadBalance都属于这种方式,它只是一个类库,集成于消费方进程中,消费方通过它来获取到服务提供方地址。
12+
13+
#### 使用负载均衡的好处
14+
当集群里的某台服务器宕机的时候,剩余的没有宕机服务可以保证服务继续使用。
15+
更加方便合理使用了更多的机器保证了良性使用,不会由于某一高峰时刻导致系统崩溃。
16+
17+
**负载均衡具有的负载算法如下**
18+
> - 随机的(Random)
19+
> - 轮询(RoundRobin)
20+
> - 一致性哈希(ConsistentHash)
21+
> - 哈希(Hash)
22+
> - 加权(Weighted)
23+
24+
#### Ribbon的核心接口组成部分
25+
| 接口 | 作用 | 默认值 |
26+
| ------------ | ------------ | ------------ | ------------ |
27+
| IClientConfig | 读取配置 | DefultClientConfigImpl |
28+
| IRule | 负载均衡规则,选择实例 | ZoneAvoidanceRule |
29+
| IPing | 筛选掉Ping不通的实例 | DummyPing |
30+
| ServerList<Server> | 交给Ribbon的实例列表 | 来源Eureka、Nacos、Consul等注册中心 |
31+
| ServerFiter<Server> | 过滤不符合条件的实例 | ZonePreferenceServerListFilter |
32+
| ILoadBalance | Ribbon的入口 | ZoneAwareLoadBalance |
33+
| ServerListUpdater | 更新交给Ribbon的List策略 | PollingServerListUpdater |
34+
35+
Ribbon是比较灵活的,它对所有的组件都定义成了接口,如果对默认值不满意,可以实现这些接口配置一下,就可以将默认实现替换掉
36+
37+
#### ILoadBalance 负载均衡器
38+
Ribbon是一个为客户端提供负载均衡功能的服务,他内部提供了一个叫ILoadBalance的接口代表负载均衡器的操作,比如添加服务操作、选择服务器操作、获取所有的服务器列表、获取可用的服务器列表等等。
39+
40+
#### ILoadBalance 的实现类源码分析
41+
<img src="https://ipman-blog-1304583208.cos.ap-nanjing.myqcloud.com/dubbo/1161609242294_.pic.jpg" width = "440" height = "400" alt="图片名称" align=center />
42+
43+
负载均衡器可以从服务发现组建(NacosDiscoveryClient、ConsulDisconveryClient、EurekaClient)获取服务信息,根据IRule去路由,并且根据IPing判断服务的可用性。
44+
45+
在BaseLoadBalance类构造函数中,开启了一个PingTask任务setupPingTask();
46+
```java
47+
public BaseLoadBalancer(String name, IRule rule, LoadBalancerStats stats, IPing ping, IPingStrategy pingStrategy) {
48+
this.rule = DEFAULT_RULE;
49+
this.pingStrategy = DEFAULT_PING_STRATEGY;
50+
this.ping = null;
51+
this.allServerList = Collections.synchronizedList(new ArrayList());
52+
this.upServerList = Collections.synchronizedList(new ArrayList());
53+
this.allServerLock = new ReentrantReadWriteLock();
54+
this.upServerLock = new ReentrantReadWriteLock();
55+
this.name = "default";
56+
this.lbTimer = null;
57+
this.pingIntervalSeconds = 10;
58+
this.maxTotalPingTimeSeconds = 5;
59+
this.serverComparator = new ServerComparator();
60+
this.pingInProgress = new AtomicBoolean(false);
61+
this.counter = Monitors.newCounter("LoadBalancer_ChooseServer");
62+
this.enablePrimingConnections = false;
63+
this.changeListeners = new CopyOnWriteArrayList();
64+
this.serverStatusListeners = new CopyOnWriteArrayList();
65+
logger.debug("LoadBalancer [{}]: initialized", name);
66+
this.name = name;
67+
this.ping = ping;
68+
this.pingStrategy = pingStrategy;
69+
this.setRule(rule);
70+
this.setupPingTask();
71+
this.lbStats = stats;
72+
this.init();
73+
}
74+
```
75+
76+
setupPingTask()开启了ShutdownEnabledTimer执行PingTask任务,在默认情况下pingIntervalSeconds为10,即每10秒,向EurekaClient、NacosClient、ConsulClient等发送一次“ping”任务。
77+
```java
78+
void setupPingTask() {
79+
if (!this.canSkipPing()) {
80+
if (this.lbTimer != null) {
81+
this.lbTimer.cancel();
82+
}
83+
84+
this.lbTimer = new ShutdownEnabledTimer("NFLoadBalancer-PingTimer-" + this.name, true);
85+
this.lbTimer.schedule(new BaseLoadBalancer.PingTask(), 0L, (long)(this.pingIntervalSeconds * 1000));
86+
this.forceQuickPing();
87+
}
88+
}
89+
```
90+
91+
PingTask源码,即new一个Pinger对象,并执行runPinger()方法。
92+
93+
查看Pinger的runPinger()方法,最终根据pingerStrategy.pingServers(ping, allServers)来获取服务的可用性,如果该返回结果相同,则不去向EurekaClient、NacosClient、ConsulClient获取注册列表,如果不同则通知ServerStatusChangeListener或者changeListeners发生了改变,进行更新或者重新拉取。
94+
95+
完整过程是:
96+
LoadBalancerClient(RibbonLoadBalancerClient是实现类)在初始化的时候(execute方法),会通过ILoadBalance(BaseLoadBalancer是实现类)向Eureka注册中心获取服务注册列表,并且每10s一次向EurekaClient、NacosClient、ConsulClient等发送“ping”,来判断服务的可用性,如果服务的可用性发生了改变或者服务数量和之前的不一致,则从注册中心更新或者重新拉取。LoadBalancerClient有了这些服务注册列表,就可以根据具体的IRule来进行负载均衡。
97+
98+
#### IRule 路由
99+
IRule接口代表负载均衡策略:
100+
```java
101+
public interface IRule {
102+
Server choose(Object var1);
103+
void setLoadBalancer(ILoadBalancer var1);
104+
ILoadBalancer getLoadBalancer();
105+
}
106+
```
107+
#### Ribbon内置的负载均衡规则:
108+
| 规则名称 | 特点 |
109+
| ------------ | ------------ | ------------ |
110+
| RandomRule | 随机选择一个Server |
111+
| RoundRobinRule | 轮询选择,轮询index,选择index对应位置的Server |
112+
| WeightedResponseTimeRule | 根据响应时间加权,响应时间越长,权重越小,被选中的可能性越低 |
113+
| BestAvailableRule | 选择一个最小的并发请求的server,逐个考察server,如果Server被tripped了,则跳过 |
114+
| ... | | |
115+
116+
117+
- 随机策略很简单,就是从服务器中随机选择一个服务器,RandomRule的实现代码如下
118+
- RoundRobinRule轮询策略表示每次都取下一个服务器,比如一共有5台服务器,第1次取第1台,第2次取第2台,第3次取第3台,以此类推;
119+
- WeightedResponseTimeRule继承了RoundRobinRule,开始的时候还没有权重列表,采用父类的轮询方式,有一个默认每30秒更新一次权重列表的定时任务,该定时任务会根据实例的响应时间来更新权重列表,choose方法做的事情就是,用一个(0,1)的随机double数乘以最大的权重得到randomWeight,然后遍历权重列表,找出第一个比randomWeight大的实例下标,然后返回该实例.
120+
- BestAvailableRule策略用来选取最少并发量请求的服务器
121+
122+
123+
### SpringCloud集成Consul+Ribbon框架-实现注册中心和负载均衡实战
124+
#### 1.参考Consul注册中心部分请参考如下教程,启动Conusl集群与服务提供者
125+
- ##### [SpringCloud集成Consul框架-实现注册中心;](https://github.com/ipipman/JavaSpringBootSamples/tree/master/springcloud-consul-register-sample "SpringCloud集成Consul框架-实现注册中心")
126+
127+
#### 2.添加Ribbon依赖
128+
```java
129+
<dependency>
130+
<groupId>org.springframework.cloud</groupId>
131+
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
132+
<version>2.1.4.RELEASE</version>
133+
</dependency>
134+
```
135+
136+
#### 3.添加Ribbon和Consul相关配置
137+
```java
138+
server.port=8308
139+
spring.application.name=consul-ribbon-service
140+
141+
#consul注册中心地址
142+
spring.cloud.consul.host=10.211.55.8
143+
#consul注册中心端口
144+
spring.cloud.consul.port=8500
145+
#consul client注册名称
146+
spring.cloud.consul.discovery.service-name=${spring.application.name}
147+
148+
#需要启动provider服务:https://github.com/ipipman/JavaSpringBootSamples/tree/master/springcloud-consul-register-sample
149+
service.url.consul.provider.service=http://consul-provider-service
150+
151+
#开启Ribbon的饥饿加载模式
152+
ribbon.eager-load.enabled=true
153+
#指定需要饥饿加载的服务名
154+
ribbon.eager-load.clients=consul-provider-service
155+
#Ribbon的超时
156+
ribbon.ConnectTimeout=3000
157+
ribbon.ReadTimeout=60000
158+
#对第一次请求的服务的重试次数
159+
ribbon.MaxAutoRetries=1
160+
#要重试的下一个服务的最大数量(不包括第一个服务)
161+
ribbon.MaxAutoRetriesNextServer=1
162+
#无论是请求超时或者socket read timeout都进行重试
163+
ribbon.OkToRetryOnAllOperations=true
164+
#默认随机策略
165+
ribbon.NFLoadBalancerRuleClassName=com.netflix.loadbalancer.RandomRule
166+
```
167+
168+
#### 4.自定义Load Balance策略
169+
```java
170+
//Ribbon更细力度的配置,可以针对不同服务设置Load Balance策略
171+
@Configuration
172+
public class XXProviderRibbonConfig {
173+
174+
//BestAvailableRule策略用来选取最少并发量请求的服务器
175+
@Bean
176+
public IRule ribbonRule(){
177+
return new BestAvailableRule();
178+
}
179+
}
180+
```
181+
182+
```java
183+
@Configuration
184+
//RibbonClients可以配置多个服务策略
185+
@RibbonClients({
186+
//Ribbon更细力度的配置,可以针对不同服务设置Load Balance策略
187+
@RibbonClient(name = "consul-provider-service", configuration = XXProviderRibbonConfig.class)
188+
})
189+
public class RibbonConfig {
190+
191+
//使用RestTemplate进行rest操作的时候,会自动使用负载均衡策略,它内部会在RestTemplate中加入LoadBalancerInterceptor这个拦截器,这个拦截器的作用就是使用负载均衡。
192+
//默认情况下会采用轮询策
193+
@LoadBalanced
194+
@Bean
195+
public RestTemplate restTemplate() {
196+
return new RestTemplate();
197+
}
198+
}
199+
```
200+
201+
#### 5.在接口中使用Ribbon调用远程服务
202+
```java
203+
@RestController
204+
@RequestMapping("/consul")
205+
public class DemoController {
206+
207+
@Value("${service.url.consul.provider.service}")
208+
private String serviceUrl;
209+
210+
@Autowired
211+
private RestTemplate restTemplate;
212+
213+
//使用Ribbon全局维度的配置
214+
@GetMapping("/ribbon")
215+
public Object goService(String name) {
216+
return restTemplate.getForObject(serviceUrl + "/demo/hello?name={1}", String.class, name);
217+
}
218+
}
219+
```
220+
221+
#### 6.启动项目,进行测试
222+
```java
223+
% curl -l 'http://127.0.0.1:8308/consul/ribbon?name=ipman'
224+
Hello ipman, response from provider: http://192.168.1.4:8081
225+
```
226+
227+
#### 7.在Consul控制台查看Ribbon服务状态
228+
<img src="https://ipman-blog-1304583208.cos.ap-nanjing.myqcloud.com/dubbo/1171609255520_.pic.jpg" width = "740" height = "340" alt="图片名称" align=center />
229+

springcloud-consul-ribbon-sample/src/main/java/com/ipman/springcloud/consul/ribbon/sample/SpringcloundConsulRibbonSampleApplication.java renamed to springcloud-consul-ribbon-sample/src/main/java/com/ipman/springcloud/consul/ribbon/sample/SpringcloudConsulRibbonSampleApplication.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,10 @@
66

77
@SpringBootApplication
88
@EnableDiscoveryClient
9-
public class SpringcloundConsulRibbonSampleApplication {
9+
public class SpringcloudConsulRibbonSampleApplication {
1010

1111
public static void main(String[] args) {
12-
SpringApplication.run(SpringcloundConsulRibbonSampleApplication.class, args);
12+
SpringApplication.run(SpringcloudConsulRibbonSampleApplication.class, args);
1313
}
1414

1515
}

springcloud-consul-ribbon-sample/src/main/java/com/ipman/springcloud/consul/ribbon/sample/api/DemoController.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ public class DemoController {
2525
@Autowired
2626
private RestTemplate restTemplate;
2727

28+
//使用Ribbon全局维度的配置
2829
@GetMapping("/ribbon")
2930
public Object goService(String name) {
3031
return restTemplate.getForObject(serviceUrl + "/demo/hello?name={1}", String.class, name);

springcloud-consul-ribbon-sample/src/main/java/com/ipman/springcloud/consul/ribbon/sample/config/RibbonConfig.java

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,12 @@
11
package com.ipman.springcloud.consul.ribbon.sample.config;
22

3+
import com.netflix.loadbalancer.IPing;
4+
import com.netflix.loadbalancer.IRule;
5+
import com.netflix.loadbalancer.PingUrl;
6+
import com.netflix.loadbalancer.RandomRule;
37
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
8+
import org.springframework.cloud.netflix.ribbon.RibbonClient;
9+
import org.springframework.cloud.netflix.ribbon.RibbonClients;
410
import org.springframework.context.annotation.Bean;
511
import org.springframework.context.annotation.Configuration;
612
import org.springframework.web.client.RestTemplate;
@@ -13,12 +19,21 @@
1319
* @Description: (用一句话描述该文件做什么)
1420
* @date 2020/12/29 10:56 上午
1521
*/
22+
23+
1624
@Configuration
25+
//RibbonClients可以配置多个服务策略
26+
@RibbonClients({
27+
//Ribbon更细力度的配置,可以针对不同服务设置Load Balance策略
28+
@RibbonClient(name = "consul-provider-service", configuration = XXProviderRibbonConfig.class)
29+
})
1730
public class RibbonConfig {
1831

19-
@Bean
32+
//使用RestTemplate进行rest操作的时候,会自动使用负载均衡策略,它内部会在RestTemplate中加入LoadBalancerInterceptor这个拦截器,这个拦截器的作用就是使用负载均衡。
33+
//默认情况下会采用轮询策
2034
@LoadBalanced
21-
public RestTemplate restTemplate(){
35+
@Bean
36+
public RestTemplate restTemplate() {
2237
return new RestTemplate();
2338
}
2439
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package com.ipman.springcloud.consul.ribbon.sample.config;
2+
3+
import com.netflix.loadbalancer.BestAvailableRule;
4+
import com.netflix.loadbalancer.IRule;
5+
import org.springframework.cloud.netflix.ribbon.RibbonClient;
6+
import org.springframework.context.annotation.Bean;
7+
import org.springframework.context.annotation.Configuration;
8+
9+
/**
10+
* Created by ipipman on 2020/12/29.
11+
*
12+
* @version V1.0
13+
* @Package com.ipman.springcloud.consul.ribbon.sample.config
14+
* @Description: (用一句话描述该文件做什么)
15+
* @date 2020/12/29 10:54 下午
16+
*/
17+
//Ribbon更细力度的配置,可以针对不同服务设置Load Balance策略
18+
@Configuration
19+
public class XXProviderRibbonConfig {
20+
21+
//BestAvailableRule策略用来选取最少并发量请求的服务器
22+
@Bean
23+
public IRule ribbonRule(){
24+
return new BestAvailableRule();
25+
}
26+
}

springcloud-consul-ribbon-sample/src/main/resources/application.properties

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,4 +9,20 @@ spring.cloud.consul.port=8500
99
spring.cloud.consul.discovery.service-name=${spring.application.name}
1010

1111
#需要启动provider服务:https://github.com/ipipman/JavaSpringBootSamples/tree/master/springcloud-consul-register-sample
12-
service.url.consul.provider.service=http://consul-provider-service
12+
service.url.consul.provider.service=http://consul-provider-service
13+
14+
#开启Ribbon的饥饿加载模式
15+
ribbon.eager-load.enabled=true
16+
#指定需要饥饿加载的服务名
17+
ribbon.eager-load.clients=consul-provider-service
18+
#Ribbon的超时
19+
ribbon.ConnectTimeout=3000
20+
ribbon.ReadTimeout=60000
21+
#对第一次请求的服务的重试次数
22+
ribbon.MaxAutoRetries=1
23+
#要重试的下一个服务的最大数量(不包括第一个服务)
24+
ribbon.MaxAutoRetriesNextServer=1
25+
#无论是请求超时或者socket read timeout都进行重试
26+
ribbon.OkToRetryOnAllOperations=true
27+
#默认随机策略
28+
ribbon.NFLoadBalancerRuleClassName=com.netflix.loadbalancer.RandomRule

0 commit comments

Comments
 (0)