【Ribbon】来手写一个负载均衡
一、Ribbon的基本介绍
1.Ribbon是什么?
- Springclod Ribbon是基于Netfix Ribbon实现的一套客户端 负载均衡的工具
- Ribbon 是 Netflix 发布的开源项目,主要功能是提供客户端的软件负载均衡算法和服务调用。Ribbon 客户端组件提供一系列完善的配置项如连接超时,重试等。简单的说,就是在配置文件中列出 Load Balancer(简称LB)后面所有的机器,Ribbon 会自动的帮助你基于某种规则(如简单轮询、随机连接等)去连接这些机器。我们很容易使用Ribbon实现自定义的负载均衡算法。
- 目前在维护中,但是仍是目前的主流
- 简单来说就是负载均衡+RestTemplate
2.Ribbon能做什么?
2.1 负载均衡
- 简单来说负载均衡是将用户的请求平摊的分配到多个服务上,从而达到系统的HA(高可用)
- 常见的负载均衡有软件Nginx,LVS,硬件F5等
2.2 Ribbon本地负载均衡客户端vs Nginx服务端负载均衡区别
- 集中式LB:Nginx是服务器负载均衡,客户端所有请求都会交给Nginx,然后由nginx实现转发请求。即负载均衡是由服务端实现的。简单来讲可以理解为医院分科室,等待我需要进的科室。
- 进程内LB:Ribbon本地负载均衡,在调用微服务接口的时候,会在注册中心上获取注册信息服务列别之后缓存到JVM本地,从而在本地实现RPC远程服务调用技术。简单来讲可以理解为具体科室,牙科我等带医生。
二、Ribbon负载均衡演示
1.构架说明
- 总结:Ribbon其实就是一个软负载均衡的客户端组件,他可以和其他所需请求的客户端结合使用,和eureka结合知识其中一个实例
图解: - 第一步先选择EurekaServer,它优先选择在同一个区域内负载较少的server
- 第二步再根据用户指定的策略,在从server取到的服务注册列表中选择一个地址
- 其中Ribbon提供了多种策略:比如轮询,随机和根据响应的时间加权
2.pom
由于新版的eureka中集成了ribbon,所以我们无需在导入,也就是说如果你有下面的就不需要在导入ribbon
3.ResrTemplate的使用
3.1 getForObject方法/getForEntity方法
- 如果是Object,返回对象为响应体中数据转化成的对象,基本上可以理解为Json
- 如果是Entity,返回对象为ResponseEntity对象,包含了响应中的一些重要信息,比如响应头,响应状态码,响应体等
@GetMapping(value = "/consumer/get/{id}")
public CommonResult getPayment1(@PathVariable("id") Long id){
log.info("success");
return restTemplate.getForObject(PAYMENT_URL+"/payment/get/"+id,CommonResult.class);
}
@GetMapping(value = "/consumer/getEntity/{id}")
public CommonResult<Payment> getForEntity(@PathVariable("id") Long id){
ResponseEntity<CommonResult> forEntity=restTemplate.getForEntity(PAYMENT_URL+"/payment/get/"+id,CommonResult.class);
if(forEntity.getStatusCode().is2xxSuccessful()){
return forEntity.getBody();
}else {
return new CommonResult<>(444,"调用失败")
}
}
3.1 postForObject方法/postForEntity方法
与get方法类似。
三、Ribbon核心组件IRule
1.IRule
- 根据特定算法中从服务列表中选取一个要访问的服务
2.Ribbon常带的负载均衡规则
3.换一个负载均衡规则(默认是轮询)
- 官方文档明确给出警告
- 这个自定义配置类不能放在 @ComponentScan所扫描的包下以及子包下,否则我们自定义的这个配置类就会被所有Ribbon客户端所共享,达不到特殊化定制的目的了。
3.1 目录结构
3.2 创建规则类
package com.atguigu.myrule;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RandomRule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyselfRule {
@Bean
public IRule myRule(){
return new RandomRule(); //定义为随机
}
}
3.3 主启动类添加注解
@RibbonClient(name = "CLOUD-PAYMENT-SERVICE",configuration = MyselfRule.class)
3.4 测试
3.5 源码
在看源码之前,需要对CAS知识有一定的了解,可以先去补补课哦。点我查看CAS相关知识点
- IRule接口
//IRule接口
public interface IRule{
/*
* choose one alive server from lb.allServers or
* lb.upServers according to key
*
* @return choosen Server object. NULL is returned if none
* server is available
*/
//选择哪个服务实例
public Server choose(Object key);
public void setLoadBalancer(ILoadBalancer lb);
public ILoadBalancer getLoadBalancer();
}
- RoundRobinRule轮询源码
public class RoundRobinRule extends AbstractLoadBalancerRule {
private AtomicInteger nextServerCyclicCounter;
private static final boolean AVAILABLE_ONLY_SERVERS = true;
private static final boolean ALL_SERVERS = false;
private static Logger log = LoggerFactory.getLogger(RoundRobinRule.class);
public RoundRobinRule() {
nextServerCyclicCounter = new AtomicInteger(0);
}
public RoundRobinRule(ILoadBalancer lb) {
this();
setLoadBalancer(lb);
}
public Server choose(ILoadBalancer lb, Object key) {
if (lb == null) {
log.warn("no load balancer");
return null;
}
Server server = null;
int count = 0;
while (server == null && count++ < 10) {
List<Server> reachableServers = lb.getReachableServers();
List<Server> allServers = lb.getAllServers();
int upCount = reachableServers.size();
int serverCount = allServers.size();
if ((upCount == 0) || (serverCount == 0)) {
log.warn("No up servers available from load balancer: " + lb);
return null;
}
int nextServerIndex = incrementAndGetModulo(serverCount);
server = allServers.get(nextServerIndex);
if (server == null) {
/* Transient. */
Thread.yield();
continue;
}
if (server.isAlive() && (server.isReadyToServe())) {
return (server);
}
// Next.
server = null;
}
if (count >= 10) {
log.warn("No available alive servers after 10 tries from load balancer: "
+ lb);
}
return server;
}
/**
* Inspired by the implementation of {@link AtomicInteger#incrementAndGet()}.
*
* @param modulo The modulo to bound the value of the counter.
* @return The next value.
*/
private int incrementAndGetModulo(int modulo) {
for (;;) {
int current = nextServerCyclicCounter.get();
int next = (current + 1) % modulo;
if (nextServerCyclicCounter.compareAndSet(current, next))
return next;
}
}
@Override
public Server choose(Object key) {
return choose(getLoadBalancer(), key);
}
@Override
public void initWithNiwsConfig(IClientConfig clientConfig) {
}
}
四、手写一个负载均衡
1. 80项增加一个接口
package com.aiguigu.springcloud.lb;
import org.springframework.cloud.client.ServiceInstance;
import java.util.List;
public interface LoadBalancer {
ServiceInstance instances(List<ServiceInstance> serviceInstances);
}
2.增加实现类
注意:@Component
package com.aiguigu.springcloud.lb;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.stereotype.Component;
import java.lang.annotation.Annotation;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
@Component
public class MyLB implements LoadBalancer {
private AtomicInteger atomicInteger=new AtomicInteger(0);
public final int getAndIncrement(){
int current;
int next;
do{
current=atomicInteger.get();
next=current>=2147483647?0:current+1;
}while (!this.atomicInteger.compareAndSet(current,next));
System.out.println("***第几次访问,次数: "+next);
return next;
}
public ServiceInstance instances(List<ServiceInstance> serviceInstances){
int index=getAndIncrement()%serviceInstances.size();
return serviceInstances.get(index);
}
}
3. controller增加方法
3.1 8001和8002分别增加方法
@GetMapping("/payment/lb")
public String getPaymentLB(){
return serverPort;
}
3.2 80增加方法
@Resource
private LoadBalancer loadBalancer;
@Resource
private DiscoveryClient discoveryClient;
@GetMapping(value = "/consumer/payment/lb")
public String getPaymentLB(){
List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
if(instances==null||instances.size()<0){
return null;
}
ServiceInstance instances1 = loadBalancer.instances(instances);
URI uri = instances1.getUri();
return restTemplate.getForObject(uri+"/payment/lb",String.class);
}
4. 测试
- 在启动前要去掉注解 config.ApplicationContexCofig配置类中的 @LoadBalanced