loadAppAndLoadBalancerIfNeed method

bool loadAppAndLoadBalancerIfNeed(
  1. {bool force = false}
)

加载APP信息和负载均衡客户端

Implementation

bool loadAppAndLoadBalancerIfNeed({bool force = false}) {
  if (!force && null != _app) {
    return true;
  }
  if (null == EurekaClient.instance) {
    logger.warning('正在初始化...');
    return false;
  }
  if (!EurekaClient.instance.ready) {
    logger.warning('正在加载服务列表...');
    return false;
  }

  logger.debug(
      'Start to refresh app:[id=$serviceId]\'s instance list and load balancer...');

  App app = EurekaClient.instance.apps.firstWhere((a) {
    return a.name?.toUpperCase() == serviceId.toUpperCase();
  }, orElse: () => null);
  if (null == app) {
    logger.warning('未找到目标服务[id=$serviceId]...');
    return false;
  }

  // 过滤关闭的实例
  List<Instance> _allInstances = []..addAll(app.instance);
  _allInstances.retainWhere((ins) => ins.status == 'UP');
  if (isEmpty(_allInstances)) {
    logger.warning('未找到目标服务[id=$serviceId]的可用实例...');
    return false;
  }
  _app = app;

  // 刷新实例负载均衡器
  List<String> remoteHostAndPorts = [];
  for (int i = 0; i < _allInstances.length; i++) {
    remoteHostAndPorts
        .add('${_allInstances[i].ipAddr}:${_allInstances[i].port}');
  }
  if (_remoteAddresses.length != _allInstances.length ||
      _remoteAddresses.any((add) => !remoteHostAndPorts.contains(add))) {
    List<Runner> runners = [];
    remoteHostAndPorts.forEach(
        (ra) => runners.add(EurekaRestClientRunner(ra, rootPath, _rc)));
    _loadBalancer?.close();
    _loadBalancer = LoadBalancer(runners);
  }

  logger.debug(
      'App:[id=$serviceId] loaded with ${remoteHostAndPorts.length} instances: $remoteHostAndPorts]');

  return true;
}