当前位置:网站首页>LoadBalancer 负载均衡
LoadBalancer 负载均衡
2022-07-30 03:25:00 【Leon_Jinhai_Sun】
前面我们讲解了如何对服务进行拆分、如何通过Eureka服务器进行服务注册与发现,那么现在我们来看看,它的负载均衡到底是如何实现的,实际上之前演示的负载均衡是依靠LoadBalancer实现的。
在2020年前的SpringCloud版本是采用Ribbon作为负载均衡实现,但是2020年的版本之后SpringCloud把Ribbon移除了,进而用自己编写的LoadBalancer替代。
那么,负载均衡是如何进行的呢?
负载均衡
实际上,在添加@LoadBalanced注解之后,会启用拦截器对我们发起的服务调用请求进行拦截(注意这里是针对我们发起的请求进行拦截),叫做LoadBalancerInterceptor,它实现ClientHttpRequestInterceptor接口:
@FunctionalInterface
public interface ClientHttpRequestInterceptor {
ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException;
}主要是对intercept方法的实现:
public ClientHttpResponse intercept(final HttpRequest request, final byte[] body, final ClientHttpRequestExecution execution) throws IOException {
URI originalUri = request.getURI();
String serviceName = originalUri.getHost();
Assert.state(serviceName != null, "Request URI does not contain a valid hostname: " + originalUri);
return (ClientHttpResponse)this.loadBalancer.execute(serviceName, this.requestFactory.createRequest(request, body, execution));
}我们可以打个断点看看实际是怎么在执行的,可以看到:


服务端会在发起请求时执行这些拦截器。
那么这个拦截器做了什么事情呢,首先我们要明确,我们给过来的请求地址,并不是一个有效的主机名称,而是服务名称,那么怎么才能得到真正需要访问的主机名称呢,肯定是得找Eureka获取的。
我们来看看loadBalancer.execute()做了什么,它的具体实现为BlockingLoadBalancerClient:
//从上面给进来了服务的名称和具体的请求实体
public <T> T execute(String serviceId, LoadBalancerRequest<T> request) throws IOException {
String hint = this.getHint(serviceId);
LoadBalancerRequestAdapter<T, DefaultRequestContext> lbRequest = new LoadBalancerRequestAdapter(request, new DefaultRequestContext(request, hint));
Set<LoadBalancerLifecycle> supportedLifecycleProcessors = this.getSupportedLifecycleProcessors(serviceId);
supportedLifecycleProcessors.forEach((lifecycle) -> {
lifecycle.onStart(lbRequest);
});
//可以看到在这里会调用choose方法自动获取对应的服务实例信息
ServiceInstance serviceInstance = this.choose(serviceId, lbRequest);
if (serviceInstance == null) {
supportedLifecycleProcessors.forEach((lifecycle) -> {
lifecycle.onComplete(new CompletionContext(Status.DISCARD, lbRequest, new EmptyResponse()));
});
//没有发现任何此服务的实例就抛异常(之前的测试中可能已经遇到了)
throw new IllegalStateException("No instances available for " + serviceId);
} else {
//成功获取到对应服务的实例,这时就可以发起HTTP请求获取信息了
return this.execute(serviceId, serviceInstance, lbRequest);
}
}所以,实际上在进行负载均衡的时候,会向Eureka发起请求,选择一个可用的对应服务,然后会返回此服务的主机地址等信息:

自定义负载均衡策略
LoadBalancer默认提供了两种负载均衡策略:
- RandomLoadBalancer - 随机分配策略
- (默认) RoundRobinLoadBalancer - 轮询分配策略
现在我们希望修改默认的负载均衡策略,可以进行指定,比如我们现在希望用户服务采用随机分配策略,我们需要先创建随机分配策略的配置类(不用加@Configuration):
public class LoadBalancerConfig {
//将官方提供的 RandomLoadBalancer 注册为Bean
@Bean
public ReactorLoadBalancer<ServiceInstance> randomLoadBalancer(Environment environment, LoadBalancerClientFactory loadBalancerClientFactory){
String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);
return new RandomLoadBalancer(loadBalancerClientFactory.getLazyProvider(name, ServiceInstanceListSupplier.class), name);
}
}接着我们需要为对应的服务指定负载均衡策略,直接使用注解即可:
@Configuration
@LoadBalancerClient(value = "userservice", //指定为 userservice 服务,只要是调用此服务都会使用我们指定的策略
configuration = LoadBalancerConfig.class) //指定我们刚刚定义好的配置类
public class BeanConfig {
@Bean
@LoadBalanced
RestTemplate template(){
return new RestTemplate();
}
}接着我们在BlockingLoadBalancerClient中添加断点,观察是否采用我们指定的策略进行请求:


发现访问userservice服务的策略已经更改为我们指定的策略了。
边栏推荐
- 奥比中光高级副总裁王兆民离职 董事会秘书暂未取得资格证
- Oracle 进程数和会话数的关系
- JUC(八):synchronized小练习
- JUC(四):简记线程的五/六种状态
- Overview of Federated Learning (2) - Classification, Framework and Future Research Directions of Federated Learning
- 新手入门C#:实现简易的计算器功能
- 【Use of scientific research tools】A
- Stimulsoft ReportsJS and DashboardsJS. 2022.3.3
- Redis (ten) - Redission principle and practice
- HCIP experiment (05) OSPF comprehensive experiment
猜你喜欢
随机推荐
HCIP OSPF
SQL 入门之第一讲——MySQL 8.0.29安装教程(windows 64位)
CDH/CDP 是什么?
(六)《数电》——二极管与CMOS门电路(入门)
redis的学习_基础部分
C# 一周入门之《C#-类和对象》Day Six
matlab之函数
JUC (7): Thread Safety Analysis of Variables
[Flink] How to determine the cluster planning size from development to production launch?
26 basic models in 6 categories that operators must master
解决导航栏变黑色
Open address method hash implementation - linear detection method
Leetcode.234 判断回文链表(双指针/快慢指针)
精品:淘宝/天猫获取购买到的商品订单详情 API
sublime text 3 设置
Simple Operations on Sequence
Public chains challenging the "Impossible Triangle"
应用在光伏逆变器中的IGBT晶圆
un7.29: How to install and configure redis in Linux-centos?
Oracle 进程数和会话数的关系









