org.zodiac.loadbalancer.ribbon.predicate.MetadataServer Maven / Gradle / Ivy
package org.zodiac.loadbalancer.ribbon.predicate;
import com.netflix.loadbalancer.Server;
import org.zodiac.commons.util.Colls;
import org.zodiac.sdk.toolkit.util.ReflectionUtil;
import org.zodiac.sdk.toolkit.util.collection.CollUtil;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
/**
* 利用反射,让 server 直接支持 nacos、consul、Eureka。
*
*/
public class MetadataServer {
private final static Map, Method> METHOD_MAP = CollUtil.concurrentMap(1);
private final static List> NO_METHOD_LIST = CollUtil.list();
private final Server server;
private final Method method;
public MetadataServer(Server server) {
this.server = server;
this.method = findMetadataMethod(server.getClass());
}
private static Method findMetadataMethod(Class> serverClass) {
/*缓存中有方法。*/
Method method = METHOD_MAP.get(serverClass);
if (method != null) {
return method;
}
/*没有方法。*/
if (NO_METHOD_LIST.contains(serverClass)) {
return null;
}
/*查找 getMetadata 方法。*/
method = ReflectionUtil.findMethod(serverClass, "getMetadata");
if (method == null) {
NO_METHOD_LIST.add(serverClass);
} else {
METHOD_MAP.put(serverClass, method);
}
return method;
}
public boolean hasMetadata() {
return method != null;
}
@SuppressWarnings("unchecked")
public Map getMetadata() {
return (Map)ReflectionUtil.invokeMethod(method, server);
}
}