fix #367
This commit is contained in:
parent
e9bbe492bb
commit
15e0f30849
@ -16,7 +16,7 @@
|
||||
<parent>
|
||||
<groupId>com.alibaba.nacos</groupId>
|
||||
<artifactId>nacos-all</artifactId>
|
||||
<version>0.8.0-SNAPSHOT</version>
|
||||
<version>0.8.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
@ -22,6 +22,8 @@ package com.alibaba.nacos.api;
|
||||
*/
|
||||
public class PropertyKeyConst {
|
||||
|
||||
public final static String SERVER_PORT = "serverPort";
|
||||
|
||||
public final static String WEB_CONTEXT = "webContext";
|
||||
|
||||
public final static String ENDPOINT = "endpoint";
|
||||
|
@ -16,7 +16,7 @@
|
||||
<parent>
|
||||
<groupId>com.alibaba.nacos</groupId>
|
||||
<artifactId>nacos-all</artifactId>
|
||||
<version>0.8.0-SNAPSHOT</version>
|
||||
<version>0.8.1-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
|
@ -48,338 +48,339 @@ import java.util.Properties;
|
||||
@SuppressWarnings("PMD.ServiceOrDaoClassShouldEndWithImplRule")
|
||||
public class NacosNamingService implements NamingService {
|
||||
|
||||
/**
|
||||
* Each Naming instance should have different namespace.
|
||||
*/
|
||||
private String namespace;
|
||||
/**
|
||||
* Each Naming instance should have different namespace.
|
||||
*/
|
||||
private String namespace;
|
||||
|
||||
private String endpoint;
|
||||
private String endpoint;
|
||||
|
||||
private String serverList;
|
||||
private String serverList;
|
||||
|
||||
private String cacheDir;
|
||||
private String cacheDir;
|
||||
|
||||
private String logName;
|
||||
private String logName;
|
||||
|
||||
private HostReactor hostReactor;
|
||||
private HostReactor hostReactor;
|
||||
|
||||
private BeatReactor beatReactor;
|
||||
private BeatReactor beatReactor;
|
||||
|
||||
private EventDispatcher eventDispatcher;
|
||||
private EventDispatcher eventDispatcher;
|
||||
|
||||
private NamingProxy serverProxy;
|
||||
private NamingProxy serverProxy;
|
||||
|
||||
private void init() {
|
||||
private void init() {
|
||||
|
||||
namespace = System.getProperty(PropertyKeyConst.NAMESPACE);
|
||||
namespace = System.getProperty(PropertyKeyConst.NAMESPACE);
|
||||
|
||||
if (StringUtils.isEmpty(namespace)) {
|
||||
namespace = UtilAndComs.DEFAULT_NAMESPACE_ID;
|
||||
}
|
||||
if (StringUtils.isEmpty(namespace)) {
|
||||
namespace = UtilAndComs.DEFAULT_NAMESPACE_ID;
|
||||
}
|
||||
|
||||
logName = System.getProperty(UtilAndComs.NACOS_NAMING_LOG_NAME);
|
||||
if (StringUtils.isEmpty(logName)) {
|
||||
logName = "naming.log";
|
||||
}
|
||||
logName = System.getProperty(UtilAndComs.NACOS_NAMING_LOG_NAME);
|
||||
if (StringUtils.isEmpty(logName)) {
|
||||
logName = "naming.log";
|
||||
}
|
||||
|
||||
String logLevel = System.getProperty(UtilAndComs.NACOS_NAMING_LOG_LEVEL);
|
||||
if (StringUtils.isEmpty(logLevel)) {
|
||||
logLevel = "INFO";
|
||||
}
|
||||
String logLevel = System.getProperty(UtilAndComs.NACOS_NAMING_LOG_LEVEL);
|
||||
if (StringUtils.isEmpty(logLevel)) {
|
||||
logLevel = "INFO";
|
||||
}
|
||||
|
||||
LogUtils.setLogLevel(logLevel);
|
||||
LogUtils.setLogLevel(logLevel);
|
||||
|
||||
cacheDir = System.getProperty("com.alibaba.nacos.naming.cache.dir");
|
||||
if (StringUtils.isEmpty(cacheDir)) {
|
||||
cacheDir = System.getProperty("user.home") + "/nacos/naming/" + namespace;
|
||||
}
|
||||
}
|
||||
cacheDir = System.getProperty("com.alibaba.nacos.naming.cache.dir");
|
||||
if (StringUtils.isEmpty(cacheDir)) {
|
||||
cacheDir = System.getProperty("user.home") + "/nacos/naming/" + namespace;
|
||||
}
|
||||
}
|
||||
|
||||
public NacosNamingService(String serverList) {
|
||||
public NacosNamingService(String serverList) {
|
||||
|
||||
this.serverList = serverList;
|
||||
init();
|
||||
eventDispatcher = new EventDispatcher();
|
||||
serverProxy = new NamingProxy(namespace, endpoint, serverList);
|
||||
beatReactor = new BeatReactor(serverProxy);
|
||||
hostReactor = new HostReactor(eventDispatcher, serverProxy, cacheDir);
|
||||
}
|
||||
this.serverList = serverList;
|
||||
init();
|
||||
eventDispatcher = new EventDispatcher();
|
||||
serverProxy = new NamingProxy(namespace, endpoint, serverList);
|
||||
beatReactor = new BeatReactor(serverProxy);
|
||||
hostReactor = new HostReactor(eventDispatcher, serverProxy, cacheDir);
|
||||
}
|
||||
|
||||
public NacosNamingService(Properties properties) {
|
||||
public NacosNamingService(Properties properties) {
|
||||
|
||||
init();
|
||||
init();
|
||||
|
||||
serverList = properties.getProperty(PropertyKeyConst.SERVER_ADDR);
|
||||
serverList = properties.getProperty(PropertyKeyConst.SERVER_ADDR);
|
||||
|
||||
if (StringUtils.isNotEmpty(properties.getProperty(PropertyKeyConst.NAMESPACE))) {
|
||||
namespace = properties.getProperty(PropertyKeyConst.NAMESPACE);
|
||||
}
|
||||
if (StringUtils.isNotEmpty(properties.getProperty(PropertyKeyConst.NAMESPACE))) {
|
||||
namespace = properties.getProperty(PropertyKeyConst.NAMESPACE);
|
||||
}
|
||||
|
||||
if (StringUtils
|
||||
.isNotEmpty(properties.getProperty(UtilAndComs.NACOS_NAMING_LOG_NAME))) {
|
||||
logName = properties.getProperty(UtilAndComs.NACOS_NAMING_LOG_NAME);
|
||||
}
|
||||
if (StringUtils
|
||||
.isNotEmpty(properties.getProperty(UtilAndComs.NACOS_NAMING_LOG_NAME))) {
|
||||
logName = properties.getProperty(UtilAndComs.NACOS_NAMING_LOG_NAME);
|
||||
}
|
||||
|
||||
if (StringUtils.isNotEmpty(properties.getProperty(PropertyKeyConst.ENDPOINT))) {
|
||||
endpoint = properties.getProperty(PropertyKeyConst.ENDPOINT) + ":"
|
||||
+ properties.getProperty("address.server.port", "8080");
|
||||
}
|
||||
|
||||
if (StringUtils
|
||||
.isNotEmpty(properties.getProperty(PropertyKeyConst.WEB_CONTEXT))) {
|
||||
String tmpWebContext = properties.getProperty(PropertyKeyConst.WEB_CONTEXT);
|
||||
UtilAndComs.WEB_CONTEXT = tmpWebContext.indexOf("/") > -1 ? tmpWebContext
|
||||
: "/" + tmpWebContext;
|
||||
if (StringUtils.isNotEmpty(properties.getProperty(PropertyKeyConst.ENDPOINT))) {
|
||||
endpoint = properties.getProperty(PropertyKeyConst.ENDPOINT) + ":"
|
||||
+ properties.getProperty("address.server.port", "8080");
|
||||
}
|
||||
|
||||
UtilAndComs.NACOS_URL_BASE = UtilAndComs.WEB_CONTEXT + "/v1/ns";
|
||||
UtilAndComs.NACOS_URL_INSTANCE = UtilAndComs.NACOS_URL_BASE + "/instance";
|
||||
}
|
||||
|
||||
cacheDir = System.getProperty("user.home") + "/nacos/naming/" + namespace;
|
||||
|
||||
boolean loadCacheAtStart = false;
|
||||
if (StringUtils.isNotEmpty(
|
||||
properties.getProperty(PropertyKeyConst.NAMING_LOAD_CACHE_AT_START))) {
|
||||
loadCacheAtStart = BooleanUtils.toBoolean(
|
||||
properties.getProperty(PropertyKeyConst.NAMING_LOAD_CACHE_AT_START));
|
||||
}
|
||||
|
||||
int clientBeatThreadCount = NumberUtils.toInt(
|
||||
properties.getProperty(PropertyKeyConst.NAMING_CLIENT_BEAT_THREAD_COUNT),
|
||||
UtilAndComs.DEFAULT_CLIENT_BEAT_THREAD_COUNT);
|
||||
|
||||
int pollingThreadCount = NumberUtils.toInt(
|
||||
properties.getProperty(PropertyKeyConst.NAMING_POLLING_THREAD_COUNT),
|
||||
UtilAndComs.DEFAULT_POLLING_THREAD_COUNT);
|
||||
|
||||
eventDispatcher = new EventDispatcher();
|
||||
serverProxy = new NamingProxy(namespace, endpoint, serverList);
|
||||
beatReactor = new BeatReactor(serverProxy, clientBeatThreadCount);
|
||||
hostReactor = new HostReactor(eventDispatcher, serverProxy, cacheDir,
|
||||
loadCacheAtStart, pollingThreadCount);
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerInstance(String serviceName, String ip, int port)
|
||||
throws NacosException {
|
||||
registerInstance(serviceName, ip, port, Constants.NAMING_DEFAULT_CLUSTER_NAME);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerInstance(String serviceName, String ip, int port,
|
||||
String clusterName) throws NacosException {
|
||||
Instance instance = new Instance();
|
||||
instance.setIp(ip);
|
||||
instance.setPort(port);
|
||||
instance.setWeight(1.0);
|
||||
instance.setClusterName(clusterName);
|
||||
|
||||
registerInstance(serviceName, instance);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerInstance(String serviceName, Instance instance)
|
||||
throws NacosException {
|
||||
|
||||
BeatInfo beatInfo = new BeatInfo();
|
||||
beatInfo.setServiceName(serviceName);
|
||||
beatInfo.setIp(instance.getIp());
|
||||
beatInfo.setPort(instance.getPort());
|
||||
beatInfo.setCluster(instance.getClusterName());
|
||||
beatInfo.setWeight(instance.getWeight());
|
||||
beatInfo.setMetadata(instance.getMetadata());
|
||||
beatInfo.setScheduled(false);
|
||||
|
||||
beatReactor.addBeatInfo(serviceName, beatInfo);
|
||||
|
||||
serverProxy.registerService(serviceName, instance);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deregisterInstance(String serviceName, String ip, int port)
|
||||
throws NacosException {
|
||||
deregisterInstance(serviceName, ip, port, Constants.NAMING_DEFAULT_CLUSTER_NAME);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deregisterInstance(String serviceName, String ip, int port,
|
||||
String clusterName) throws NacosException {
|
||||
beatReactor.removeBeatInfo(serviceName, ip, port);
|
||||
serverProxy.deregisterService(serviceName, ip, port, clusterName);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Instance> getAllInstances(String serviceName) throws NacosException {
|
||||
return getAllInstances(serviceName, new ArrayList<String>());
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Instance> getAllInstances(String serviceName, boolean subscribe)
|
||||
throws NacosException {
|
||||
return getAllInstances(serviceName, new ArrayList<String>(), subscribe);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Instance> getAllInstances(String serviceName, List<String> clusters)
|
||||
throws NacosException {
|
||||
return getAllInstances(serviceName, clusters, true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Instance> getAllInstances(String serviceName, List<String> clusters,
|
||||
boolean subscribe) throws NacosException {
|
||||
|
||||
ServiceInfo serviceInfo;
|
||||
if (subscribe) {
|
||||
serviceInfo = hostReactor.getServiceInfo(serviceName,
|
||||
StringUtils.join(clusters, ","));
|
||||
}
|
||||
else {
|
||||
serviceInfo = hostReactor.getServiceInfoDirectlyFromServer(serviceName,
|
||||
StringUtils.join(clusters, ","));
|
||||
}
|
||||
List<Instance> list;
|
||||
if (serviceInfo == null
|
||||
|| CollectionUtils.isEmpty(list = serviceInfo.getHosts())) {
|
||||
return new ArrayList<Instance>();
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Instance> selectInstances(String serviceName, boolean healthy)
|
||||
throws NacosException {
|
||||
return selectInstances(serviceName, new ArrayList<String>(), healthy);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Instance> selectInstances(String serviceName, boolean healthy,
|
||||
boolean subscribe) throws NacosException {
|
||||
return selectInstances(serviceName, new ArrayList<String>(), healthy, subscribe);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Instance> selectInstances(String serviceName, List<String> clusters,
|
||||
boolean healthy) throws NacosException {
|
||||
return selectInstances(serviceName, clusters, healthy, true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Instance> selectInstances(String serviceName, List<String> clusters,
|
||||
boolean healthy, boolean subscribe) throws NacosException {
|
||||
ServiceInfo serviceInfo;
|
||||
if (subscribe) {
|
||||
serviceInfo = hostReactor.getServiceInfo(serviceName,
|
||||
StringUtils.join(clusters, ","));
|
||||
}
|
||||
else {
|
||||
serviceInfo = hostReactor.getServiceInfoDirectlyFromServer(serviceName,
|
||||
StringUtils.join(clusters, ","));
|
||||
}
|
||||
return selectInstances(serviceInfo, healthy);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Instance selectOneHealthyInstance(String serviceName) throws NacosException {
|
||||
return selectOneHealthyInstance(serviceName, new ArrayList<String>());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Instance selectOneHealthyInstance(String serviceName, boolean subscribe)
|
||||
throws NacosException {
|
||||
return selectOneHealthyInstance(serviceName, new ArrayList<String>(), subscribe);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Instance selectOneHealthyInstance(String serviceName, List<String> clusters)
|
||||
throws NacosException {
|
||||
return selectOneHealthyInstance(serviceName, clusters, true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Instance selectOneHealthyInstance(String serviceName, List<String> clusters,
|
||||
boolean subscribe) throws NacosException {
|
||||
|
||||
if (subscribe) {
|
||||
return Balancer.RandomByWeight.selectHost(hostReactor
|
||||
.getServiceInfo(serviceName, StringUtils.join(clusters, ",")));
|
||||
}
|
||||
else {
|
||||
return Balancer.RandomByWeight
|
||||
.selectHost(hostReactor.getServiceInfoDirectlyFromServer(serviceName,
|
||||
StringUtils.join(clusters, ",")));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void subscribe(String service, EventListener listener) {
|
||||
eventDispatcher.addListener(
|
||||
hostReactor.getServiceInfo(service, StringUtils.EMPTY), StringUtils.EMPTY,
|
||||
listener);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void subscribe(String service, List<String> clusters, EventListener listener) {
|
||||
eventDispatcher.addListener(
|
||||
hostReactor.getServiceInfo(service, StringUtils.join(clusters, ",")),
|
||||
StringUtils.join(clusters, ","), listener);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void unsubscribe(String service, EventListener listener) {
|
||||
eventDispatcher.removeListener(service, StringUtils.EMPTY, listener);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void unsubscribe(String service, List<String> clusters,
|
||||
EventListener listener) {
|
||||
eventDispatcher.removeListener(service, StringUtils.join(clusters, ","),
|
||||
listener);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ListView<String> getServicesOfServer(int pageNo, int pageSize)
|
||||
throws NacosException {
|
||||
return serverProxy.getServiceList(pageNo, pageSize);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ListView<String> getServicesOfServer(int pageNo, int pageSize,
|
||||
AbstractSelector selector) throws NacosException {
|
||||
return serverProxy.getServiceList(pageNo, pageSize, selector);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ServiceInfo> getSubscribeServices() {
|
||||
return eventDispatcher.getSubscribeServices();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getServerStatus() {
|
||||
return serverProxy.serverHealthy() ? "UP" : "DOWN";
|
||||
}
|
||||
|
||||
private List<Instance> selectInstances(ServiceInfo serviceInfo, boolean healthy) {
|
||||
List<Instance> list;
|
||||
if (serviceInfo == null
|
||||
|| CollectionUtils.isEmpty(list = serviceInfo.getHosts())) {
|
||||
return new ArrayList<Instance>();
|
||||
}
|
||||
|
||||
Iterator<Instance> iterator = list.iterator();
|
||||
while (iterator.hasNext()) {
|
||||
Instance instance = iterator.next();
|
||||
if (healthy != instance.isHealthy() || !instance.isEnabled()
|
||||
|| instance.getWeight() <= 0) {
|
||||
iterator.remove();
|
||||
}
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
public BeatReactor getBeatReactor() {
|
||||
return beatReactor;
|
||||
}
|
||||
initWebRootContext();
|
||||
|
||||
cacheDir = System.getProperty("user.home") + "/nacos/naming/" + namespace;
|
||||
|
||||
boolean loadCacheAtStart = false;
|
||||
if (StringUtils.isNotEmpty(
|
||||
properties.getProperty(PropertyKeyConst.NAMING_LOAD_CACHE_AT_START))) {
|
||||
loadCacheAtStart = BooleanUtils.toBoolean(
|
||||
properties.getProperty(PropertyKeyConst.NAMING_LOAD_CACHE_AT_START));
|
||||
}
|
||||
|
||||
int clientBeatThreadCount = NumberUtils.toInt(
|
||||
properties.getProperty(PropertyKeyConst.NAMING_CLIENT_BEAT_THREAD_COUNT),
|
||||
UtilAndComs.DEFAULT_CLIENT_BEAT_THREAD_COUNT);
|
||||
|
||||
int pollingThreadCount = NumberUtils.toInt(
|
||||
properties.getProperty(PropertyKeyConst.NAMING_POLLING_THREAD_COUNT),
|
||||
UtilAndComs.DEFAULT_POLLING_THREAD_COUNT);
|
||||
|
||||
eventDispatcher = new EventDispatcher();
|
||||
serverProxy = new NamingProxy(namespace, endpoint, serverList);
|
||||
beatReactor = new BeatReactor(serverProxy, clientBeatThreadCount);
|
||||
hostReactor = new HostReactor(eventDispatcher, serverProxy, cacheDir,
|
||||
loadCacheAtStart, pollingThreadCount);
|
||||
|
||||
}
|
||||
|
||||
private void initWebRootContext() {
|
||||
// support the web context with ali-yun if the app deploy by EDAS
|
||||
String webContext = System.getProperties().getProperty(PropertyKeyConst.WEB_CONTEXT);
|
||||
if (StringUtils.isNotEmpty(webContext)) {
|
||||
UtilAndComs.WEB_CONTEXT = webContext.indexOf("/") > -1 ? webContext
|
||||
: "/" + webContext;
|
||||
}
|
||||
|
||||
UtilAndComs.NACOS_URL_BASE = UtilAndComs.WEB_CONTEXT + "/v1/ns";
|
||||
UtilAndComs.NACOS_URL_INSTANCE = UtilAndComs.NACOS_URL_BASE + "/instance";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerInstance(String serviceName, String ip, int port)
|
||||
throws NacosException {
|
||||
registerInstance(serviceName, ip, port, Constants.NAMING_DEFAULT_CLUSTER_NAME);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerInstance(String serviceName, String ip, int port,
|
||||
String clusterName) throws NacosException {
|
||||
Instance instance = new Instance();
|
||||
instance.setIp(ip);
|
||||
instance.setPort(port);
|
||||
instance.setWeight(1.0);
|
||||
instance.setClusterName(clusterName);
|
||||
|
||||
registerInstance(serviceName, instance);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerInstance(String serviceName, Instance instance)
|
||||
throws NacosException {
|
||||
|
||||
BeatInfo beatInfo = new BeatInfo();
|
||||
beatInfo.setServiceName(serviceName);
|
||||
beatInfo.setIp(instance.getIp());
|
||||
beatInfo.setPort(instance.getPort());
|
||||
beatInfo.setCluster(instance.getClusterName());
|
||||
beatInfo.setWeight(instance.getWeight());
|
||||
beatInfo.setMetadata(instance.getMetadata());
|
||||
beatInfo.setScheduled(false);
|
||||
|
||||
beatReactor.addBeatInfo(serviceName, beatInfo);
|
||||
|
||||
serverProxy.registerService(serviceName, instance);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deregisterInstance(String serviceName, String ip, int port)
|
||||
throws NacosException {
|
||||
deregisterInstance(serviceName, ip, port, Constants.NAMING_DEFAULT_CLUSTER_NAME);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deregisterInstance(String serviceName, String ip, int port,
|
||||
String clusterName) throws NacosException {
|
||||
beatReactor.removeBeatInfo(serviceName, ip, port);
|
||||
serverProxy.deregisterService(serviceName, ip, port, clusterName);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Instance> getAllInstances(String serviceName) throws NacosException {
|
||||
return getAllInstances(serviceName, new ArrayList<String>());
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Instance> getAllInstances(String serviceName, boolean subscribe)
|
||||
throws NacosException {
|
||||
return getAllInstances(serviceName, new ArrayList<String>(), subscribe);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Instance> getAllInstances(String serviceName, List<String> clusters)
|
||||
throws NacosException {
|
||||
return getAllInstances(serviceName, clusters, true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Instance> getAllInstances(String serviceName, List<String> clusters,
|
||||
boolean subscribe) throws NacosException {
|
||||
|
||||
ServiceInfo serviceInfo;
|
||||
if (subscribe) {
|
||||
serviceInfo = hostReactor.getServiceInfo(serviceName,
|
||||
StringUtils.join(clusters, ","));
|
||||
} else {
|
||||
serviceInfo = hostReactor.getServiceInfoDirectlyFromServer(serviceName,
|
||||
StringUtils.join(clusters, ","));
|
||||
}
|
||||
List<Instance> list;
|
||||
if (serviceInfo == null
|
||||
|| CollectionUtils.isEmpty(list = serviceInfo.getHosts())) {
|
||||
return new ArrayList<Instance>();
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Instance> selectInstances(String serviceName, boolean healthy)
|
||||
throws NacosException {
|
||||
return selectInstances(serviceName, new ArrayList<String>(), healthy);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Instance> selectInstances(String serviceName, boolean healthy,
|
||||
boolean subscribe) throws NacosException {
|
||||
return selectInstances(serviceName, new ArrayList<String>(), healthy, subscribe);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Instance> selectInstances(String serviceName, List<String> clusters,
|
||||
boolean healthy) throws NacosException {
|
||||
return selectInstances(serviceName, clusters, healthy, true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Instance> selectInstances(String serviceName, List<String> clusters,
|
||||
boolean healthy, boolean subscribe) throws NacosException {
|
||||
ServiceInfo serviceInfo;
|
||||
if (subscribe) {
|
||||
serviceInfo = hostReactor.getServiceInfo(serviceName,
|
||||
StringUtils.join(clusters, ","));
|
||||
} else {
|
||||
serviceInfo = hostReactor.getServiceInfoDirectlyFromServer(serviceName,
|
||||
StringUtils.join(clusters, ","));
|
||||
}
|
||||
return selectInstances(serviceInfo, healthy);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Instance selectOneHealthyInstance(String serviceName) throws NacosException {
|
||||
return selectOneHealthyInstance(serviceName, new ArrayList<String>());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Instance selectOneHealthyInstance(String serviceName, boolean subscribe)
|
||||
throws NacosException {
|
||||
return selectOneHealthyInstance(serviceName, new ArrayList<String>(), subscribe);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Instance selectOneHealthyInstance(String serviceName, List<String> clusters)
|
||||
throws NacosException {
|
||||
return selectOneHealthyInstance(serviceName, clusters, true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Instance selectOneHealthyInstance(String serviceName, List<String> clusters,
|
||||
boolean subscribe) throws NacosException {
|
||||
|
||||
if (subscribe) {
|
||||
return Balancer.RandomByWeight.selectHost(hostReactor
|
||||
.getServiceInfo(serviceName, StringUtils.join(clusters, ",")));
|
||||
} else {
|
||||
return Balancer.RandomByWeight
|
||||
.selectHost(hostReactor.getServiceInfoDirectlyFromServer(serviceName,
|
||||
StringUtils.join(clusters, ",")));
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void subscribe(String service, EventListener listener) {
|
||||
eventDispatcher.addListener(
|
||||
hostReactor.getServiceInfo(service, StringUtils.EMPTY), StringUtils.EMPTY,
|
||||
listener);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void subscribe(String service, List<String> clusters, EventListener listener) {
|
||||
eventDispatcher.addListener(
|
||||
hostReactor.getServiceInfo(service, StringUtils.join(clusters, ",")),
|
||||
StringUtils.join(clusters, ","), listener);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void unsubscribe(String service, EventListener listener) {
|
||||
eventDispatcher.removeListener(service, StringUtils.EMPTY, listener);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void unsubscribe(String service, List<String> clusters,
|
||||
EventListener listener) {
|
||||
eventDispatcher.removeListener(service, StringUtils.join(clusters, ","),
|
||||
listener);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ListView<String> getServicesOfServer(int pageNo, int pageSize)
|
||||
throws NacosException {
|
||||
return serverProxy.getServiceList(pageNo, pageSize);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ListView<String> getServicesOfServer(int pageNo, int pageSize,
|
||||
AbstractSelector selector) throws NacosException {
|
||||
return serverProxy.getServiceList(pageNo, pageSize, selector);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ServiceInfo> getSubscribeServices() {
|
||||
return eventDispatcher.getSubscribeServices();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getServerStatus() {
|
||||
return serverProxy.serverHealthy() ? "UP" : "DOWN";
|
||||
}
|
||||
|
||||
private List<Instance> selectInstances(ServiceInfo serviceInfo, boolean healthy) {
|
||||
List<Instance> list;
|
||||
if (serviceInfo == null
|
||||
|| CollectionUtils.isEmpty(list = serviceInfo.getHosts())) {
|
||||
return new ArrayList<Instance>();
|
||||
}
|
||||
|
||||
Iterator<Instance> iterator = list.iterator();
|
||||
while (iterator.hasNext()) {
|
||||
Instance instance = iterator.next();
|
||||
if (healthy != instance.isHealthy() || !instance.isEnabled()
|
||||
|| instance.getWeight() <= 0) {
|
||||
iterator.remove();
|
||||
}
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
public BeatReactor getBeatReactor() {
|
||||
return beatReactor;
|
||||
}
|
||||
}
|
||||
|
@ -18,6 +18,7 @@ package com.alibaba.nacos.client.naming.net;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.alibaba.fastjson.TypeReference;
|
||||
import com.alibaba.nacos.api.PropertyKeyConst;
|
||||
import com.alibaba.nacos.api.common.Constants;
|
||||
import com.alibaba.nacos.api.exception.NacosException;
|
||||
import com.alibaba.nacos.api.naming.pojo.Instance;
|
||||
@ -47,398 +48,403 @@ import java.util.concurrent.TimeUnit;
|
||||
*/
|
||||
public class NamingProxy {
|
||||
|
||||
private static final int DEFAULT_SERVER_PORT = 8848;
|
||||
private static final int DEFAULT_SERVER_PORT = 8848;
|
||||
|
||||
private String namespaceId;
|
||||
private int serverPort = DEFAULT_SERVER_PORT;
|
||||
|
||||
private String endpoint;
|
||||
private String namespaceId;
|
||||
|
||||
private String nacosDomain;
|
||||
private String endpoint;
|
||||
|
||||
private List<String> serverList;
|
||||
private String nacosDomain;
|
||||
|
||||
private List<String> serversFromEndpoint = new ArrayList<String>();
|
||||
private List<String> serverList;
|
||||
|
||||
private long lastSrvRefTime = 0L;
|
||||
private List<String> serversFromEndpoint = new ArrayList<String>();
|
||||
|
||||
private long vipSrvRefInterMillis = TimeUnit.SECONDS.toMillis(30);
|
||||
private long lastSrvRefTime = 0L;
|
||||
|
||||
private CredentialService credentialService = CredentialService.getInstance();
|
||||
private long vipSrvRefInterMillis = TimeUnit.SECONDS.toMillis(30);
|
||||
|
||||
private ScheduledExecutorService executorService;
|
||||
private CredentialService credentialService = CredentialService.getInstance();
|
||||
|
||||
public NamingProxy(String namespaceId, String endpoint, String serverList) {
|
||||
private ScheduledExecutorService executorService;
|
||||
|
||||
this.namespaceId = namespaceId;
|
||||
this.endpoint = endpoint;
|
||||
if (StringUtils.isNotEmpty(serverList)) {
|
||||
this.serverList = Arrays.asList(serverList.split(","));
|
||||
if (this.serverList.size() == 1) {
|
||||
this.nacosDomain = serverList;
|
||||
}
|
||||
}
|
||||
public NamingProxy(String namespaceId, String endpoint, String serverList) {
|
||||
|
||||
executorService = new ScheduledThreadPoolExecutor(1, new ThreadFactory() {
|
||||
@Override
|
||||
public Thread newThread(Runnable r) {
|
||||
Thread t = new Thread(r);
|
||||
t.setName("com.alibaba.nacos.client.naming.serverlist.updater");
|
||||
t.setDaemon(true);
|
||||
return t;
|
||||
}
|
||||
});
|
||||
this.namespaceId = namespaceId;
|
||||
this.endpoint = endpoint;
|
||||
|
||||
executorService.scheduleWithFixedDelay(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
refreshSrvIfNeed();
|
||||
}
|
||||
}, 0, vipSrvRefInterMillis, TimeUnit.MILLISECONDS);
|
||||
|
||||
refreshSrvIfNeed();
|
||||
}
|
||||
|
||||
public List<String> getServerListFromEndpoint() {
|
||||
|
||||
try {
|
||||
String urlString = "http://" + endpoint + "/nacos/serverlist";
|
||||
|
||||
List<String> headers = Arrays.asList("Client-Version", UtilAndComs.VERSION,
|
||||
"Accept-Encoding", "gzip,deflate,sdch", "Connection", "Keep-Alive",
|
||||
"RequestId", UuidUtils.generateUuid());
|
||||
|
||||
HttpClient.HttpResult result = HttpClient.httpGet(urlString, headers, null,
|
||||
UtilAndComs.ENCODING);
|
||||
if (HttpURLConnection.HTTP_OK != result.code) {
|
||||
throw new IOException("Error while requesting: " + urlString
|
||||
+ "'. Server returned: " + result.code);
|
||||
}
|
||||
|
||||
String content = result.content;
|
||||
List<String> list = new ArrayList<String>();
|
||||
for (String line : IoUtils.readLines(new StringReader(content))) {
|
||||
if (!line.trim().isEmpty()) {
|
||||
list.add(line.trim());
|
||||
}
|
||||
}
|
||||
|
||||
return list;
|
||||
|
||||
}
|
||||
catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private void refreshSrvIfNeed() {
|
||||
try {
|
||||
|
||||
if (!CollectionUtils.isEmpty(serverList)) {
|
||||
LogUtils.LOG.debug("server list provided by user: " + serverList);
|
||||
return;
|
||||
}
|
||||
|
||||
if (System.currentTimeMillis() - lastSrvRefTime < vipSrvRefInterMillis) {
|
||||
return;
|
||||
}
|
||||
|
||||
List<String> list = getServerListFromEndpoint();
|
||||
|
||||
if (CollectionUtils.isEmpty(list)) {
|
||||
throw new Exception("Can not acquire Nacos list");
|
||||
}
|
||||
|
||||
if (!CollectionUtils.isEqualCollection(list, serversFromEndpoint)) {
|
||||
LogUtils.LOG.info("SERVER-LIST", "server list is updated: " + list);
|
||||
}
|
||||
|
||||
serversFromEndpoint = list;
|
||||
lastSrvRefTime = System.currentTimeMillis();
|
||||
}
|
||||
catch (Throwable e) {
|
||||
LogUtils.LOG.warn("failed to update server list", e);
|
||||
}
|
||||
}
|
||||
|
||||
public void registerService(String serviceName, Instance instance)
|
||||
throws NacosException {
|
||||
|
||||
LogUtils.LOG.info("REGISTER-SERVICE",
|
||||
"{} registering service {} with instance: {}", namespaceId, serviceName,
|
||||
instance);
|
||||
|
||||
final Map<String, String> params = new HashMap<String, String>(8);
|
||||
params.put(Constants.REQUEST_PARAM_NAMESPACE_ID, namespaceId);
|
||||
params.put("ip", instance.getIp());
|
||||
params.put("port", String.valueOf(instance.getPort()));
|
||||
params.put("weight", String.valueOf(instance.getWeight()));
|
||||
params.put("enable", String.valueOf(instance.isEnabled()));
|
||||
params.put("healthy", String.valueOf(instance.isHealthy()));
|
||||
params.put("metadata", JSON.toJSONString(instance.getMetadata()));
|
||||
params.put("serviceName", serviceName);
|
||||
params.put("clusterName", instance.getClusterName());
|
||||
|
||||
reqAPI(UtilAndComs.NACOS_URL_INSTANCE, params, HttpMethod.POST);
|
||||
|
||||
}
|
||||
|
||||
private void checkTenant(Map<String, String> params) {
|
||||
String tenantId = credentialService.getCredential().getTenantId();
|
||||
if (tenantId == null || tenantId.trim().length() == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
String tenantApp = System.getProperty("project.name");
|
||||
String tenantAk = credentialService.getCredential().getAccessKey();
|
||||
String tenantSK = credentialService.getCredential().getSecretKey();
|
||||
String signData = getSignData(params);
|
||||
String signature = SignUtil.sign(signData, tenantSK);
|
||||
params.put("signature", signature);
|
||||
params.put("data", signData);
|
||||
params.put("ak", tenantAk);
|
||||
params.put("app", tenantApp);
|
||||
params.put(Constants.REQUEST_PARAM_NAMESPACE_ID, tenantId);
|
||||
}
|
||||
catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
private static String getSignData(Map<String, String> params) {
|
||||
String data = "";
|
||||
return params.containsKey("dom")
|
||||
? System.currentTimeMillis() + "@@" + (String) params.get("dom")
|
||||
: String.valueOf(System.currentTimeMillis());
|
||||
}
|
||||
|
||||
public void deregisterService(String serviceName, String ip, int port, String cluster)
|
||||
throws NacosException {
|
||||
|
||||
LogUtils.LOG.info("DEREGISTER-SERVICE",
|
||||
"{} deregistering service {} with instance: {}:{}@{}", namespaceId,
|
||||
serviceName, ip, port, cluster);
|
||||
|
||||
final Map<String, String> params = new HashMap<String, String>(8);
|
||||
params.put(Constants.REQUEST_PARAM_NAMESPACE_ID, namespaceId);
|
||||
params.put("ip", ip);
|
||||
params.put("port", String.valueOf(port));
|
||||
params.put("serviceName", serviceName);
|
||||
params.put("cluster", cluster);
|
||||
|
||||
reqAPI(UtilAndComs.NACOS_URL_INSTANCE, params, HttpMethod.DELETE);
|
||||
}
|
||||
|
||||
public String queryList(String serviceName, String clusters, int udpPort,
|
||||
boolean healthyOnly) throws NacosException {
|
||||
|
||||
final Map<String, String> params = new HashMap<String, String>(8);
|
||||
params.put(Constants.REQUEST_PARAM_NAMESPACE_ID, namespaceId);
|
||||
params.put("serviceName", serviceName);
|
||||
params.put("clusters", clusters);
|
||||
params.put("udpPort", String.valueOf(udpPort));
|
||||
params.put("clientIP", NetUtils.localIP());
|
||||
params.put("healthyOnly", String.valueOf(healthyOnly));
|
||||
|
||||
return reqAPI(UtilAndComs.NACOS_URL_BASE + "/instance/list", params,
|
||||
HttpMethod.GET);
|
||||
}
|
||||
|
||||
public long sendBeat(BeatInfo beatInfo) {
|
||||
try {
|
||||
LogUtils.LOG.info("BEAT", "{} sending beat to server: {}", namespaceId,
|
||||
beatInfo.toString());
|
||||
Map<String, String> params = new HashMap<String, String>(4);
|
||||
params.put("beat", JSON.toJSONString(beatInfo));
|
||||
params.put(Constants.REQUEST_PARAM_NAMESPACE_ID, namespaceId);
|
||||
params.put("serviceName", beatInfo.getServiceName());
|
||||
String result = reqAPI(UtilAndComs.NACOS_URL_BASE + "/instance/beat", params,
|
||||
HttpMethod.PUT);
|
||||
JSONObject jsonObject = JSON.parseObject(result);
|
||||
|
||||
if (jsonObject != null) {
|
||||
return jsonObject.getLong("clientBeatInterval");
|
||||
}
|
||||
}
|
||||
catch (Exception e) {
|
||||
LogUtils.LOG.error("CLIENT-BEAT",
|
||||
"failed to send beat: " + JSON.toJSONString(beatInfo), e);
|
||||
}
|
||||
return 0L;
|
||||
}
|
||||
|
||||
public boolean serverHealthy() {
|
||||
|
||||
try {
|
||||
reqAPI(UtilAndComs.NACOS_URL_BASE + "/api/hello",
|
||||
new HashMap<String, String>(2));
|
||||
}
|
||||
catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public ListView<String> getServiceList(int pageNo, int pageSize)
|
||||
throws NacosException {
|
||||
return getServiceList(pageNo, pageSize, null);
|
||||
}
|
||||
|
||||
public ListView<String> getServiceList(int pageNo, int pageSize,
|
||||
AbstractSelector selector) throws NacosException {
|
||||
|
||||
Map<String, String> params = new HashMap<String, String>(4);
|
||||
params.put("pageNo", String.valueOf(pageNo));
|
||||
params.put("pageSize", String.valueOf(pageSize));
|
||||
params.put(Constants.REQUEST_PARAM_NAMESPACE_ID, namespaceId);
|
||||
|
||||
if (selector != null) {
|
||||
switch (SelectorType.valueOf(selector.getType())) {
|
||||
case none:
|
||||
break;
|
||||
case label:
|
||||
ExpressionSelector expressionSelector = (ExpressionSelector) selector;
|
||||
params.put("selector", JSON.toJSONString(expressionSelector));
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
String result = reqAPI(UtilAndComs.NACOS_URL_BASE + "/service/list", params);
|
||||
|
||||
JSONObject json = JSON.parseObject(result);
|
||||
ListView<String> listView = new ListView<String>();
|
||||
listView.setCount(json.getInteger("count"));
|
||||
listView.setData(JSON.parseObject(json.getString("doms"),
|
||||
new TypeReference<List<String>>() {
|
||||
}));
|
||||
|
||||
return listView;
|
||||
}
|
||||
|
||||
public String reqAPI(String api, Map<String, String> params) throws NacosException {
|
||||
|
||||
List<String> snapshot = serversFromEndpoint;
|
||||
if (!CollectionUtils.isEmpty(serverList)) {
|
||||
snapshot = serverList;
|
||||
}
|
||||
|
||||
return reqAPI(api, params, snapshot);
|
||||
}
|
||||
|
||||
public String reqAPI(String api, Map<String, String> params, String method)
|
||||
throws NacosException {
|
||||
|
||||
List<String> snapshot = serversFromEndpoint;
|
||||
if (!CollectionUtils.isEmpty(serverList)) {
|
||||
snapshot = serverList;
|
||||
}
|
||||
|
||||
return reqAPI(api, params, snapshot, method);
|
||||
}
|
||||
|
||||
public String callServer(String api, Map<String, String> params, String curServer)
|
||||
throws NacosException {
|
||||
return callServer(api, params, curServer, HttpMethod.GET);
|
||||
}
|
||||
|
||||
public String callServer(String api, Map<String, String> params, String curServer,
|
||||
String method) throws NacosException {
|
||||
long start = System.currentTimeMillis();
|
||||
long end = 0;
|
||||
|
||||
List<String> headers = Arrays.asList("Client-Version", UtilAndComs.VERSION,
|
||||
"Accept-Encoding", "gzip,deflate,sdch", "Connection", "Keep-Alive",
|
||||
"RequestId", UuidUtils.generateUuid());
|
||||
|
||||
String url;
|
||||
|
||||
if (!curServer.contains(UtilAndComs.SERVER_ADDR_IP_SPLITER)) {
|
||||
curServer = curServer + UtilAndComs.SERVER_ADDR_IP_SPLITER
|
||||
+ DEFAULT_SERVER_PORT;
|
||||
}
|
||||
|
||||
url = HttpClient.getPrefix() + curServer + api;
|
||||
|
||||
HttpClient.HttpResult result = HttpClient.request(url, headers, params,
|
||||
UtilAndComs.ENCODING, method);
|
||||
end = System.currentTimeMillis();
|
||||
|
||||
MetricsMonitor.getNamingRequestMonitor(method, url, String.valueOf(result.code))
|
||||
.record(end - start, TimeUnit.MILLISECONDS);
|
||||
|
||||
if (HttpURLConnection.HTTP_OK == result.code) {
|
||||
return result.content;
|
||||
}
|
||||
|
||||
if (HttpURLConnection.HTTP_NOT_MODIFIED == result.code) {
|
||||
return StringUtils.EMPTY;
|
||||
}
|
||||
|
||||
LogUtils.LOG.error("CALL-SERVER", "failed to req API:" + HttpClient.getPrefix()
|
||||
+ curServer + api + ". code:" + result.code + " msg: " + result.content);
|
||||
|
||||
throw new NacosException(NacosException.SERVER_ERROR,
|
||||
"failed to req API:" + HttpClient.getPrefix() + curServer + api
|
||||
+ ". code:" + result.code + " msg: " + result.content);
|
||||
}
|
||||
|
||||
public String reqAPI(String api, Map<String, String> params, List<String> servers) {
|
||||
return reqAPI(api, params, servers, HttpMethod.GET);
|
||||
}
|
||||
|
||||
public String reqAPI(String api, Map<String, String> params, List<String> servers,
|
||||
String method) {
|
||||
|
||||
params.put(Constants.REQUEST_PARAM_NAMESPACE_ID, getNamespaceId());
|
||||
checkTenant(params);
|
||||
|
||||
if (CollectionUtils.isEmpty(servers) && StringUtils.isEmpty(nacosDomain)) {
|
||||
throw new IllegalArgumentException("no server available");
|
||||
}
|
||||
|
||||
if (servers != null && !servers.isEmpty()) {
|
||||
if (StringUtils.isNotEmpty(serverList)) {
|
||||
this.serverList = Arrays.asList(serverList.split(","));
|
||||
if (this.serverList.size() == 1) {
|
||||
this.nacosDomain = serverList;
|
||||
}
|
||||
}
|
||||
|
||||
Random random = new Random(System.currentTimeMillis());
|
||||
int index = random.nextInt(servers.size());
|
||||
String serverPort = System.getProperties().getProperty(PropertyKeyConst.SERVER_PORT);
|
||||
if (StringUtils.isNotEmpty(serverPort)) {
|
||||
this.serverPort = Integer.valueOf(serverPort.trim());
|
||||
}
|
||||
|
||||
for (int i = 0; i < servers.size(); i++) {
|
||||
String server = servers.get(index);
|
||||
try {
|
||||
return callServer(api, params, server, method);
|
||||
}
|
||||
catch (Exception e) {
|
||||
LogUtils.LOG.error("NA",
|
||||
"req api:" + api + " failed, server(" + server, e);
|
||||
}
|
||||
executorService = new ScheduledThreadPoolExecutor(1, new ThreadFactory() {
|
||||
@Override
|
||||
public Thread newThread(Runnable r) {
|
||||
Thread t = new Thread(r);
|
||||
t.setName("com.alibaba.nacos.client.naming.serverlist.updater");
|
||||
t.setDaemon(true);
|
||||
return t;
|
||||
}
|
||||
});
|
||||
|
||||
index = (index + 1) % servers.size();
|
||||
}
|
||||
executorService.scheduleWithFixedDelay(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
refreshSrvIfNeed();
|
||||
}
|
||||
}, 0, vipSrvRefInterMillis, TimeUnit.MILLISECONDS);
|
||||
|
||||
throw new IllegalStateException("failed to req API:" + api
|
||||
+ " after all servers(" + servers + ") tried");
|
||||
}
|
||||
refreshSrvIfNeed();
|
||||
}
|
||||
|
||||
for (int i = 0; i < UtilAndComs.REQUEST_DOMAIN_RETRY_COUNT; i++) {
|
||||
try {
|
||||
return callServer(api, params, nacosDomain);
|
||||
}
|
||||
catch (Exception e) {
|
||||
LogUtils.LOG.error("NA",
|
||||
"req api:" + api + " failed, server(" + nacosDomain, e);
|
||||
}
|
||||
}
|
||||
public void setServerPort(int serverPort) {
|
||||
this.serverPort = serverPort;
|
||||
}
|
||||
|
||||
throw new IllegalStateException("failed to req API:/api/" + api
|
||||
+ " after all servers(" + servers + ") tried");
|
||||
public List<String> getServerListFromEndpoint() {
|
||||
|
||||
try {
|
||||
String urlString = "http://" + endpoint + "/nacos/serverlist";
|
||||
|
||||
List<String> headers = Arrays.asList("Client-Version", UtilAndComs.VERSION,
|
||||
"Accept-Encoding", "gzip,deflate,sdch", "Connection", "Keep-Alive",
|
||||
"RequestId", UuidUtils.generateUuid());
|
||||
|
||||
HttpClient.HttpResult result = HttpClient.httpGet(urlString, headers, null,
|
||||
UtilAndComs.ENCODING);
|
||||
if (HttpURLConnection.HTTP_OK != result.code) {
|
||||
throw new IOException("Error while requesting: " + urlString
|
||||
+ "'. Server returned: " + result.code);
|
||||
}
|
||||
|
||||
String content = result.content;
|
||||
List<String> list = new ArrayList<String>();
|
||||
for (String line : IoUtils.readLines(new StringReader(content))) {
|
||||
if (!line.trim().isEmpty()) {
|
||||
list.add(line.trim());
|
||||
}
|
||||
}
|
||||
|
||||
return list;
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private void refreshSrvIfNeed() {
|
||||
try {
|
||||
|
||||
if (!CollectionUtils.isEmpty(serverList)) {
|
||||
LogUtils.LOG.debug("server list provided by user: " + serverList);
|
||||
return;
|
||||
}
|
||||
|
||||
if (System.currentTimeMillis() - lastSrvRefTime < vipSrvRefInterMillis) {
|
||||
return;
|
||||
}
|
||||
|
||||
List<String> list = getServerListFromEndpoint();
|
||||
|
||||
if (CollectionUtils.isEmpty(list)) {
|
||||
throw new Exception("Can not acquire Nacos list");
|
||||
}
|
||||
|
||||
if (!CollectionUtils.isEqualCollection(list, serversFromEndpoint)) {
|
||||
LogUtils.LOG.info("SERVER-LIST", "server list is updated: " + list);
|
||||
}
|
||||
|
||||
serversFromEndpoint = list;
|
||||
lastSrvRefTime = System.currentTimeMillis();
|
||||
} catch (Throwable e) {
|
||||
LogUtils.LOG.warn("failed to update server list", e);
|
||||
}
|
||||
}
|
||||
|
||||
public void registerService(String serviceName, Instance instance)
|
||||
throws NacosException {
|
||||
|
||||
LogUtils.LOG.info("REGISTER-SERVICE",
|
||||
"{} registering service {} with instance: {}", namespaceId, serviceName,
|
||||
instance);
|
||||
|
||||
final Map<String, String> params = new HashMap<String, String>(8);
|
||||
params.put(Constants.REQUEST_PARAM_NAMESPACE_ID, namespaceId);
|
||||
params.put("ip", instance.getIp());
|
||||
params.put("port", String.valueOf(instance.getPort()));
|
||||
params.put("weight", String.valueOf(instance.getWeight()));
|
||||
params.put("enable", String.valueOf(instance.isEnabled()));
|
||||
params.put("healthy", String.valueOf(instance.isHealthy()));
|
||||
params.put("metadata", JSON.toJSONString(instance.getMetadata()));
|
||||
params.put("serviceName", serviceName);
|
||||
params.put("clusterName", instance.getClusterName());
|
||||
|
||||
reqAPI(UtilAndComs.NACOS_URL_INSTANCE, params, HttpMethod.POST);
|
||||
|
||||
}
|
||||
|
||||
private void checkTenant(Map<String, String> params) {
|
||||
String tenantId = credentialService.getCredential().getTenantId();
|
||||
if (tenantId == null || tenantId.trim().length() == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
String tenantApp = System.getProperty("project.name");
|
||||
String tenantAk = credentialService.getCredential().getAccessKey();
|
||||
String tenantSK = credentialService.getCredential().getSecretKey();
|
||||
String signData = getSignData(params);
|
||||
String signature = SignUtil.sign(signData, tenantSK);
|
||||
params.put("signature", signature);
|
||||
params.put("data", signData);
|
||||
params.put("ak", tenantAk);
|
||||
params.put("app", tenantApp);
|
||||
params.put(Constants.REQUEST_PARAM_NAMESPACE_ID, tenantId);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
private static String getSignData(Map<String, String> params) {
|
||||
String data = "";
|
||||
return params.containsKey("dom")
|
||||
? System.currentTimeMillis() + "@@" + (String) params.get("dom")
|
||||
: String.valueOf(System.currentTimeMillis());
|
||||
}
|
||||
|
||||
public void deregisterService(String serviceName, String ip, int port, String cluster)
|
||||
throws NacosException {
|
||||
|
||||
LogUtils.LOG.info("DEREGISTER-SERVICE",
|
||||
"{} deregistering service {} with instance: {}:{}@{}", namespaceId,
|
||||
serviceName, ip, port, cluster);
|
||||
|
||||
final Map<String, String> params = new HashMap<String, String>(8);
|
||||
params.put(Constants.REQUEST_PARAM_NAMESPACE_ID, namespaceId);
|
||||
params.put("ip", ip);
|
||||
params.put("port", String.valueOf(port));
|
||||
params.put("serviceName", serviceName);
|
||||
params.put("cluster", cluster);
|
||||
|
||||
reqAPI(UtilAndComs.NACOS_URL_INSTANCE, params, HttpMethod.DELETE);
|
||||
}
|
||||
|
||||
public String queryList(String serviceName, String clusters, int udpPort,
|
||||
boolean healthyOnly) throws NacosException {
|
||||
|
||||
final Map<String, String> params = new HashMap<String, String>(8);
|
||||
params.put(Constants.REQUEST_PARAM_NAMESPACE_ID, namespaceId);
|
||||
params.put("serviceName", serviceName);
|
||||
params.put("clusters", clusters);
|
||||
params.put("udpPort", String.valueOf(udpPort));
|
||||
params.put("clientIP", NetUtils.localIP());
|
||||
params.put("healthyOnly", String.valueOf(healthyOnly));
|
||||
|
||||
return reqAPI(UtilAndComs.NACOS_URL_BASE + "/instance/list", params,
|
||||
HttpMethod.GET);
|
||||
}
|
||||
|
||||
public long sendBeat(BeatInfo beatInfo) {
|
||||
try {
|
||||
LogUtils.LOG.info("BEAT", "{} sending beat to server: {}", namespaceId,
|
||||
beatInfo.toString());
|
||||
Map<String, String> params = new HashMap<String, String>(4);
|
||||
params.put("beat", JSON.toJSONString(beatInfo));
|
||||
params.put(Constants.REQUEST_PARAM_NAMESPACE_ID, namespaceId);
|
||||
params.put("serviceName", beatInfo.getServiceName());
|
||||
String result = reqAPI(UtilAndComs.NACOS_URL_BASE + "/instance/beat", params,
|
||||
HttpMethod.PUT);
|
||||
JSONObject jsonObject = JSON.parseObject(result);
|
||||
|
||||
if (jsonObject != null) {
|
||||
return jsonObject.getLong("clientBeatInterval");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LogUtils.LOG.error("CLIENT-BEAT",
|
||||
"failed to send beat: " + JSON.toJSONString(beatInfo), e);
|
||||
}
|
||||
return 0L;
|
||||
}
|
||||
|
||||
public boolean serverHealthy() {
|
||||
|
||||
try {
|
||||
reqAPI(UtilAndComs.NACOS_URL_BASE + "/api/hello",
|
||||
new HashMap<String, String>(2));
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public ListView<String> getServiceList(int pageNo, int pageSize)
|
||||
throws NacosException {
|
||||
return getServiceList(pageNo, pageSize, null);
|
||||
}
|
||||
|
||||
public ListView<String> getServiceList(int pageNo, int pageSize,
|
||||
AbstractSelector selector) throws NacosException {
|
||||
|
||||
Map<String, String> params = new HashMap<String, String>(4);
|
||||
params.put("pageNo", String.valueOf(pageNo));
|
||||
params.put("pageSize", String.valueOf(pageSize));
|
||||
params.put(Constants.REQUEST_PARAM_NAMESPACE_ID, namespaceId);
|
||||
|
||||
if (selector != null) {
|
||||
switch (SelectorType.valueOf(selector.getType())) {
|
||||
case none:
|
||||
break;
|
||||
case label:
|
||||
ExpressionSelector expressionSelector = (ExpressionSelector) selector;
|
||||
params.put("selector", JSON.toJSONString(expressionSelector));
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
String result = reqAPI(UtilAndComs.NACOS_URL_BASE + "/service/list", params);
|
||||
|
||||
JSONObject json = JSON.parseObject(result);
|
||||
ListView<String> listView = new ListView<String>();
|
||||
listView.setCount(json.getInteger("count"));
|
||||
listView.setData(JSON.parseObject(json.getString("doms"),
|
||||
new TypeReference<List<String>>() {
|
||||
}));
|
||||
|
||||
return listView;
|
||||
}
|
||||
|
||||
public String reqAPI(String api, Map<String, String> params) throws NacosException {
|
||||
|
||||
List<String> snapshot = serversFromEndpoint;
|
||||
if (!CollectionUtils.isEmpty(serverList)) {
|
||||
snapshot = serverList;
|
||||
}
|
||||
|
||||
return reqAPI(api, params, snapshot);
|
||||
}
|
||||
|
||||
public String reqAPI(String api, Map<String, String> params, String method)
|
||||
throws NacosException {
|
||||
|
||||
List<String> snapshot = serversFromEndpoint;
|
||||
if (!CollectionUtils.isEmpty(serverList)) {
|
||||
snapshot = serverList;
|
||||
}
|
||||
|
||||
return reqAPI(api, params, snapshot, method);
|
||||
}
|
||||
|
||||
public String callServer(String api, Map<String, String> params, String curServer)
|
||||
throws NacosException {
|
||||
return callServer(api, params, curServer, HttpMethod.GET);
|
||||
}
|
||||
|
||||
public String callServer(String api, Map<String, String> params, String curServer,
|
||||
String method) throws NacosException {
|
||||
long start = System.currentTimeMillis();
|
||||
long end = 0;
|
||||
|
||||
List<String> headers = Arrays.asList("Client-Version", UtilAndComs.VERSION,
|
||||
"Accept-Encoding", "gzip,deflate,sdch", "Connection", "Keep-Alive",
|
||||
"RequestId", UuidUtils.generateUuid());
|
||||
|
||||
String url;
|
||||
|
||||
if (!curServer.contains(UtilAndComs.SERVER_ADDR_IP_SPLITER)) {
|
||||
curServer = curServer + UtilAndComs.SERVER_ADDR_IP_SPLITER
|
||||
+ serverPort;
|
||||
}
|
||||
|
||||
url = HttpClient.getPrefix() + curServer + api;
|
||||
|
||||
HttpClient.HttpResult result = HttpClient.request(url, headers, params,
|
||||
UtilAndComs.ENCODING, method);
|
||||
end = System.currentTimeMillis();
|
||||
|
||||
MetricsMonitor.getNamingRequestMonitor(method, url, String.valueOf(result.code))
|
||||
.record(end - start, TimeUnit.MILLISECONDS);
|
||||
|
||||
if (HttpURLConnection.HTTP_OK == result.code) {
|
||||
return result.content;
|
||||
}
|
||||
|
||||
if (HttpURLConnection.HTTP_NOT_MODIFIED == result.code) {
|
||||
return StringUtils.EMPTY;
|
||||
}
|
||||
|
||||
LogUtils.LOG.error("CALL-SERVER", "failed to req API:" + HttpClient.getPrefix()
|
||||
+ curServer + api + ". code:" + result.code + " msg: " + result.content);
|
||||
|
||||
throw new NacosException(NacosException.SERVER_ERROR,
|
||||
"failed to req API:" + HttpClient.getPrefix() + curServer + api
|
||||
+ ". code:" + result.code + " msg: " + result.content);
|
||||
}
|
||||
|
||||
public String reqAPI(String api, Map<String, String> params, List<String> servers) {
|
||||
return reqAPI(api, params, servers, HttpMethod.GET);
|
||||
}
|
||||
|
||||
public String reqAPI(String api, Map<String, String> params, List<String> servers,
|
||||
String method) {
|
||||
|
||||
params.put(Constants.REQUEST_PARAM_NAMESPACE_ID, getNamespaceId());
|
||||
checkTenant(params);
|
||||
|
||||
if (CollectionUtils.isEmpty(servers) && StringUtils.isEmpty(nacosDomain)) {
|
||||
throw new IllegalArgumentException("no server available");
|
||||
}
|
||||
|
||||
}
|
||||
if (servers != null && !servers.isEmpty()) {
|
||||
|
||||
public String getNamespaceId() {
|
||||
return namespaceId;
|
||||
}
|
||||
Random random = new Random(System.currentTimeMillis());
|
||||
int index = random.nextInt(servers.size());
|
||||
|
||||
for (int i = 0; i < servers.size(); i++) {
|
||||
String server = servers.get(index);
|
||||
try {
|
||||
return callServer(api, params, server, method);
|
||||
} catch (Exception e) {
|
||||
LogUtils.LOG.error("NA",
|
||||
"req api:" + api + " failed, server(" + server, e);
|
||||
}
|
||||
|
||||
index = (index + 1) % servers.size();
|
||||
}
|
||||
|
||||
throw new IllegalStateException("failed to req API:" + api
|
||||
+ " after all servers(" + servers + ") tried");
|
||||
}
|
||||
|
||||
for (int i = 0; i < UtilAndComs.REQUEST_DOMAIN_RETRY_COUNT; i++) {
|
||||
try {
|
||||
return callServer(api, params, nacosDomain);
|
||||
} catch (Exception e) {
|
||||
LogUtils.LOG.error("NA",
|
||||
"req api:" + api + " failed, server(" + nacosDomain, e);
|
||||
}
|
||||
}
|
||||
|
||||
throw new IllegalStateException("failed to req API:/api/" + api
|
||||
+ " after all servers(" + servers + ") tried");
|
||||
|
||||
}
|
||||
|
||||
public String getNamespaceId() {
|
||||
return namespaceId;
|
||||
}
|
||||
}
|
||||
|
@ -18,7 +18,7 @@
|
||||
<parent>
|
||||
<artifactId>nacos-all</artifactId>
|
||||
<groupId>com.alibaba.nacos</groupId>
|
||||
<version>0.8.0-SNAPSHOT</version>
|
||||
<version>0.8.1-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
@ -18,7 +18,7 @@
|
||||
<parent>
|
||||
<groupId>com.alibaba.nacos</groupId>
|
||||
<artifactId>nacos-all</artifactId>
|
||||
<version>0.8.0-SNAPSHOT</version>
|
||||
<version>0.8.1-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
@ -17,7 +17,7 @@
|
||||
<parent>
|
||||
<groupId>com.alibaba.nacos</groupId>
|
||||
<artifactId>nacos-all</artifactId>
|
||||
<version>0.8.0-SNAPSHOT</version>
|
||||
<version>0.8.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
@ -18,7 +18,7 @@
|
||||
<parent>
|
||||
<groupId>com.alibaba.nacos</groupId>
|
||||
<artifactId>nacos-all</artifactId>
|
||||
<version>0.8.0-SNAPSHOT</version>
|
||||
<version>0.8.1-SNAPSHOT</version>
|
||||
</parent>
|
||||
<artifactId>nacos-console</artifactId>
|
||||
<!--<packaging>war</packaging>-->
|
||||
|
@ -18,7 +18,7 @@
|
||||
<parent>
|
||||
<groupId>com.alibaba.nacos</groupId>
|
||||
<artifactId>nacos-all</artifactId>
|
||||
<version>0.8.0-SNAPSHOT</version>
|
||||
<version>0.8.1-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
|
@ -18,7 +18,7 @@
|
||||
<parent>
|
||||
<groupId>com.alibaba.nacos</groupId>
|
||||
<artifactId>nacos-all</artifactId>
|
||||
<version>0.8.0-SNAPSHOT</version>
|
||||
<version>0.8.1-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
|
@ -18,7 +18,7 @@
|
||||
<parent>
|
||||
<groupId>com.alibaba.nacos</groupId>
|
||||
<artifactId>nacos-all</artifactId>
|
||||
<version>0.8.0-SNAPSHOT</version>
|
||||
<version>0.8.1-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
|
@ -18,7 +18,7 @@
|
||||
<parent>
|
||||
<groupId>com.alibaba.nacos</groupId>
|
||||
<artifactId>nacos-all</artifactId>
|
||||
<version>0.8.0-SNAPSHOT</version>
|
||||
<version>0.8.1-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
|
||||
|
3
pom.xml
3
pom.xml
@ -21,7 +21,7 @@
|
||||
<inceptionYear>2018</inceptionYear>
|
||||
<groupId>com.alibaba.nacos</groupId>
|
||||
<artifactId>nacos-all</artifactId>
|
||||
<version>0.8.0-SNAPSHOT</version>
|
||||
<version>0.8.1-SNAPSHOT</version>
|
||||
<packaging>pom</packaging>
|
||||
|
||||
<name>Alibaba NACOS ${project.version}</name>
|
||||
@ -742,5 +742,6 @@
|
||||
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
</project>
|
||||
|
||||
|
@ -17,7 +17,7 @@
|
||||
<parent>
|
||||
<groupId>com.alibaba.nacos</groupId>
|
||||
<artifactId>nacos-all</artifactId>
|
||||
<version>0.8.0-SNAPSHOT</version>
|
||||
<version>0.8.1-SNAPSHOT</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
Loading…
Reference in New Issue
Block a user