负载均衡-ribbon源码解析

负载均衡-ribbon源码解析

1 @LoadBalanced注解

java 复制代码
/**
 * 基于ribbon调用服务及负载均衡
 * @return
 */
@LoadBalanced
@Bean
public RestTemplate restTemplate(){
    return new RestTemplate();
}
java 复制代码
@Bean
@ConditionalOnMissingBean
public RestTemplateCustomizer restTemplateCustomizer(final LoadBalancerInterceptor loadBalancerInterceptor) {
    return (restTemplate) -> {
        // 获取拦截器
        List<ClientHttpRequestInterceptor> list = new ArrayList(restTemplate.getInterceptors());
        // 添加一个新的拦截器(负载均衡的拦截器,该拦截器就是在restTemplate发送请求之前执行)
        list.add(loadBalancerInterceptor);
        // 将拦截器设置到restTemplate中  该restTemplate就是在OrderApplication中添加了@LoadBalanced的注解
        restTemplate.setInterceptors(list);
    };
}

总上所属:@LoadBalanced就是对template起到标识作用,加了@LoadBalanced注解的template开启负载均衡

2 源码解析

1)通过restTemplate发起请求

java 复制代码
Result result = restTemplate.getForObject("http://product-server/product/" + id, Result.class);

2)执行拦截器的intercept方法

java 复制代码
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);
    // 调用loadBalancer的execute方法  loadBalancer:负载均衡器
    // serviceName:就是product-server
    return (ClientHttpResponse)this.loadBalancer.execute(serviceName, this.requestFactory.createRequest(request, body, execution));
}

3)查看RibbonLoadBalancerClient中的execute方法

java 复制代码
public <T> T execute(String serviceId, LoadBalancerRequest<T> request, Object hint) throws IOException {
    // 通过负载均衡器 
    ILoadBalancer loadBalancer = this.getLoadBalancer(serviceId);
    // 通过负载均衡器 接 负载均衡算法 获取服务实例
    Server server = this.getServer(loadBalancer, hint);
    if (server == null) {
        throw new IllegalStateException("No instances available for " + serviceId);
    } else {
        RibbonLoadBalancerClient.RibbonServer ribbonServer = new RibbonLoadBalancerClient.RibbonServer(serviceId, server, this.isSecure(server, serviceId), this.serverIntrospector(serviceId).getMetadata(server));
        return this.execute(serviceId, (ServiceInstance)ribbonServer, (LoadBalancerRequest)request);
    }
}

4)根据负载均衡算法获取服务实例

java 复制代码
protected Server getServer(ILoadBalancer loadBalancer, Object hint) {
    return loadBalancer == null ? null : loadBalancer.chooseServer(hint != null ? hint : "default");
}
java 复制代码
public Server chooseServer(Object key) {
    if (this.counter == null) {
        this.counter = this.createCounter();
    }
    this.counter.increment();
    if (this.rule == null) {
        return null;
    } else {
        try {
            // rule就是配置的负载均衡算法
            // choose就是根据指定的负载均衡算法获取服务实例
            return this.rule.choose(key);
        } catch (Exception var3) {
            logger.warn("LoadBalancer [{}]:  Error choosing server for key {}", new Object[]{this.name, key, var3});
            return null;
        }
    }
}
java 复制代码
// 默认的负载均衡器
private static final IRule DEFAULT_RULE = new RoundRobinRule();

}

}

}

复制代码
```java
// 默认的负载均衡器
private static final IRule DEFAULT_RULE = new RoundRobinRule();
相关推荐
孙克旭_26 分钟前
day051-ansible循环、判断与jinja2模板
linux·运维·服务器·网络·ansible
总有刁民想爱朕ha1 小时前
零基础搭建监控系统:Grafana+InfluxDB 保姆级教程,5分钟可视化服务器性能!
运维·服务器·grafana
Mr_Orangechen1 小时前
Linux 下使用 VS Code 远程 GDB 调试 ARM 程序
linux·运维·arm开发
撰卢2 小时前
【个人笔记】负载均衡
运维·笔记·负载均衡
lilian1292 小时前
linux系统mysql性能优化
linux·运维·mysql
weixin_516023073 小时前
Geant4 安装---Ubuntu
linux·运维·ubuntu
wanhengidc3 小时前
企业选择大带宽服务器租用的原因有哪些?
运维·服务器
罗技1234 小时前
用Filebeat OSS 7.10.2将收集日志到Easysearch
运维·es
egoist20235 小时前
【Linux仓库】虚拟地址空间【进程·陆】
linux·运维·服务器·操作系统·进程·虚拟地址空间·fork
云和数据.ChenGuang5 小时前
自动化运维工具jenkins问题
运维·自动化·jenkins·运维面试题·运维试题