一:Ribbon是什么?

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

二:LB方案分类  

  目前主流的LB方案可分成两类:一种是集中式LB, 即在服务的消费方和提供方之间使用独立的LB设施(可以是硬件,如F5, 也可以是软件,如nginx), 由该设施负责把访问请求通过某种策略转发至服务的提供方;另一种是进程内LB,将LB逻辑集成到消费方,消费方从服务注册中心获知有哪些地址可用,然后自己再从这些地址中选择出一个合适的服务器。Ribbon就属于后者,它只是一个类库,集成于消费方进程,消费方通过它来获取到服务提供方的地址。

三:Ribbon的主要组件与工作流程

  Ribbon的核心组件(均为接口类型)有以下几个:

  ServerList:用于获取地址列表。它既可以是静态的(提供一组固定的地址),也可以是动态的(从注册中心中定期查询地址列表)。

  ServerListFilter:仅当使用动态ServerList时使用,用于在原始的服务列表中使用一定策略过虑掉一部分地址。

  IRule:选择一个最终的服务地址作为LB结果。选择策略有轮询、根据响应时间加权、断路器(当Hystrix可用时)等。

  Ribbon在工作时首选会通过ServerList来获取所有可用的服务列表,然后通过ServerListFilter过虑掉一部分地址,最后在剩下的地址中通过IRule选择出一台服务器作为最终结果。

四:Ribbon提供的主要负载均衡策略介绍

  1:简单轮询负载均衡(RoundRobin):以轮询的方式依次将请求调度不同的服务器,即每次调度执行i = (i + 1) mod n,并选出第i台服务器。

  2:随机负载均衡 (Random): 随机选择状态为UP的Server

  3:加权响应时间负载均衡 (WeightedResponseTime):根据相应时间分配一个weight,相应时间越长,weight越小,被选中的可能性越低。

  4:区域感知轮询负载均衡(ZoneAvoidanceRule):复合判断server所在区域的性能和server的可用性选择server

Ribbon自带负载均衡策略比较

五:Ribbon单独使用

  创建一个maven工程,名称是ribbon_client,pom的内容如下:

<dependencies>
<dependency>
<groupId>com.netflix.ribbon</groupId>
<artifactId>ribbon-core</artifactId>
<version>2.2.</version>
</dependency>
<dependency>
<groupId>com.netflix.ribbon</groupId>
<artifactId>ribbon-httpclient</artifactId>
<version>2.2.</version>
</dependency>
</dependencies>

sample-client.properties配置文件

# Max number of retries
sample-client.ribbon.MaxAutoRetries= # Max number of next servers to retry (excluding the first server)
sample-client.ribbon.MaxAutoRetriesNextServer= # Whether all operations can be retried for this client
sample-client.ribbon.OkToRetryOnAllOperations=true # Interval to refresh the server list from the source
sample-client.ribbon.ServerListRefreshInterval= # Connect timeout used by Apache HttpClient
sample-client.ribbon.ConnectTimeout= # Read timeout used by Apache HttpClient
sample-client.ribbon.ReadTimeout= # Initial list of servers, can be changed via Archaius dynamic property at runtime
sample-client.ribbon.listOfServers=www.sohu.com:,www..com:,www.sina.com.cn: sample-client.ribbon.EnablePrimeConnections=true

RibbonMain代码

import java.net.URI;

