import com.alibaba.cloud.nacos.ribbon.NacosServer;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.commons.util.InetUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
@Slf4j
@Configuration
public class CustomizeLoadBalancerRule extends AbstractLoadBalancerRule implements InitializingBean {
@Autowired
private InetUtils inetUtils;
private String localIp = null;
private final int TOTAL_RETRY = 10;
private final AtomicInteger nextIndex = new AtomicInteger();
@Override
public void initWithNiwsConfig(IClientConfig iClientConfig) {
log.info("ClientName: {}", iClientConfig.getClientName());
}
@Override
public Server choose(Object key) {
Server server = null;
try {
ILoadBalancer lb = getLoadBalancer();
int retry = 0;
while (server == null && retry++ < TOTAL_RETRY) {
List<Server> reachableServers = lb.getReachableServers();
List<Server> allServers = lb.getAllServers();
int upCount = reachableServers.size();
int serverCount = allServers.size();
if (upCount == 0 || serverCount == 0) {
log.warn("无可用服务: {}", lb);
return null;
}
Server localServer = null;
for (Server server1 : reachableServers) {
NacosServer nacosServer = (NacosServer) server1;
Instance instance = nacosServer.getInstance();
String ip = instance.getIp();
if (ip.equals(localIp)) {
if (server1.isAlive() && (server1.isReadyToServe())) {
localServer = server1;
}
}
}
if(null != localServer){
return localServer;
}
int nextServerIndex = incrementAndGetModulo(serverCount);
server = allServers.get(nextServerIndex);
if (server == null) {
Thread.yield();
continue;
}
if (server.isAlive() && (server.isReadyToServe())) {
return server;
}
server = null;
}
if (retry >= TOTAL_RETRY) {
log.warn("重试{}次, 仍无可用服务: {}", retry, lb);
}
} catch (Exception e) {
log.error("rule error", e);
throw new RuntimeException("rule error");
}
return server;
}
@Override
public void afterPropertiesSet() throws Exception {
localIp = inetUtils.findFirstNonLoopbackHostInfo().getIpAddress();
log.info("本机ip地址:{}", localIp);
}
@Profile({"dev"})
@Bean
public IRule ribbonRule() {
return new CustomizeLoadBalancerRule();
}
private int incrementAndGetModulo(int modulo) {
for (;;) {
int current = nextIndex.get();
int next = (current + 1) % modulo;
if (nextIndex.compareAndSet(current, next) && current < modulo) {
return current;
}
}
}
}