负载均衡-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();
相关推荐
码龄3年 审核中2 小时前
说说SSH的端口转发
大数据·运维·ssh
盛世隐者2 小时前
【Linux】定制Linux系统
linux·运维·服务器
Lxt.星翊5 小时前
MySQL(安装和卸载、数据库存储原理图)
linux·运维·windows
苹果醋35 小时前
JAVA面试汇总(二)多线程(五)
运维·vue.js·spring boot·nginx·课程设计
JustNow_Man6 小时前
Cline中模型识别任务与clinerules相关性的实现逻辑
linux·运维·ubuntu
小白银子6 小时前
零基础从头教学Linux(Day 56)
linux·运维·python
你想考研啊6 小时前
Linux下搭建Activemq的Master-Slave(共享文件模式)
linux·运维·activemq
Teamhelper_AR7 小时前
AR巡检系统:打开工业智能运维的下一幕
运维·ar
道阻且长行则将至!7 小时前
ubuntu中为什么查看CPU的步进?查看命令是什么?
linux·运维·ubuntu·步进·stepping
Wang's Blog8 小时前
Linux小课堂: 网络接口与连接监控命令详解
linux·运维·服务器