import com.netflix.client.ClientFactory;
import com.netflix.client.http.HttpRequest;
import com.netflix.client.http.HttpResponse;
import com.netflix.config.ConfigurationManager;
import com.netflix.loadbalancer.ZoneAwareLoadBalancer;
import com.netflix.niws.client.http.RestClient; public class RibbonMain {
public static void main( String[] args ) throws Exception {
ConfigurationManager.loadPropertiesFromResources("sample-client.properties");
System.out.println(ConfigurationManager.getConfigInstance().getProperty("sample-client.ribbon.listOfServers")); RestClient client = (RestClient)ClientFactory.getNamedClient("sample-client");
HttpRequest request = HttpRequest.newBuilder().uri(new URI("/")).build(); for(int i = ; i < ; i ++) {
HttpResponse response = client.executeWithLoadBalancer(request);
System.out.println("Status for URI:" + response.getRequestedURI() + " is :" + response.getStatus());
} ZoneAwareLoadBalancer lb = (ZoneAwareLoadBalancer) client.getLoadBalancer();
System.out.println(lb.getLoadBalancerStats()); ConfigurationManager.getConfigInstance().setProperty("sample-client.ribbon.listOfServers", "ccblog.cn:80,www.linkedin.com:80"); System.out.println("changing servers ...");
Thread.sleep(); for(int i = ; i < ; i ++) {
HttpResponse response = client.executeWithLoadBalancer(request);
System.out.println("Status for URI:" + response.getRequestedURI() + " is :" + response.getStatus());
}
System.out.println(lb.getLoadBalancerStats());
}
}

代码解析

  使用 Archaius ConfigurationManager 加载属性;

  使用 ClientFactory 创建客户端和负载均衡器;

  使用 builder 构建 http 请求。注意我们只支持 URI 的 "/" 部分的路径,一旦服务器被负载均衡器选中,会由客户端计算出完整的 URI;

  调用 API client.executeWithLoadBalancer(),不是 exeucte() API;

  动态修正配置中的服务器池;

  等待服务器列表刷新(配置文件中定义的刷新间隔是为 3 秒钟);

  打印出负载均衡器记录的服务器统计信息。

六:Ribbon结合eureka使用

  创建maven工程 eureka_ribbon_client 该工程启动和相关配置依赖:

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4..RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-ribbon</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Brixton.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

  在应用主类中,通过@EnableDiscoveryClient注解来添加发现服务能力。创建RestTemplate实例,并通过@LoadBalanced注解开启均衡负载能力。

@SpringBootApplication
@EnableDiscoveryClient
public class RibbonApplication {
@Bean
@LoadBalanced
RestTemplate restTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(RibbonApplication.class, args);
}
}

  创建ConsumerController来消费service01的getuser服务。通过直接RestTemplate来调用服务

@RestController
public class ConsumerController { @Autowired
RestTemplate restTemplate; @RequestMapping(value = "/getuserinfo", method = RequestMethod.GET)
public String add() {
return restTemplate.getForEntity("http://biz-service-0/getuser", String.class).getBody();
}
}

  Ribbon其实就是一个软负载均衡的客户端组件,他可以和其他所需请求的客户端结合使用,和eureka结合只是其中的一个实例。

