美文网首页
springcloud-ribbon负载均衡

springcloud-ribbon负载均衡

作者: jiahzhon | 来源:发表于2020-07-08 14:37 被阅读0次

什么是ribbon

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

LB

  • 即负载均衡(Load Balance),在微服务或分布式集群中经常用的一种应用。
  • 负载均衡简单的说就是将用户的请求平摊地分配到多个服务上,从而达到系统的HA。常见的负载均衡有软件Nginx,LVS,硬件F5等。
  • 相应的在中间件,例如:dubbbo和springCloud中均给我们提供了负载均衡,springcloud的负载均衡算法可以自定义

初步配置(服务消费者端中)

  • 架构图:


    image.png
  • 上Eureka服务端看到的服务提供者:


    image.png
    1. pom.xml中(使用ribbon要集成eureka)
  <!-- Ribbon相关 -->
  <dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-eureka</artifactId>
  </dependency>
  <dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-ribbon</artifactId>
  </dependency>
  <dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-config</artifactId>
  </dependency>
    1. application.yml中(注册到eureka)
eureka:
  client:
    register-with-eureka: false
    service-url: 
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/,http://eureka7003.com:7003/eureka/  
    1. 启动类添加@EnableEurekaClient
    1. 请求用到的RestTemplate(@LoadBalanced)
@Configuration
public class ConfigBean //boot -->spring   applicationContext.xml --- @Configuration配置   ConfigBean = applicationContext.xml
{ 
 @Bean
 @LoadBalanced//Spring Cloud Ribbon是基于Netflix Ribbon实现的一套客户端       负载均衡的工具。
 public RestTemplate getRestTemplate()
 {
  return new RestTemplate();
 }
}
  • 5:Controller中(注意请求的服务地址,是配置中spring-application-name的对外暴露的统一的服务实例名)
@RestController
public class DeptController_Consumer
{

 //private static final String REST_URL_PREFIX = "http://localhost:8001";
 private static final String REST_URL_PREFIX = "http://MICROSERVICECLOUD-DEPT";

 /**
  * 使用 使用restTemplate访问restful接口非常的简单粗暴无脑。 (url, requestMap,
  * ResponseBean.class)这三个参数分别代表 REST请求地址、请求参数、HTTP响应转换被转换成的对象类型。
  */
 @Autowired
 private RestTemplate restTemplate;

 @RequestMapping(value = "/consumer/dept/add")
 public boolean add(Dept dept)
 {
  return restTemplate.postForObject(REST_URL_PREFIX + "/dept/add", dept, Boolean.class);
 }

}

核心组件IRule

  • 根据特定算法中从服务列表中选取一个要访问的服务。
  • 在配置类中添加IRULE
@Configuration
public class ConfigBean //boot -->spring   applicationContext.xml --- @Configuration配置   ConfigBean = applicationContext.xml
{ 
 @Bean
 @LoadBalanced//Spring Cloud Ribbon是基于Netflix Ribbon实现的一套客户端       负载均衡的工具。
 public RestTemplate getRestTemplate()
 {
  return new RestTemplate();
 }
 
 @Bean
 public IRule myRule()
 {
  //return new RoundRobinRule();
  //return new RandomRule();//达到的目的,用我们重新选择的随机算法替代默认的轮询。
  return new RetryRule();
 }
}
  • 分类
    • RoundRobinRule - 轮询
    • RamdomRule - 随机
    • AvailabilityFilteringRule - 会先过滤由于多次访问故障而处于断路器跳闸状态的服务,还有并发的连接数量超过阀值得服务,然后对剩余的服务列表按照轮询策略进行访问。
    • WeightedResponseTimeRule - 根据平均响应时间计算所有服务的权重,响应时间越快服务权重越大被选中的概率越高。刚启动时如果统计信息不足,则使用RoundRobinRule策略,等统计信息足够,会切换到WeightedResponseTimeRule。
    • RetryRule - 先按照RoundRobinRule的策略获取服务,如果获取服务失败则在制定时间会进行重试,获取可用的服务。
    • BestAvailableRule - 会先过滤由于多次访问故障而处于断路器跳闸状态的服务,然后选择一个并发量最小的服务。
    • ZoneAvoidanceRule - 默认规则,复合判断server所在区域的性能和server的可用性选择服务器。

自定义负载均衡策略

  • 1:修改接收服务的项目的启动类(name 是对应的提供服务的应用)
@SpringBootApplication
@EnableEurekaClient
//在启动该微服务的时候就能去加载我们的自定义Ribbon配置类,从而使配置生效
@RibbonClient(name="MICROSERVICECLOUD-DEPT",configuration=MySelfRule.class)
public class DeptConsumer80_App
{
 public static void main(String[] args)
 {
  SpringApplication.run(DeptConsumer80_App.class, args);
 }
}
  • 2 : 自定义配置类
    • 官方文档明确给出了警告:这个自定义配置类不能放在@ComponentScan所扫描的当前包以及子包下,否则我们自定义的这个配置类就会被所有的Ribbon客户端所共享,也就是说我们达不到特殊化定制的目的了。
@Configuration
public class MySelfRule
{
 @Bean
 public IRule myRule()
 {
  return new RandomRule_ZY();// 我自定义为每台机器5次
 }
}
  • 自定义的负载均衡算法
import java.util.List;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;

public class RandomRule_ZY extends AbstractLoadBalancerRule
{

 // total = 0 // 当total==5以后,我们指针才能往下走,
 // index = 0 // 当前对外提供服务的服务器地址,
 // total需要重新置为零,但是已经达到过一个5次,我们的index = 1
 // 分析:我们5次,但是微服务只有8001 8002 8003 三台,OK?
 // 
 
 
 private int total = 0;    // 总共被调用的次数,目前要求每台被调用5次
 private int currentIndex = 0; // 当前提供服务的机器号

 public Server choose(ILoadBalancer lb, Object key)
 {
  if (lb == null) {
   return null;
  }
  Server server = null;

  while (server == null) {
   if (Thread.interrupted()) {
    return null;
   }
   List<Server> upList = lb.getReachableServers();
   List<Server> allList = lb.getAllServers();

   int serverCount = allList.size();
   if (serverCount == 0) {
    /*
     * No servers. End regardless of pass, because subsequent passes only get more
     * restrictive.
     */
    return null;
   }

//   int index = rand.nextInt(serverCount);// java.util.Random().nextInt(3);
//   server = upList.get(index);

   
//   private int total = 0;    // 总共被调用的次数,目前要求每台被调用5次
//   private int currentIndex = 0; // 当前提供服务的机器号
            if(total < 5)
            {
             server = upList.get(currentIndex);
             total++;
            }else {
             total = 0;
             currentIndex++;
             if(currentIndex >= upList.size())
             {
               currentIndex = 0;
             }
            }   
   
   
   if (server == null) {
    /*
     * The only time this should happen is if the server list were somehow trimmed.
     * This is a transient condition. Retry after yielding.
     */
    Thread.yield();
    continue;
   }

   if (server.isAlive()) {
    return (server);
   }

   // Shouldn't actually happen.. but must be transient or a bug.
   server = null;
   Thread.yield();
  }

  return server;

 }

 @Override
 public Server choose(Object key)
 {
  return choose(getLoadBalancer(), key);
 }

 @Override
 public void initWithNiwsConfig(IClientConfig clientConfig)
 {
  // TODO Auto-generated method stub

 }

}

相关文章

网友评论

      本文标题:springcloud-ribbon负载均衡

      本文链接:https://www.haomeiwen.com/subject/xhkccktx.html