负载均衡-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();
相关推荐
一叶龙洲13 分钟前
Ubuntu开机无法用向日葵远程控制
linux·运维·ubuntu
计算机安禾25 分钟前
【Linux从入门到镜头】第29篇:文本处理三剑客(下)——awk 数据处理神器
linux·运维·服务器
网络安全许木36 分钟前
自学渗透测试第28天(协议补漏与FTP抓包)
运维·服务器·网络安全·渗透测试·php
V我五十买鸡腿1 小时前
网安基础 Windows 和 Linux 那些常用命令
linux·运维·windows
日取其半万世不竭1 小时前
用云服务器部署 Hexo 博客,Nginx 托管静态页面全流程
运维·服务器·nginx
handler011 小时前
进程状态流转的本质:Linux 内核队列与底层数据结构解密
linux·运维·c语言·数据结构·c++·笔记·学习
龙智DevSecOps解决方案1 小时前
深度:Perforce P4 MCP 服务器开源解析——当版本控制遇见 AI Agent
运维·服务器·人工智能
小杰帅气1 小时前
负载均衡式的在线OJ
运维·负载均衡
蜡笔婧萱2 小时前
Linux--RHCE关于at和crond的第一次应用
linux·运维·服务器
VBsemi-专注于MOSFET研发定制2 小时前
高端LED封装自动化产线功率MOSFET选型方案——精密、高效与可靠驱动系统设计指南
运维·单片机·自动化