SpringCloud之Ribbon的更多相关文章

  1. SpringCloud(4)---Ribbon服务调用,源码分析

    SpringCloud(4)---Ribbon 本篇模拟订单服务调用商品服务,同时商品服务采用集群部署. 注册中心服务端口号7001,订单服务端口号9001,商品集群端口号:8001.8002.800 ...

  2. spring-cloud配置ribbon负载均衡

    spring-cloud配置ribbon负载均衡 ribbon提供的负载均衡就是开箱即用的,简单的不能再简单了 为了顺利演示此demo,你需要如下 需要提前配置eureka服务端,具体看 https: ...

  3. 浅谈SpringCloud (三) Ribbon负载均衡

    什么是负载均衡 当一台服务器的单位时间内的访问量越大时,服务器压力就越大,大到超过自身承受能力时,服务器就会崩溃.为了避免服务器崩溃,让用户有更好的体验,我们通过负载均衡的方式来分担服务器压力. 我们 ...

  4. SpringCloud系列——Ribbon 负载均衡

    前言 Ribbon是一个客户端负载均衡器,它提供了对HTTP和TCP客户端的行为的大量控制.我们在上篇(猛戳:SpringCloud系列——Feign 服务调用)已经实现了多个服务之间的Feign调用 ...

  5. SpringCloud Netflix Ribbon(负载均衡)

    ⒈Ribbon是什么? Spring Cloud Ribbon是基于Netflix Ribbon实现的一套客户端负载均衡工具. Ribbon是Netflix发布的开源项目,主要功能是提供客户端的软件负 ...

  6. java框架之SpringCloud(4)-Ribbon&Feign负载均衡

    在上一章节已经学习了 Eureka 的使用,SpringCloud 也提供了基于 Eureka 负载均衡的两种方案:Ribbon 和 Feign. Ribbon负载均衡 介绍 SpringCloud ...

  7. springcloud(五)-Ribbon

    前言 先发句牢骚,最近太TM忙了,一直没时间静下心来继续写微服务架构!EMMMMMM..... 经过前文的讲解,我们已经实现了微服务的注册与发现.启动各个微服务时,Eureka Client会把自己的 ...

  8. springcloud基于ribbon的canary路由方案

    思路 根据eureka的metadata进行自定义元数据,然后使用ribbon对该元数据进行过滤和匹配,选择server. 实现 这里使用header来传递路由信息,改造ribbon-discover ...

  9. SpringCloud之Ribbon:负载均衡

    Spring Cloud集成了Ribbon,结合Eureka,可实现客户端的负载均衡. 下面实现一个例子,结构下图所示. 一.服务器端 1.创建项目 开发工具:IntelliJ IDEA 2019.2 ...

  10. SpringCloud学习笔记(四、SpringCloud Netflix Ribbon)

    目录: Ribbon简介 Ribbon的应用 RestTemplate简介 Ribbon负载均衡源码分析 Ribbon简介: 1.负载均衡是什么 负载均衡,根据其字面意思来说就是让集群服务具有共同完成 ...

随机推荐

  1. 初步认识linux的top命令

    今天学习了一下top命令,强大无比啊! top命令涉及到的东西很多.用来监视系统的运行状态,top打印包括cpu.内存.进程使用情况的统计信息,还打印出进程列表. 输入top命令,不带任何参数,默认打 ...

  2. [ExecuteInEditMode]

    ExecuteInEditMode属性的作用是在EditMode下也可以执行脚本.Unity中默认情况下,脚本只有在运行的时候才被执行,加上此属性后,不运行程序,也能执行脚本. 与PlayMode不同 ...

  3. php获取响应状态码

    $ch = curl_init('http://www.jb51.net'); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_exec($ch); ...

  4. maven打包到私服,打的是war包,好郁闷

    jenkins打完包上传到私服以后,发现只有war包,然而并木有别人想要的jar包,郁闷之极啊! 然后把公司的项目做了对比,发现这个正常的能上传jar包的项目的与我的另一个项目有点出入: 正常:  异 ...

  5. hadoop Mapreduce组件介绍

    MapReduce原理 MapRedcue采用‘分而治之’的思想,对大规模数据集的操作,分发给一个主节点下的各个分节点共同完成,然后通过整合各个节点的中间结果,得到最终结果.Mapreduce就是任务 ...

  6. 工作总结(二):Web Design

    PHP框架:CakePHP 前端框架:Bootstrap Payment Data Transfer:https://developer.paypal.com/docs/classic/paypal- ...

  7. C#的math类的全部运算方法

    Abs 返回指定数字的绝对值.Acos 返回余弦值为指定数字的角度.Asin 返回正弦值为指定数字的角度.Atan 返回正切值为指定数字的角度.Atan2 返回正切值为两个指定数字的商的角度.BigM ...

  8. ckeditor粘贴上传图片

    公司做的项目需要用到文本上传功能. 网上找了很久,大部分都有一些不成熟的问题,皇天不负有心人终于让我找到了一个成熟的项目. 接下来就看一下吧 1.打开工程: 对于文档的上传我们需要知道这个项目的逻辑是 ...

  9. Spring 整合 RocketMQ

    1. 引入jar包 <!-- RocketMQ --> <dependency> <groupId>com.alibaba.rocketmq</groupId ...

  10. TypeScript开发环境搭建(Visual studio code)

    使用Visual Studio Code搭建TypeScript开发环境 1.TypeScript是干什么的 ? TypeScript是由微软Anders Hejlsberg(安德斯·海尔斯伯格,也是 ...