目录
一. Ribbon⼯作原理
二. @LoadBalanced源码剖析
(一)研究LoadBalancerAutoConfifiguration
(二)分析拦截器LoadBalancerInterceptor
1. 关注点1:
2. 关注点2:选择服务
3 . 关注点3:
(三)serverList分析
三. RoundRobinRule轮询策略源码剖析
四. RandomRule随机策略源码剖析
重点:Ribbon给restTemplate添加了⼀个拦截器
package org.springframework.cloud.client.loadbalancer;
import org.springframework.cloud.client.ServiceInstance;
import java.io.IOException;
import java.net.URI;
/**
* Represents a client-side load balancer.
* @author Spencer Gibb
*/
public interface LoadBalancerClient extends ServiceInstanceChooser {
// 根据服务执⾏请求内容
T execute(String serviceId, LoadBalancerRequest request) throws IOException;
// 根据服务执⾏请求内容
T execute(String serviceId, ServiceInstance serviceInstance, LoadBalancerRequest request) throws IOException;
// 拼接请求⽅式 传统中是ip:port 现在是服务名称:port 形式
URI reconstructURI(ServiceInstance instance, URI original);
}
=========》》》LoadBalancerAutoConfifiguration⾥⾯的内容剖析
第⼆处:注⼊resttemplate定制器
第三处:使⽤定制器给集合中的每⼀个resttemplate对象添加⼀个拦截器
==========》》》》分析LoadBalancerInterceptor.intercept()⽅法
⾮常核⼼的⼀个⽅法:RibbonLoadBalancerClient.execute()
=====》》》回到主配置类RibbonAutoConfifiguration
RibbonClientConfifiguration中装配了⼤脑和肢⼲
ZoneAwareLoadBalancer#chooseServer
⽗类:com.netflflix.loadbalancer.BaseLoadBalancer#chooseServer
在下图所示的RibbonLoadBalancerClient类的execute方法的return代码行打上断点,消费端Debug运行后,浏览器请求消费端,进入该方法
AbstractClientHttpRequest#execute
还是在RibbonClientConfiguration这个类中有一个ServerList
把⽬光聚焦到使⽤这个空对象ServerList的地⽅
进⼊enableAndInitLearnNewServersFeature()⽅法
进入ServerListUpdater接口的实现类EurekaNotificationServerListUpdater,在该类中找到start(final UpdateAction updateAction)方法:
/*
*
* Copyright 2013 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.netflix.loadbalancer;
import com.netflix.client.config.IClientConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
/**
* The most well known and basic load balancing strategy, i.e. Round Robin Rule.
*
* @author stonse
* @author Nikos Michalakis
*
*/
public class RoundRobinRule extends AbstractLoadBalancerRule {
private AtomicInteger nextServerCyclicCounter;
private static final boolean AVAILABLE_ONLY_SERVERS = true;
private static final boolean ALL_SERVERS = false;
private static Logger log = LoggerFactory.getLogger(RoundRobinRule.class);
public RoundRobinRule() {
nextServerCyclicCounter = new AtomicInteger(0);
}
public RoundRobinRule(ILoadBalancer lb) {
this();
setLoadBalancer(lb);
}
// 负载均衡策略类核⼼⽅法
public Server choose(ILoadBalancer lb, Object key) {
if (lb == null) {
log.warn("no load balancer");
return null;
}
Server server = null;
int count = 0;
while (server == null && count++ < 10) {
// 所有可⽤服务实例列表
List reachableServers = lb.getReachableServers();
// 所有服务实例列表
List allServers = lb.getAllServers();
int upCount = reachableServers.size();
int serverCount = allServers.size();
if ((upCount == 0) || (serverCount == 0)) {
log.warn("No up servers available from load balancer: " + lb);
return null;
}
// 获得⼀个轮询索引
int nextServerIndex = incrementAndGetModulo(serverCount);
// 根据索引取出服务实例对象
server = allServers.get(nextServerIndex);
if (server == null) {
/* Transient. */
Thread.yield();
continue;
}
// 判断服务可⽤后返回
if (server.isAlive() && (server.isReadyToServe())) {
return (server);
}
// Next.
server = null;
}
if (count >= 10) {
log.warn("No available alive servers after 10 tries from load balancer: "
+ lb);
}
return server;
}
/**
* Inspired by the implementation of {@link AtomicInteger#incrementAndGet()}.
*
* @param modulo The modulo to bound the value of the counter.
* @return The next value.
*/
private int incrementAndGetModulo(int modulo) {
for (;;) {
// 取出上次的计数
int current = nextServerCyclicCounter.get();
// 因为是轮询,计数+1之后对总数取模
int next = (current + 1) % modulo;
if (nextServerCyclicCounter.compareAndSet(current, next))
return next;
}
}
@Override
public Server choose(Object key) {
return choose(getLoadBalancer(), key);
}
@Override
public void initWithNiwsConfig(IClientConfig clientConfig) {
}
}