SpringCloud学习笔记(2):使用Ribbon负载均衡
简介
Spring Cloud Ribbon是基于Netflix Ribbon实现的一套客户端负载均衡工具,在注册中心对Ribbon客户端进行注册后,Ribbon可以基于某种负载均衡算法,如轮询(默认)、随机、加权轮询、加权随机等自动帮助服务消费者调用接口。
项目介绍
- sc-parent,父模块(请参照SpringCloud学习笔记(1):Eureka注册中心)
- sc-eureka,注册中心(请参照SpringCloud学习笔记(1):Eureka注册中心)
- sc-provider-random,随机端口的提供者
- sc-consumer,使用Ribbon负载均衡的消费者
随机端口的提供者
1.在父模块下创建子模块项目sc-provider-random,pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.cf</groupId>
<artifactId>sc-parent</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>sc-provider-random</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
</dependencies>
</project>
2.创建启动类provider.ProviderApplication:
package provider;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ProviderApplication {
public static void main(String[] args) {
SpringApplication.run(ProviderApplication.class, args);
}
}
3.创建Controller:provider.controller.BookController
package provider.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RequestMapping("/book")
@RestController
public class BookController {
@GetMapping("/list")
public String getBookList(){
System.out.println("------------我被访问了-----------");
return "[\"Java入门到放弃\",\"C++入门到放弃\",\"Python入门到放弃\",\"C入门到放弃\"]";
}
}
4.创建application.yml:
server:
port: 0 #默认8080,配置随机端口需要设置为0
spring:
application:
name: sc-provider-random
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8080/eureka/
instance:
instance-id: ${spring.application.name}:${random.value} #实例名随机生成
5.依次启动注册中心sc-eureka以及两个提供者sc-provider-random,提供者sc-provider-random每次启动端口都不一样,可以看到sc-provider-random的两个实例都在注册中心注册:

使用Ribbon负载均衡的消费者
1.在父模块下创建子模块项目sc-consumer,pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.cf</groupId>
<artifactId>sc-parent</artifactId>
<version>0.0.1-SNAPSHOT</version>
</parent>
<artifactId>sc-consumer</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!-- spring-cloud-starter-netflix-eureka-client依赖中已经包含ribbon -->
<!-- <dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency> -->
</dependencies>
</project>
2.创建启动类consumer.ConsumerApplication:
package consumer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
public class ConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerApplication.class, args);
}
//为RestTemplate整合Ribbon,使其具备负载均衡的能力
@LoadBalanced
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
3.创建调用提供者服务的Controller:consumer.controller.ConsumerController
package consumer.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
public class ConsumerController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/getBookList")
public String getBookList(){
//sc-provider-random 为提供者服务名
return restTemplate.getForObject("http://sc-provider-random/book/list", String.class);
}
}
注意:在使用Ribbon负载均衡时,服务名称不能有下划线,否则会出现valid hostname异常
4.创建application.yml:
server:
port: 8083
spring:
application:
name: sc-consumer
eureka:
client:
registerWithEureka: false
serviceUrl:
defaultZone: http://localhost:8080/eureka/
5.依次启动注册中心sc-eureka、两个提供者sc-provider-random、消费者sc-consumer,并访问http://localhost:8083/getBookList:

