4.1 Ribbon 介绍
4.1.1 Ribbon 简介
Ribbon是Netflix下的负载均衡项目,它在集群中为各个客户端的通信提供了支持,它主要实现中间层应用程序的负载均衡。
Ribbon提供以下特性:
- 负载均衡器,可支持插拔式的负载均衡规则。
- 对多种协议提供支持,例如HTTP、TCP、UDP
- 集成了负载均衡功能的客户端。
同为Netflix项目,Ribbon可以与Eureka整合使用,Ribbon同样被集成到Spring Cloud 中,作为spring-cloud-ne由ix项目中的子模块。
Spring Cloud将Ribbon的API进行了封装, 使用者可以使用封装后的API来实现负载均衡,也可以直接使用Ribbon的原生APL
4.1.2 Ribbon 子模块
Ribbon主要有以下三大子模块。
- ribbon-core:该模块为Ribbon项目的核心,主要包括负载均衡器接口定义、客户端 接口定义、内置的负载均衡实现等API。
- ribbon-eureka:为Eureka客户端提供的负载均衡实现类。
- ribbon-httpclient:对Apache的HttpClient进行封装,该模块提供了含有负载均衡功 能的REST客户端。
4.1.3负载均衡器组件
Ribbon的负载均衡器主要与集群中的各个服务器进行通信,负载均衡器需要提供以下基础功能:
- 维护服务器的IP、DNS名称等信息。
- 根据特定的逻辑在服务器列表中循环。
为了实现负载均衡的基础功能,Ribbon的负载均衡器有以下三大子模块。
- Rule: 一个逻辑组件,这些逻辑将会决定从服务器列表中返回哪个服务器实例。
- Ping:该组件主要使用定时器来确保服务器网络可以连接。
- ServerList:服务器列表,可以通过静态的配置确定负载的服务器,也可以动态指定 服务器列表。如果动态指定服务器列表,则会有后台的线程来刷新该列表。
本章关于Ribbon的知识,主要围绕负载均衡器组件进行
4.2 第一个Ribbon程序
本章的4.2节和4.3节,单独使用Ribbon框架,关于整合Spring Cloud的内容,将在 4.4节讲述。本节将以一个简单的Hello World程序来展示Ribbon API的使用。
本例的程序 结构如图所示。
本书所使用的Spring Cloud, 默认集成的Ribbon版本为2.2.2, 因此本书也使用该版本的Ribbon
4.2.1编写服务
为了能查看负载均衡效果,先编写一个简单的REST服务,通过指定不同的端口,让服务可以启动多个实例。本例的请求服务器,仅仅是一个基于Spring Boot的Web应用,
与2.3节中的应用类似,如果读者熟悉建立过程,可跳过部分创建过程,本小节最终目的 是发布两个REST服务。
新建名称为first-ribbon-server的Maven项目,加入以下依赖:
1 2 3 4 5 |
|
建立Spring Boot启动类,如代码所示:
1 2 3 4 5 6 7 8 9 10 |
|
运行main方法,并在控制台输入端口号,即可启动Web服务器
接下来编写控制器:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
在控制器中,发布了两个REST服务。其中,调用地址为/person/personld的服务后, 会返回一个Person实例的JSON字符串,为了看到请求的URL,为Person的message属性设置了请求的URL
4.2.2 编写请求客户端
新建名称为first-ribbon-client的Maven项目,加入以下依赖:
1 2 3 4 5 6 7 8 9 10 |
|
接下来,使用Ribbon的客户端发送请求, 请见代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
|
在代码清单中,使用ConfigurationManager类来配置请求的服务器列表,为 localhost:8080 与 localhost:8081, 再使用RestClient 对象,向/person/1 地址发送 6 次请求。
启动两次服务器类FirstServerApplication,并在控制台分别输入8080和8081端口。启动服务器后,运行客户端,输出结果如下:
1 2 3 4 5 6 |
|
根据输出结果可知,RestClient轮流向8080与8081端口发送请求,可见在RestClient 中己经帮我们实现了负载均衡的功能
4.2.3 Ribbon 的配置
在编写客户端时,使用了 ConfigurationManager来设置配置项,除了在代码中指定配置项外,还可以将配置放到.properties 文件中。
ConfigurationManager 的 loadPropertiesFromResources 方法可以指定properties文件的位置,配置格式如下: