负载均衡-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();
相关推荐
Tipriest_3 小时前
Ubuntu常用的软件格式deb, rpm, dmg, AppImage等打包及使用方法
linux·运维·ubuntu
真智AI3 小时前
利用 Claude Opus 4 自动化 GitHub 工作流:从安装到实战详解
运维·自动化·github
胡斌附体4 小时前
linux测试端口是否可被外部访问
linux·运维·服务器·python·测试·端口测试·临时服务器
愚润求学4 小时前
【Linux】自旋锁和读写锁
linux·运维
大锦终4 小时前
【Linux】常用基本指令
linux·运维·服务器·centos
知北游天4 小时前
Linux:多线程---深入互斥&&浅谈同步
linux·运维·服务器
Gappsong8744 小时前
【Linux学习】Linux安装并配置Redis
java·linux·运维·网络安全
try2find5 小时前
移动conda虚拟环境的安装目录
linux·运维·conda
码农101号5 小时前
Linux中容器文件操作和数据卷使用以及目录挂载
linux·运维·服务器
程序员弘羽6 小时前
Linux进程管理:从基础到实战
linux·运维·服务器