多次访问后,通过控制台的日志打印可以发现消费者时通过轮询的方式访问两个提供者实例。
更改负载均衡策略
Ribbon默认使用RoundRobinRule(轮询)来做为负载均衡策略,我们可以实现IRule接口或者使用Ribbon提供的现成的负载均衡策略来替换默认的轮询策略。如下,使用随机访问的策略来替代默认的轮询,在消费者启动类中添加:
@Bean
public IRule randomRule(){
return new RandomRule();//使用随机访问的策略来替代默认的轮询
}
自定义负载均衡策略
一个自定义负载均衡策略小例子,依旧是轮询访问策略,只是每个服务实例访问5次后才会访问下一个服务实例。
1.创建类consumer.rule.MyRule:
package consumer.rule;
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 MyRule extends AbstractLoadBalancerRule {
private int currIndex = 0;//当前服务实例索引
private int currCount = 0;//当前服务实例被访问次数
private static final int MAX_COUNT = 5;//每个服务实例最大访问次数为5
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 = chooseRandomInt(upList.size());
server = upList.get(index);
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;
}
protected synchronized int chooseRandomInt(int serverCount) {
currCount++;
if(currCount > MAX_COUNT){
currIndex++;
if(currIndex >= serverCount){
currIndex = 0;
}
currCount = 1;
}
return currIndex;
}
@Override
public Server choose(Object key) {
return choose(getLoadBalancer(), key);
}
@Override
public void initWithNiwsConfig(IClientConfig clientConfig) {
// TODO Auto-generated method stub
}
}
2.修改配置:
@Bean
public IRule randomRule(){
return new MyRule();
}
依次启动注册中心sc-eureka、两个提供者sc-provider-random、消费者sc-consumer,并访问http://localhost:8083/getBookList进行测试。
SpringCloud学习笔记(2):使用Ribbon负载均衡的更多相关文章
- go微服务框架kratos学习笔记七(kratos warden 负载均衡 balancer)
目录 go微服务框架kratos学习笔记七(kratos warden 负载均衡 balancer) demo demo server demo client 池 dao service p2c ro ...
- springcloud(十四)、ribbon负载均衡策略应用案例
一.eureka-server服务中心项目不再创建 二.eureka-common-empdept公共组件项目不再掩饰 三.创建eureka-client-provider-empdept-one提供 ...
- 【官方文档】Nginx负载均衡学习笔记(二)负载均衡基本概念介绍
简介 负载均衡(Server Load Balancer)是将访问流量根据转发策略分发到后端多台 ECS 的流量分发控制服务.负载均衡可以通过流量分发扩展应用系统对外的服务能力,通过消除单点故障提升应 ...
- SpringCloud学习笔记《---03 Ribbon Rule---》核心篇
- SpringCloud学习笔记(五):Ribbon负载均衡
简介 Spring Cloud Ribbon是基于Netflix Ribbon实现的一套 客户端 负载均衡的工具 .(重点:客户端) 简单的说,Ribbon是Netflix发布的开源项目,主要功能是提 ...
- SpringCloud学习(4)——Ribbon负载均衡
Ribbon概述 SpringCloud Ribbon是基于Netflix Ribbon实现的一套客户端负载均衡工具. 简单的说, Ribbon是Netflix发布的开源项目, 主要功能是提供客户端软 ...
- SpringCloud的入门学习之概念理解、Ribbon负载均衡入门
1.Ribbon负载均衡,Spring Cloud Ribbon是基于Netflix Ribbon实现的一套客户端.负载均衡的工具. 答:简单的说,Ribbon是Netflix发布的开源项目,主要功能 ...
- spring cloud学习笔记二 ribbon负载均衡
Ribbon是Netflix发布的负载均衡器,它有助于控制HTTP和TCP的客户端的行为.为Ribbon配置服务提供者地址后,Ribbon就可基于某种负载均衡算法,自动地帮助服务消费者去请求.Ribb ...
- 最适合新手入门的SpringCloud教程 6—Ribbon负载均衡「F版本」
SpringCloud版本:Finchley.SR2 SpringBoot版本:2.0.3.RELEASE 源码地址:https://gitee.com/bingqilinpeishenme/Java ...
随机推荐
- Selenium+java - Ajax浮动框处理
Ajax浮动框 我们常遇到的某些网站首页输入框,点击后显示的浮动下拉热点,如下图: 实际案例 模拟场景如下: hao123首页搜索输入框,单击搜索框,点击浮动框中的哪吒票房破30亿,单击后选项的文字内 ...
- 建立第一个G2图表
Step1:引进G2脚本 方法一:引入在线脚本 <script src="https://gw.alipayobjects.com/os/lib/antv/g2/3.4.10/dist ...
- 算法之《图》Java实现
数据结构之图 定义(百度百科) 图的术语表 无向图 深度优先搜索 广度优先遍历 有向图 路径问题 调度问题 强连通性 最小生成树(无向图) 最小生成树的贪心算法 加权无向图的数据结构 Kruskal算 ...
- 从输入URL到浏览器显示页面发生了哪些事情---个人理解
经典面试题:从输入URL到页面显示发生了哪些事情 以前一直都记不住,这次自己理解了一下 用自己的话总结了一次,不对的地方希望大佬给我指出来 1.主机通过DHCP协议获取客户端的IP地址.子网掩码和DN ...
- Android常用库源码解析
图片加载框架比较 共同优点 都对多级缓存.线程池.缓存算法做了处理 自适应程度高,根据系统性能初始化缓存配置.系统信息变更后动态调整策略.比如根据 CPU 核数确定最大并发数,根据可用内存确定内存缓存 ...
- 网页如何设置favicon.ico
1.首先制作ico图,并命名favicon.ico 2.将文件放在项目的根目录下
- cmd命令行界面运行python脚本显示的中文不正确
在notepad++中编写了一个脚本(如图一),在cmd命令行界面中运行却发现显示的中文不正确(如图2).图3显示的是cmd界面的默认编码. 解决方案:将脚本的注释语言改为GBK,编码格式改为ANSI ...
- 从 Python 之父的对话聊起,关于知识产权、知识共享与文章翻译
一.缘起 前不久,我在翻译 Guido van Rossum(Python之父)的文章时,给他留言,申请非商业用途的翻译授权. 过程中起了点小误会,略去不表,最终的结果是:他的文章以CC BY-NC- ...
- vector function trmplate
/* vector function template programmer:qpz */ #include <iostream> #include <vector> #def ...
- xgboost与gdbt的不同和优化
XGBoost是GBDT算法的一种变种,是一种常用的有监督集成学习算法:是一种 伸缩性强.便捷的可并行构建模型的Gradient Boosting算法 Xgboost和GBDT不同之处 xgboost ...