Ribbon服务详解

1、Ribbon客户端负载均衡,maven

    org.springframework.cloud
    spring-cloud-starter-ribbon
    1.3.1.RELEASE

2、代码引入

  只需要在RestTemplate的bean上面加入@LoadBalanced注解即可在使用RestTemplate发送HTTP请求时,自动实现负载均衡调用

@LoadBalanced
@Bean
public RestTemplate restTemplate(){
    return new RestTemplate();

}

3、负载均衡策略

负载均衡器,需要配置两样东西:

1、服务地址列表——谁来参选?

2、选择策略规则——怎么选?

第二步,按照服务方的地址端口列表,配置一个Server的List。添加给负载均衡器。

第三步,构造或选择一个IRule实现类,通过ConfigurationMannager来配置【客户端名称】.ribbon.NFLoadBalancerRuleClassName属性,将配置键赋予一个规则类。

这里我们不操作,使用默认的 RoundRobinRule。

4、负载均衡的两种配置方法:

一种直接调用ConfigurationManager获取配置实例,然后设置配置属性;

public class MyIRule { 
      @Bean public IRule rule() {
              return new RandomRule();
      }
}

@EnableDiscoveryClient
// name是服务提供者名,configuration是我们配置的负载均衡策略
@RibbonClient(name="cloud-provider",configuration = MyIRule.class)
public class CloudConsumerApplication {
    public static void main(String[] args) {
        SpringApplication.run(CloudConsumerApplication.class, args);
    }
}
 

一种是在application.yml中配置。

ribbon配置文件添加:
service-B.ribbon.NFLoadBalancerRuleClassName=com.netflix.loadbalancer.RandomRule
其中service-B是我注册到Eureka的serviceID

5、总结:

    1)用户创建RestTemplate

    2)添加了ribbon依赖后,会在项目启动的时候自动往RestTemplate中添加LoadBalancerInterceptor拦截器

    3)用户根据RestTemplate发起请求时,会将请求转发到LoadBalancerInterceptor去执行,该拦截器会根据指定的负载均衡方式获取该次请求对应的应用服务端IP、port

    4)根据获取到的IP、port重新封装请求,发送HTTP请求,返回具体响应

6、负载均衡器LoadBalancerClient

addServers():用于添加一个Server集合。
chooseServer():用于根据key去获取Server。
markServerDown():用于标记某个服务下线。
getReachableServers():获取可用的Server集合。
getAllServers():获取所有的Server集合。

BestAvailableRule:选择最小请求值。
ClientConfigEnableRoundRobinRule:轮循。
RandomRule:随机选择一个server。
RoundRobinRule:轮循选择server。
RetryRule:根据轮循的方式重试。
WeightedResponseTimeRule:根据响应时间去分配一个weight,weight越低,被选择的可能性就越低。
ZoneAvoidanceRule:根据server的zone区域和可用性来轮循选择。

 

你可能感兴趣的:(springcloud)