【SpringBoot】SpringBoot 之Ribbon服务调用 【SpringCloud】SpringCloud 服务提供者集群与服务发现Discovery(三)

Ribbon介绍

  Spring Cloud Ribbon是基于Netflix Ribbon实现的一套客户端负载均衡的工具

  Ribbon是Netflix发布的开源项目,主要功能是提供客户端的软件负载均衡算法和服务调用。Ribbon客户端组件提供一系列完善的配置项如连接超时、重试等。简单的说,就是在配置文件中列出Load Balance(简称LB)后面所有的机器,Ribbon会自动的帮组你基于某种规则(如简单轮询,随机连接等)去连接这些机器,我们很容易使用Ribbon实现自定义的负载均衡算法

  LB负载均衡(Load Balance)

  简单的说就是将用户的请求平摊到分配到多个服务上,从而达到系统的HA(高可用)。

  常见的负载均衡有软件Nginx、LVS、硬件FS等

  Ribbon本地负载均衡客户端 VS Nginx服务端负载均衡区别

  Nginx是服务器负载均衡,客户端所有请求都会教给Nginx,然后由nginx实现转发请求,即负载均衡是由服务端实现的

  Ribbon本地负载均衡,在调用微服务接口时候,会在注册中心上获取注册信息服务列表之后缓存到JVM本地,从而本地实现RPC远程调用技术

  官网:https://github.com/Netflix/ribbon

Ribbon使用

  1、搭建项目、参考【SpringCloud】SpringCloud 服务提供者集群与服务发现Discovery(三)的示例

    采用Eureka作为注册中心,且有2个服务提供者

    架构如下:

    

  2、Ribbon依赖,依赖如下:

1 <dependency>
2     <groupId>org.springframework.cloud</groupId>
3     <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
4     <version>2.2.2.RELEASE</version>
5     <scope>compile</scope>
6 </dependency>

    通过查看示例项目,调用者order项目依赖,发现在Eureka依赖中,默认含有依赖Ribbon的依赖

       

  3、查看RibbonClientConfiguration.java,Ribbon自动装载类。

 1 @Configuration(proxyBeanMethods = false)
 2 @EnableConfigurationProperties
 3 @Import({ HttpClientConfiguration.class, OkHttpRibbonConfiguration.class,
 4         RestClientRibbonConfiguration.class, HttpClientRibbonConfiguration.class })
 5 public class RibbonClientConfiguration {
 6 
 7     ...
 8 
 9     // 自动注入IRule接口用来代表负责负载均衡的策略
10     @Bean
11     @ConditionalOnMissingBean
12     public IRule ribbonRule(IClientConfig config) {
13         if (this.propertiesFactory.isSet(IRule.class, name)) {
14             return this.propertiesFactory.get(IRule.class, config, name);
15         }
16         ZoneAvoidanceRule rule = new ZoneAvoidanceRule();
17         rule.initWithNiwsConfig(config);
18         return rule;
19     }
20 
21     // 自动注入ILoadBalance接口用来代表负责均衡的操作
22     @Bean
23     @ConditionalOnMissingBean
24     public ILoadBalancer ribbonLoadBalancer(IClientConfig config,
25             ServerList<Server> serverList, ServerListFilter<Server> serverListFilter,
26             IRule rule, IPing ping, ServerListUpdater serverListUpdater) {
27         if (this.propertiesFactory.isSet(ILoadBalancer.class, name)) {
28             return this.propertiesFactory.get(ILoadBalancer.class, config, name);
29         }
30         return new ZoneAwareLoadBalancer<>(config, rule, ping, serverList,
31                 serverListFilter, serverListUpdater);
32     }
33 
34     ...
35 }

     其中自动注入IRule接口用来代表负责负载均衡的策略(默认策略:ZoneAvoidanceRule),和自动注入ILoadBalance接口用来代表负责均衡的操作(默认均衡:ZoneAwareLoadBalancer)

  4、查看ILoadBalance接口

  5、查看IRule接口

自带负载均衡规则说明

  

猜你喜欢

转载自www.cnblogs.com/h--d/p/12684613.html