比如: 我想按照权重取匹配优先级
我如何计算权重?Ribbon之前的方式是定时任务,每30s去访问Ping请求,计算请求时间,反应时间来算出权重,现在这么一套我要如何实现?我们不可能一 一实现这7种策略,所以我们还是要用SpringCloud 结合Ribbon 来使用他的负载均衡, 下面我们使用固定版本的SpringCloud来做demo
我使用的版本如下
本文使用的版本是
Spring-boot-starter-parent 2.3.0.RELEASE
Spring-cloud-dependencies Hoxton.SR1
引入上面的包后
自动就引入了Ribbon的版本 spring-cloud-starter-netflix-ribbon:2.2.1.RELEASE
Ribbon 一共7 种策略
包依赖如图所示
本次我们使用四个微服务 + 一个Eureka注册中心 不知道如何构建的请参考前面的文章
Ribbon负载均衡(一)Ribbon实战
我们都知道 Ribbon是进程级别的负载均衡,而负载均衡策略实现是在调用端也就是client客户端,客户端user去判断你要调用的服务order有多少个服务注册到eureka上,而且客户端计算你每个order服务权重,计算每个order服务的请求时间,响应时间等等,所以我们的orderOne,orderTwo,orderThree这三个不用处理,因为他们order服务提供者
我们只需要改造user服务即可
我们改造一下
user微服务的Pom文件
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.3.0.RELEASE
com.ribbon.user
demo
0.0.1-SNAPSHOT
user
Demo project for Spring Boot
1.8
Hoxton.SR1
org.springframework.boot
spring-boot-starter-web
org.springframework.cloud
spring-cloud-starter-netflix-eureka-client
org.springframework.boot
spring-boot-starter-test
test
org.projectlombok
lombok
1.18.16
compile
org.springframework.cloud
spring-cloud-dependencies
${spring-cloud.version}
pom
import
org.springframework.boot
spring-boot-maven-plugin
切记切记切记
在主启动类的最外层,不要把配置Ribbon的文件放在启动类及包扫描目录,也就是 java文件夹下 , 新建一个文件夹 ribbon
文件夹ribbon下新建 RibbonConfiguration.java
package ribbon;
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 RibbonConfiguration {
@Bean
public IRule myRandomRule() {
// 随机策略
return new RandomRule();
}
// @Bean
// public IRule myWeightedRule() {
// // 权重优先
// return new WeightedResponseTimeRule();
// }
//
//
// @Bean
// public IRule myRoundRule() {
// // 轮询策略
// return new RoundRobinRule();
// }
//
//
// @Bean
// public IRule myBestRule() {
// // 最高可用策略
// return new BestAvailableRule();
// }
}
新建 config/ribbon 下面RestTemplateConfig.java 配置RestTemplate来访问Controller,使用Ribbon负载均衡
package com.ribbon.user.config.ribbon;//package com.ribbon.user.config.cloudconfig;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
import ribbon.RibbonConfiguration;
/**
* 如果是 SpringCloud 使用Ribbon 配置下面的
*/
//在这里配置我们自定义的LoadBalancer策略
//注意这里的name属性 需要和eureka页面中的服务提供者名字保持一致
@RibbonClient(name = "order", configuration = RibbonConfiguration.class)
@Configuration
public class RestTemplateConfig {
//如果不加上面的注释 @LoadBalanced 就不会从eureka上获取 order服务地址, 也就不会使用负载均衡,
// 你访问的 http://order/order order服务的host就会找不到
@Bean
@LoadBalanced
//使用这个 @LoadBalanced 注解给restTemplate赋予了负载均衡的能力
RestTemplate restTemplate() {
return new RestTemplate();
}
}
package com.ribbon.user.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
@RestController
@Slf4j
public class UserController {
@Autowired
private LoadBalancerClient loadBalancerClient;
@Resource
private RestTemplate restTemplate;
@GetMapping("/user")
public String test() {
log.info("client 发起UserController");
return "user";
}
@GetMapping("/client")
public String client() {
//通过Ribbon client 去实现负载均衡算法,获取URL信息
log.info("client 开始调用");
//我们选择的是eureka 上的 order 应用服务,因为我们直到 order有两个
ServiceInstance order = loadBalancerClient.choose("order");
log.info("Uri:{}", order.getUri());
log.info("Host:{}", order.getHost());
log.info("Port:{}", order.getPort());
log.info("InstanceId:{}", order.getInstanceId());
log.info("Metadata:{}", order.getMetadata());
log.info("Weight:{}", order.getMetadata().get("weight"));
log.info("ServiceId:{}", order.getServiceId());
log.info("Scheme:{}", order.getScheme());
log.info("==================================================");
return "user";
}
@GetMapping("/testribbon")
public String testRibbon() {
//restTemplate 请求访问 order订单服务的 order URL ,
// 参数URL http://order/order 第一个order 就是服务名字 就是注册在Eureka上的 服务名字 第二个order就是 controller 入口
// 第二个参数String.class 就是 访问返回值
String result = restTemplate.getForObject("http://order/order", String.class);
log.info("user 发起UserController 测试ribbon 调用 :{} ", result);
return result;
}
}
访问 localhost:8088/testribbon
如果报错, 看下你的RestTemplate种的@LoadBalanced 注解是否加上,不加上默认是使用正常的restTemplate 访问IP+PORT ,你的URL是 http://order/order 不会去Eureka上获取order服务的地址及端口的
没有@LoadBalanced 注解 会报如下错误
nested exception is java.net.UnknownHostException: order] with root cause
java.net.UnknownHostException: order
2022-05-15 21:51:03.169 ERROR 6216 --- [nio-8088-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.web.client.ResourceAccessException: I/O error on GET request for "http://order/order": order; nested exception is java.net.UnknownHostException: order] with root cause
java.net.UnknownHostException: order
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:184) ~[na:1.8.0_181]
服务正常启动
采用 随机负载均衡策略
@Bean
public IRule myRandomRule() {
// 随机策略
return new RandomRule();
}
访问testribbon接口 http://localhost:8088/testribbon
看看RestTemplate访问的是否是随机访问三个节点中的一个
RibbonConfiguration.java 种 把随机策略注释掉, 放开轮询策略
@Bean
public IRule myRoundRule() {
// 轮询策略
return new RoundRobinRule();
}
重启User服务
访问testribbon接口 http://localhost:8088/testribbon
看看RestTemplate访问的是否是轮询访问三个节点中的一个
RibbonConfiguration.java 种 把轮询策略注释掉, 放开最优可用策略
@Bean
public IRule myBestRule() {
// 最高可用策略
return new BestAvailableRule();
}
重启User服务
访问testribbon接口 http://localhost:8088/testribbon
看看RestTemplate访问的是否是 最优访问三个节点中的节点
是不是 最优解怎么确认? 我们看下面的日志
DynamicServerListLoadBalancer for client order initialized: DynamicServerListLoadBalancer:{NFLoadBalancer:name=order,current list of Servers=[localhost:8090, localhost:8089, localhost:8091],Load balancer stats=Zone stats: {defaultzone=[Zone:defaultzone; Instance count:3; Active connections count: 0; Circuit breaker tripped count: 0; Active connections per server: 0.0;]
},Server stats: [[Server:localhost:8090; Zone:defaultZone; Total Requests:0; Successive connection failure:0; Total blackout seconds:0; Last connection made:Thu Jan 01 08:00:00 CST 1970; First connection made: Thu Jan 01 08:00:00 CST 1970; Active Connections:0; total failure count in last (1000) msecs:0; average resp time:0.0; 90 percentile resp time:0.0; 95 percentile resp time:0.0; min resp time:0.0; max resp time:0.0; stddev resp time:0.0]
, [Server:localhost:8091; Zone:defaultZone; Total Requests:0; Successive connection failure:0; Total blackout seconds:0; Last connection made:Thu Jan 01 08:00:00 CST 1970; First connection made: Thu Jan 01 08:00:00 CST 1970; Active Connections:0; total failure count in last (1000) msecs:0; average resp time:0.0; 90 percentile resp time:0.0; 95 percentile resp time:0.0; min resp time:0.0; max resp time:0.0; stddev resp time:0.0]
, [Server:localhost:8089; Zone:defaultZone; Total Requests:0; Successive connection failure:0; Total blackout seconds:0; Last connection made:Thu Jan 01 08:00:00 CST 1970; First connection made: Thu Jan 01 08:00:00 CST 1970; Active Connections:0; total failure count in last (1000) msecs:0; average resp time:0.0; 90 percentile resp time:0.0; 95 percentile resp time:0.0; min resp time:0.0; max resp time:0.0; stddev resp time:0.0]
什么意思,下面解释一下
#注册了三个地址
current list of Servers=[localhost:8090, localhost:8089, localhost:8091],
#8090 地址
[Server:localhost:8090
# 总请求数量 0
Total Requests:0;
#连续(successive)请求异常数量 0
Successive connection failure:0;
#总的断路时长 0s
Total blackout seconds:0;
# 活跃连接数 底层源码取的就是 activeRequestsCount
Active Connections:0;
#一定时间内失败 连接数量
total failure count in last (1000) msecs:0;
#平均响应时间
average resp time:0.0;
#90%,95%的请求响应时间
90 percentile resp time:0.0;
95 percentile resp time:0.0;
因为 第一个就是8090, 因为是模拟的, 也没有请求,所以三个order服务的并发链接数都是0, 也就是orderTwo 相等于 orderOne和orderThree, 所以每次用最优选取的时候都会选第一个orderTwo
RibbonConfiguration.java 种 把最优可用策略注释掉, 放开权重优先策略
@Bean
public IRule myWeightedRule() {
// 权重优先
return new WeightedResponseTimeRule();
}
重启User服务
http://localhost:8088/testribbon 访问testribbon接口
看看RestTemplate访问的是否是 权重优先三个节点中的节点
是不是 权重优先怎么确认? 我们看下面的日志,节点选择不规则, 而且 日志
Weight adjusting job started 说明有定时任务在不停的计算权重, 到底是怎么计算的?
2022-05-24 00:00:11.922 INFO 15920 --- [nio-8088-exec-3] c.ribbon.user.controller.UserController : user 发起UserController 测试ribbon 调用 :orderOne
2022-05-24 00:00:12.466 INFO 15920 --- [nio-8088-exec-5] c.ribbon.user.controller.UserController : user 发起UserController 测试ribbon 调用 :orderTwo
2022-05-24 00:00:12.919 INFO 15920 --- [nio-8088-exec-4] c.ribbon.user.controller.UserController : user 发起UserController 测试ribbon 调用 :orderThree
2022-05-24 00:00:13.346 INFO 15920 --- [nio-8088-exec-6] c.ribbon.user.controller.UserController : user 发起UserController 测试ribbon 调用 :orderOne
2022-05-24 00:00:13.742 INFO 15920 --- [nio-8088-exec-7] c.ribbon.user.controller.UserController : user 发起UserController 测试ribbon 调用 :orderOne
2022-05-24 00:00:14.088 INFO 15920 --- [nio-8088-exec-9] c.ribbon.user.controller.UserController : user 发起UserController 测试ribbon 调用 :orderThree
2022-05-24 00:00:14.545 INFO 15920 --- [nio-8088-exec-8] c.ribbon.user.controller.UserController : user 发起UserController 测试ribbon 调用 :orderTwo
2022-05-24 00:00:14.909 INFO 15920 --- [io-8088-exec-10] c.ribbon.user.controller.UserController : user 发起UserController 测试ribbon 调用 :orderTwo
2022-05-24 00:00:15.123 INFO 15920 --- [nio-8088-exec-1] c.ribbon.user.controller.UserController : user 发起UserController 测试ribbon 调用 :orderTwo
2022-05-24 00:00:16.218 INFO 15920 --- [nio-8088-exec-2] c.ribbon.user.controller.UserController : user 发起UserController 测试ribbon 调用 :orderTwo
2022-05-24 00:00:16.632 INFO 15920 --- [nio-8088-exec-3] c.ribbon.user.controller.UserController : user 发起UserController 测试ribbon 调用 :orderOne
2022-05-24 00:00:26.597 INFO 15920 --- [ightTimer-order] c.n.l.WeightedResponseTimeRule : Weight adjusting job started
2022-05-24 00:00:26.612 INFO 15920 --- [der_defaultzone] c.n.l.WeightedResponseTimeRule : Weight adjusting job started
2022-05-24 00:00:27.627 INFO 15920 --- [der_defaultzone] c.n.l.WeightedResponseTimeRule : Weight adjusting job started
2022-05-24 00:00:56.608 INFO 15920 --- [ightTimer-order] c.n.l.WeightedResponseTimeRule : Weight adjusting job started
2022-05-24 00:00:56.624 INFO 15920 --- [der_defaultzone] c.n.l.WeightedResponseTimeRule : Weight adjusting job started
权重计算过程
初始化时,启动一个定时器,每隔 30s 根据服务的响应时间分配一次权重,响应时间越长,权重越低,被选择到的概率也越低。响应时间越短,权重越高,实例被选中概率越高。得到权重后,生成随机权重,命中权重比随机权重大的第一个服务实例
先 看下权重优先 源码的注释
* Using the Random API, generate a random number between 1 and10+30+40+20.
* Let's assume that the above list is randomized. Based on the weights, we
* have intervals as follows:
*
* 1-----10 (A's weight)
*
* 11----40 (A's weight + B's weight)
*
* 41----80 (A's weight + B's weight + C's weight)
*
* 81----100(A's weight + B's weight + C's weight + C's weight)
*
* Here's the psuedo code for deciding where to send the request:
*
* if (random_number between 1 & 10) {send request to A;}
*
* else if (random_number between 11 & 40) {send request to B;}
*
* else if (random_number between 41 & 80) {send request to C;}
*
* else if (random_number between 81 & 100) {send request to D;}
*
* When there is not enough statistics gathered for the servers, this rule
* will fall back to use {@link RoundRobinRule}.
也就是说:现在有三个服务实例,平均响应时间分别为:
A:100ms
B:200ms
C:300ms
则权重分别是:
A:600-100 = 500
B:500+600-200 = 900
C:900+600-300 = 1200
生成的随机数若在 0-500 之间,则命中服务 A,如在 500 - 900 之间,则命中服务 B,如在 900 - 1200,则命中服务 C,如果没有命中任何服务实例,则取轮询策略的结果。
我还没找打 怎么把权重打印出来, 因为源码中打印了Weight adjusting job started ,改源码肯定是可以的,但是应该有更简洁的方法,暂时我还没找到而已
至此我们已经 可以熟练的使用Ribbon了 , 也可以定制自己的负载均衡策略, 除了这7种,也可以自定义负载均衡策略 ,比如A机器5次,换B机器5次,换C机器这样的自定义负载均衡