简介
用来了解下Ribbon选择服务实例和服务实例列表更新机制;
选择服务实例
涉及到如下几个类:
- 1.ILoadBalancer:负载均衡对象,用于封装ServerList;
- 2.IRule:实例选择规则对象,决定采用何种规则进行实例选择;
- 3.Predicate:断言类,选择规则的具体实现;
- 4.LoadBalancerStats:用于保存实例状态的缓存类;
更新过程
Ribbon更新服务实例主要依靠的对象有:
- PollingServerListUpdater:该对象是用来更新服务实例包装类,其该类启动时通过初始化一个LazyHolder,LazyHolder是一个定时任务Excutor的包装类,该Executor会定时调用updateAction.doUpdate()方法进行service instance更新,源码如下:
@Override
public synchronized void start(final UpdateAction updateAction) {
if (isActive.compareAndSet(false, true)) {
final Runnable wrapperRunnable = new Runnable() {
@Override
public void run() {
if (!isActive.get()) {
if (scheduledFuture != null) {
scheduledFuture.cancel(true);
}
return;
}
try {
updateAction.doUpdate();//服务实例更新
lastUpdated = System.currentTimeMillis();
} catch (Exception e) {
logger.warn("Failed one update cycle", e);
}
}
};
//获取定时Executor进行任务调度
scheduledFuture = getRefreshExecutor().scheduleWithFixedDelay(
wrapperRunnable,
initialDelayMs,
refreshIntervalMs,
TimeUnit.MILLISECONDS
);
} else {
logger.info("Already active, no-op");
}
}
- ServerListUpdater.UpdateAction源码如下:
protected final ServerListUpdater.UpdateAction updateAction = new ServerListUpdater.UpdateAction() {
@Override
public void doUpdate() {
updateListOfServers();
}
};
- ServerList的具体实现类serverListImpl进行服务实例更新:
@VisibleForTesting
public void updateListOfServers() {
List<T> servers = new ArrayList<T>();
if (serverListImpl != null) {
//获取最新服务实例
servers = serverListImpl.getUpdatedListOfServers();
LOGGER.debug("List of Servers for {} obtained from Discovery client: {}",
getIdentifier(), servers);
if (filter != null) {
servers = filter.getFilteredListOfServers(servers);
LOGGER.debug("Filtered List of Servers for {} obtained from Discovery client: {}",
getIdentifier(), servers);
}
}
updateAllServerList(servers);
}