fix(nacos-client:config): Fix code conflicts

This commit is contained in:
chuntaojun 2019-06-18 23:27:28 +08:00
commit c91f99b82e
53 changed files with 673 additions and 74 deletions

View File

@ -52,6 +52,8 @@ public class PropertyKeyConst {
public final static String MAX_RETRY = "maxRetry"; public final static String MAX_RETRY = "maxRetry";
public final static String ENABLE_REMOTE_SYNC_CONFIG = "enableRemoteSyncConfig";
public final static String NAMING_LOAD_CACHE_AT_START = "namingLoadCacheAtStart"; public final static String NAMING_LOAD_CACHE_AT_START = "namingLoadCacheAtStart";
public final static String NAMING_CLIENT_BEAT_THREAD_COUNT = "namingClientBeatThreadCount"; public final static String NAMING_CLIENT_BEAT_THREAD_COUNT = "namingClientBeatThreadCount";

View File

@ -36,6 +36,23 @@ public interface ConfigService {
*/ */
String getConfig(String dataId, String group, long timeoutMs) throws NacosException; String getConfig(String dataId, String group, long timeoutMs) throws NacosException;
/**
* Get config and register Listener
*
* If you want to pull it yourself when the program starts to get the configuration for the first time,
* and the registered Listener is used for future configuration updates, you can keep the original
* code unchanged, just add the system parameter: enableRemoteSyncConfig = "true" ( But there is network overhead);
* therefore we recommend that you use this interface directly
*
* @param dataId dataId
* @param group group
* @param timeoutMs read timeout
* @param listener {@link Listener}
* @return config value
* @throws NacosException NacosException
*/
String getConfigAndSignListener(String dataId, String group, long timeoutMs, Listener listener) throws NacosException;
/** /**
* Add a listener to the configuration, after the server modified the * Add a listener to the configuration, after the server modified the
* configuration, the client will use the incoming listener callback. * configuration, the client will use the incoming listener callback.

View File

@ -193,6 +193,7 @@ public abstract class AbstractHealthChecker implements Cloneable {
} }
@Override
public Tcp clone() throws CloneNotSupportedException { public Tcp clone() throws CloneNotSupportedException {
Tcp config = new Tcp(); Tcp config = new Tcp();
config.setType(this.type); config.setType(this.type);

View File

@ -27,6 +27,7 @@ import com.alibaba.nacos.client.config.filter.impl.ConfigResponse;
import com.alibaba.nacos.client.config.http.HttpAgent; import com.alibaba.nacos.client.config.http.HttpAgent;
import com.alibaba.nacos.client.config.http.MetricsHttpAgent; import com.alibaba.nacos.client.config.http.MetricsHttpAgent;
import com.alibaba.nacos.client.config.http.ServerHttpAgent; import com.alibaba.nacos.client.config.http.ServerHttpAgent;
import com.alibaba.nacos.client.config.impl.CacheData;
import com.alibaba.nacos.client.config.impl.ClientWorker; import com.alibaba.nacos.client.config.impl.ClientWorker;
import com.alibaba.nacos.client.config.impl.HttpSimpleClient.HttpResult; import com.alibaba.nacos.client.config.impl.HttpSimpleClient.HttpResult;
import com.alibaba.nacos.client.config.impl.LocalConfigInfoProcessor; import com.alibaba.nacos.client.config.impl.LocalConfigInfoProcessor;
@ -122,6 +123,13 @@ public class NacosConfigService implements ConfigService {
return getConfigInner(namespace, dataId, group, timeoutMs); return getConfigInner(namespace, dataId, group, timeoutMs);
} }
@Override
public String getConfigAndSignListener(String dataId, String group, long timeoutMs, Listener listener) throws NacosException {
String content = getConfig(dataId, group, timeoutMs);
worker.addTenantListenersWithContent(dataId, group, content, Arrays.asList(listener));
return content;
}
@Override @Override
public void addListener(String dataId, String group, Listener listener) throws NacosException { public void addListener(String dataId, String group, Listener listener) throws NacosException {
worker.addTenantListeners(dataId, group, Arrays.asList(listener)); worker.addTenantListeners(dataId, group, Arrays.asList(listener));
@ -166,6 +174,7 @@ public class NacosConfigService implements ConfigService {
content = worker.getServerConfig(dataId, group, tenant, timeoutMs); content = worker.getServerConfig(dataId, group, tenant, timeoutMs);
cr.setContent(content); cr.setContent(content);
configFilterChainManager.doFilter(null, cr); configFilterChainManager.doFilter(null, cr);
content = cr.getContent(); content = cr.getContent();

View File

@ -91,9 +91,9 @@ public class ServerHttpAgent implements HttpAgent {
return result; return result;
} }
} catch (ConnectException ce) { } catch (ConnectException ce) {
LOGGER.error("[NACOS ConnectException httpDelete] currentServerAddr:{}, err : {}", serverListMgr.getCurrentServerAddr(), ce.getMessage()); LOGGER.error("[NACOS ConnectException httpGet] currentServerAddr:{}, err : {}", serverListMgr.getCurrentServerAddr(), ce.getMessage());
} catch (SocketTimeoutException stoe) { } catch (SocketTimeoutException stoe) {
LOGGER.error("[NACOS SocketTimeoutException httpDelete] currentServerAddr:{} err : {}", serverListMgr.getCurrentServerAddr(), stoe.getMessage()); LOGGER.error("[NACOS SocketTimeoutException httpGet] currentServerAddr:{} err : {}", serverListMgr.getCurrentServerAddr(), stoe.getMessage());
} catch (IOException ioe) { } catch (IOException ioe) {
LOGGER.error("[NACOS IOException httpGet] currentServerAddr: " + serverListMgr.getCurrentServerAddr(), ioe); LOGGER.error("[NACOS IOException httpGet] currentServerAddr: " + serverListMgr.getCurrentServerAddr(), ioe);
throw ioe; throw ioe;
@ -138,7 +138,7 @@ public class ServerHttpAgent implements HttpAgent {
if (result.code == HttpURLConnection.HTTP_INTERNAL_ERROR if (result.code == HttpURLConnection.HTTP_INTERNAL_ERROR
|| result.code == HttpURLConnection.HTTP_BAD_GATEWAY || result.code == HttpURLConnection.HTTP_BAD_GATEWAY
|| result.code == HttpURLConnection.HTTP_UNAVAILABLE) { || result.code == HttpURLConnection.HTTP_UNAVAILABLE) {
LOGGER.error("[NACOS ConnectException httpPost] currentServerAddr: {}, httpCode: {}", LOGGER.error("[NACOS ConnectException] currentServerAddr: {}, httpCode: {}",
currentServerAddr, result.code); currentServerAddr, result.code);
} else { } else {
// Update the currently available server addr // Update the currently available server addr
@ -425,6 +425,7 @@ public class ServerHttpAgent implements HttpAgent {
return code; return code;
} }
@Override
public String toString() { public String toString() {
return "STSCredential{" + return "STSCredential{" +
"accessKeyId='" + accessKeyId + '\'' + "accessKeyId='" + accessKeyId + '\'' +

View File

@ -66,6 +66,7 @@ public class CacheData {
/** /**
* Add listener * Add listener
* if CacheData already set new content, Listener should init lastCallMd5 by CacheData.md5
* *
* @param listener listener * @param listener listener
*/ */
@ -73,7 +74,7 @@ public class CacheData {
if (null == listener) { if (null == listener) {
throw new IllegalArgumentException("listener is null"); throw new IllegalArgumentException("listener is null");
} }
ManagerListenerWrap wrap = new ManagerListenerWrap(listener); ManagerListenerWrap wrap = new ManagerListenerWrap(listener, md5);
if (listeners.addIfAbsent(wrap)) { if (listeners.addIfAbsent(wrap)) {
LOGGER.info("[{}] [add-listener] ok, tenant={}, dataId={}, group={}, cnt={}", name, tenant, dataId, group, LOGGER.info("[{}] [add-listener] ok, tenant={}, dataId={}, group={}, cnt={}", name, tenant, dataId, group,
listeners.size()); listeners.size());
@ -167,6 +168,7 @@ public class CacheData {
final Listener listener = listenerWrap.listener; final Listener listener = listenerWrap.listener;
Runnable job = new Runnable() { Runnable job = new Runnable() {
@Override
public void run() { public void run() {
ClassLoader myClassLoader = Thread.currentThread().getContextClassLoader(); ClassLoader myClassLoader = Thread.currentThread().getContextClassLoader();
ClassLoader appClassLoader = listener.getClass().getClassLoader(); ClassLoader appClassLoader = listener.getClass().getClassLoader();
@ -290,6 +292,11 @@ class ManagerListenerWrap {
this.listener = listener; this.listener = listener;
} }
ManagerListenerWrap(Listener listener, String md5) {
this.listener = listener;
this.lastCallMd5 = md5;
}
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
if (null == obj || obj.getClass() != getClass()) { if (null == obj || obj.getClass() != getClass()) {

View File

@ -82,7 +82,7 @@ public class ClientWorker {
} }
} }
public void addTenantListeners(String dataId, String group, List<? extends Listener> listeners) { public void addTenantListeners(String dataId, String group, List<? extends Listener> listeners) throws NacosException {
group = null2defaultGroup(group); group = null2defaultGroup(group);
String tenant = agent.getTenant(); String tenant = agent.getTenant();
CacheData cache = addCacheDataIfAbsent(dataId, group, tenant); CacheData cache = addCacheDataIfAbsent(dataId, group, tenant);
@ -91,6 +91,16 @@ public class ClientWorker {
} }
} }
public void addTenantListenersWithContent(String dataId, String group, String content, List<? extends Listener> listeners) throws NacosException {
group = null2defaultGroup(group);
String tenant = agent.getTenant();
CacheData cache = addCacheDataIfAbsent(dataId, group, tenant);
cache.setContent(content);
for (Listener listener : listeners) {
cache.addListener(listener);
}
}
public void removeTenantListener(String dataId, String group, Listener listener) { public void removeTenantListener(String dataId, String group, Listener listener) {
group = null2defaultGroup(group); group = null2defaultGroup(group);
String tenant = agent.getTenant(); String tenant = agent.getTenant();
@ -161,13 +171,12 @@ public class ClientWorker {
return cache; return cache;
} }
public CacheData addCacheDataIfAbsent(String dataId, String group, String tenant) { public CacheData addCacheDataIfAbsent(String dataId, String group, String tenant) throws NacosException {
CacheData cache = getCache(dataId, group, tenant); CacheData cache = getCache(dataId, group, tenant);
if (null != cache) { if (null != cache) {
return cache; return cache;
} }
String key = GroupKey.getKeyTenant(dataId, group, tenant); String key = GroupKey.getKeyTenant(dataId, group, tenant);
cache = new CacheData(configFilterChainManager, agent.getName(), dataId, group, tenant);
synchronized (cacheMap) { synchronized (cacheMap) {
CacheData cacheFromMap = getCache(dataId, group, tenant); CacheData cacheFromMap = getCache(dataId, group, tenant);
// multiple listeners on the same dataid+group and race condition,so // multiple listeners on the same dataid+group and race condition,so
@ -177,6 +186,13 @@ public class ClientWorker {
cache = cacheFromMap; cache = cacheFromMap;
// reset so that server not hang this check // reset so that server not hang this check
cache.setInitializing(true); cache.setInitializing(true);
} else {
cache = new CacheData(configFilterChainManager, agent.getName(), dataId, group, tenant);
// fix issue # 1317
if (enableRemoteSyncConfig) {
String content = getServerConfig(dataId, group, tenant, 3000L);
cache.setContent(content);
}
} }
Map<String, CacheData> copy = new HashMap<String, CacheData>(cacheMap.get()); Map<String, CacheData> copy = new HashMap<String, CacheData>(cacheMap.get());
@ -461,6 +477,8 @@ public class ClientWorker {
Constants.CONFIG_LONG_POLL_TIMEOUT), Constants.MIN_CONFIG_LONG_POLL_TIMEOUT); Constants.CONFIG_LONG_POLL_TIMEOUT), Constants.MIN_CONFIG_LONG_POLL_TIMEOUT);
taskPenaltyTime = NumberUtils.toInt(properties.getProperty(PropertyKeyConst.CONFIG_RETRY_TIME), Constants.CONFIG_RETRY_TIME); taskPenaltyTime = NumberUtils.toInt(properties.getProperty(PropertyKeyConst.CONFIG_RETRY_TIME), Constants.CONFIG_RETRY_TIME);
enableRemoteSyncConfig = Boolean.parseBoolean(properties.getProperty(PropertyKeyConst.ENABLE_REMOTE_SYNC_CONFIG));
} }
class LongPollingRunnable implements Runnable { class LongPollingRunnable implements Runnable {
@ -559,4 +577,5 @@ public class ClientWorker {
private long timeout; private long timeout;
private double currentLongingTaskCount = 0; private double currentLongingTaskCount = 0;
private int taskPenaltyTime; private int taskPenaltyTime;
private boolean enableRemoteSyncConfig = false;
} }

View File

@ -36,6 +36,7 @@ public class TimerService {
@SuppressWarnings("PMD.ThreadPoolCreationRule") @SuppressWarnings("PMD.ThreadPoolCreationRule")
static ScheduledExecutorService scheduledExecutor = Executors static ScheduledExecutorService scheduledExecutor = Executors
.newSingleThreadScheduledExecutor(new ThreadFactory() { .newSingleThreadScheduledExecutor(new ThreadFactory() {
@Override
public Thread newThread(Runnable r) { public Thread newThread(Runnable r) {
Thread t = new Thread(r); Thread t = new Thread(r);
t.setName("com.alibaba.nacos.client.Timer"); t.setName("com.alibaba.nacos.client.Timer");

View File

@ -85,6 +85,7 @@ public final class CredentialService implements SpasCredentialLoader {
LOGGER.info("[{}] {} is freed", appName, this.getClass().getSimpleName()); LOGGER.info("[{}] {} is freed", appName, this.getClass().getSimpleName());
} }
@Override
public Credentials getCredential() { public Credentials getCredential() {
Credentials localCredential = credentials; Credentials localCredential = credentials;
if (localCredential.valid()) { if (localCredential.valid()) {

View File

@ -38,6 +38,7 @@ public class Credentials implements SpasCredential {
this(null, null, null); this(null, null, null);
} }
@Override
public String getAccessKey() { public String getAccessKey() {
return accessKey; return accessKey;
} }
@ -46,6 +47,7 @@ public class Credentials implements SpasCredential {
this.accessKey = accessKey; this.accessKey = accessKey;
} }
@Override
public String getSecretKey() { public String getSecretKey() {
return secretKey; return secretKey;
} }

View File

@ -118,7 +118,7 @@ public class FailoverReactor {
String failover = ConcurrentDiskUtil.getFileContent(failoverDir + UtilAndComs.FAILOVER_SWITCH, String failover = ConcurrentDiskUtil.getFileContent(failoverDir + UtilAndComs.FAILOVER_SWITCH,
Charset.defaultCharset().toString()); Charset.defaultCharset().toString());
if (!StringUtils.isEmpty(failover)) { if (!StringUtils.isEmpty(failover)) {
List<String> lines = Arrays.asList(failover.split(DiskCache.getLineSeperator())); List<String> lines = Arrays.asList(failover.split(DiskCache.getLineSeparator()));
for (String line : lines) { for (String line : lines) {
String line1 = line.trim(); String line1 = line.trim();
@ -212,6 +212,7 @@ public class FailoverReactor {
} }
class DiskFileWriter extends TimerTask { class DiskFileWriter extends TimerTask {
@Override
public void run() { public void run() {
Map<String, ServiceInfo> map = hostReactor.getServiceInfoMap(); Map<String, ServiceInfo> map = hostReactor.getServiceInfoMap();
for (Map.Entry<String, ServiceInfo> entry : map.entrySet()) { for (Map.Entry<String, ServiceInfo> entry : map.entrySet()) {

View File

@ -71,9 +71,8 @@ public class DiskCache {
} }
} }
public static String getLineSeperator() { public static String getLineSeparator() {
String lineSeparator = System.getProperty("line.separator"); return System.getProperty("line.separator");
return lineSeparator;
} }
public static Map<String, ServiceInfo> read(String cacheDir) { public static Map<String, ServiceInfo> read(String cacheDir) {
@ -82,7 +81,7 @@ public class DiskCache {
BufferedReader reader = null; BufferedReader reader = null;
try { try {
File[] files = makeSureCacheDirExists(cacheDir).listFiles(); File[] files = makeSureCacheDirExists(cacheDir).listFiles();
if (files == null) { if (files == null || files.length == 0) {
return domMap; return domMap;
} }

View File

@ -40,7 +40,7 @@ public class Balancer {
public static class RandomByWeight { public static class RandomByWeight {
public static List<Instance> selectAll(ServiceInfo serviceInfo) { public static List<Instance> selectAll(ServiceInfo serviceInfo) {
List<Instance> hosts = nothing(serviceInfo); List<Instance> hosts = serviceInfo.getHosts();
if (CollectionUtils.isEmpty(hosts)) { if (CollectionUtils.isEmpty(hosts)) {
throw new IllegalStateException("no host to srv for serviceInfo: " + serviceInfo.getName()); throw new IllegalStateException("no host to srv for serviceInfo: " + serviceInfo.getName());
@ -59,10 +59,6 @@ public class Balancer {
return getHostByRandomWeight(hosts); return getHostByRandomWeight(hosts);
} }
public static List<Instance> nothing(ServiceInfo serviceInfo) {
return serviceInfo.getHosts();
}
} }
/** /**
@ -91,7 +87,6 @@ public class Balancer {
NAMING_LOGGER.debug("for (Host host : hosts)"); NAMING_LOGGER.debug("for (Host host : hosts)");
vipChooser.refresh(hostsWithWeight); vipChooser.refresh(hostsWithWeight);
NAMING_LOGGER.debug("vipChooser.refresh"); NAMING_LOGGER.debug("vipChooser.refresh");
Instance host = vipChooser.randomWithWeight(); return vipChooser.randomWithWeight();
return host;
} }
} }

View File

@ -140,9 +140,7 @@ public class HostReactor {
if (!oldHostMap.containsKey(key)) { if (!oldHostMap.containsKey(key)) {
newHosts.add(host); newHosts.add(host);
continue;
} }
} }
for (Map.Entry<String, Instance> entry : oldHostMap.entrySet()) { for (Map.Entry<String, Instance> entry : oldHostMap.entrySet()) {
@ -154,7 +152,6 @@ public class HostReactor {
if (!newHostMap.containsKey(key)) { if (!newHostMap.containsKey(key)) {
remvHosts.add(host); remvHosts.add(host);
continue;
} }
} }

View File

@ -35,7 +35,7 @@ public class PushReceiver implements Runnable {
private ScheduledExecutorService executorService; private ScheduledExecutorService executorService;
public static final int UDP_MSS = 64 * 1024; private static final int UDP_MSS = 64 * 1024;
private DatagramSocket udpSocket; private DatagramSocket udpSocket;

View File

@ -31,10 +31,12 @@ public class GenericPoller<T> implements Poller<T> {
this.items = items; this.items = items;
} }
@Override
public T next() { public T next() {
return items.get(Math.abs(index.getAndIncrement() % items.size())); return items.get(Math.abs(index.getAndIncrement() % items.size()));
} }
@Override
public Poller<T> refresh(List<T> items) { public Poller<T> refresh(List<T> items) {
return new GenericPoller<T>(items); return new GenericPoller<T>(items);
} }

View File

@ -63,6 +63,7 @@ public final class JvmRandom extends Random {
* @param seed ignored * @param seed ignored
* @throws UnsupportedOperationException * @throws UnsupportedOperationException
*/ */
@Override
public synchronized void setSeed(long seed) { public synchronized void setSeed(long seed) {
if (this.constructed) { if (this.constructed) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
@ -75,6 +76,7 @@ public final class JvmRandom extends Random {
* @return Nothing, this method always throws an UnsupportedOperationException. * @return Nothing, this method always throws an UnsupportedOperationException.
* @throws UnsupportedOperationException * @throws UnsupportedOperationException
*/ */
@Override
public synchronized double nextGaussian() { public synchronized double nextGaussian() {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
@ -85,6 +87,7 @@ public final class JvmRandom extends Random {
* @param byteArray ignored * @param byteArray ignored
* @throws UnsupportedOperationException * @throws UnsupportedOperationException
*/ */
@Override
public void nextBytes(byte[] byteArray) { public void nextBytes(byte[] byteArray) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
} }
@ -95,6 +98,7 @@ public final class JvmRandom extends Random {
* *
* @return the random int * @return the random int
*/ */
@Override
public int nextInt() { public int nextInt() {
return nextInt(Integer.MAX_VALUE); return nextInt(Integer.MAX_VALUE);
} }
@ -107,6 +111,7 @@ public final class JvmRandom extends Random {
* @return the random int * @return the random int
* @throws IllegalArgumentException when <code>n &lt;= 0</code> * @throws IllegalArgumentException when <code>n &lt;= 0</code>
*/ */
@Override
public int nextInt(int n) { public int nextInt(int n) {
return SHARED_RANDOM.nextInt(n); return SHARED_RANDOM.nextInt(n);
} }
@ -117,6 +122,7 @@ public final class JvmRandom extends Random {
* *
* @return the random long * @return the random long
*/ */
@Override
public long nextLong() { public long nextLong() {
return nextLong(Long.MAX_VALUE); return nextLong(Long.MAX_VALUE);
} }
@ -158,6 +164,7 @@ public final class JvmRandom extends Random {
* *
* @return the random boolean * @return the random boolean
*/ */
@Override
public boolean nextBoolean() { public boolean nextBoolean() {
return SHARED_RANDOM.nextBoolean(); return SHARED_RANDOM.nextBoolean();
} }
@ -168,6 +175,7 @@ public final class JvmRandom extends Random {
* *
* @return the random float * @return the random float
*/ */
@Override
public float nextFloat() { public float nextFloat() {
return SHARED_RANDOM.nextFloat(); return SHARED_RANDOM.nextFloat();
} }
@ -177,6 +185,7 @@ public final class JvmRandom extends Random {
* *
* @return the random double * @return the random double
*/ */
@Override
public double nextDouble() { public double nextDouble() {
return SHARED_RANDOM.nextDouble(); return SHARED_RANDOM.nextDouble();
} }

View File

@ -146,6 +146,7 @@ public class ThreadLocalRandom extends Random {
* The actual ThreadLocal * The actual ThreadLocal
*/ */
private static final ThreadLocal<ThreadLocalRandom> localRandom = new ThreadLocal<ThreadLocalRandom>() { private static final ThreadLocal<ThreadLocalRandom> localRandom = new ThreadLocal<ThreadLocalRandom>() {
@Override
protected ThreadLocalRandom initialValue() { protected ThreadLocalRandom initialValue() {
return new ThreadLocalRandom(); return new ThreadLocalRandom();
} }
@ -165,6 +166,7 @@ public class ThreadLocalRandom extends Random {
* *
* @throws UnsupportedOperationException always * @throws UnsupportedOperationException always
*/ */
@Override
public void setSeed(long seed) { public void setSeed(long seed) {
if (initialized) { if (initialized) {
throw new UnsupportedOperationException(); throw new UnsupportedOperationException();
@ -172,6 +174,7 @@ public class ThreadLocalRandom extends Random {
rnd = (seed ^ multiplier) & mask; rnd = (seed ^ multiplier) & mask;
} }
@Override
protected int next(int bits) { protected int next(int bits) {
rnd = (rnd * multiplier + addend) & mask; rnd = (rnd * multiplier + addend) & mask;
return (int)(rnd >>> (48 - bits)); return (int)(rnd >>> (48 - bits));

View File

@ -54,8 +54,6 @@ public class CmdbProvider implements CmdbReader, CmdbWriter {
private Set<String> entityTypeSet = new HashSet<>(); private Set<String> entityTypeSet = new HashSet<>();
private List<EntityEvent> eventList = new ArrayList<>();
private long eventTimestamp = System.currentTimeMillis(); private long eventTimestamp = System.currentTimeMillis();
public CmdbProvider() throws NacosException { public CmdbProvider() throws NacosException {

View File

@ -31,25 +31,29 @@ import java.util.zip.GZIPInputStream;
public class IoUtils { public class IoUtils {
public static byte[] tryDecompress(InputStream raw) throws Exception { public static byte[] tryDecompress(InputStream raw) throws Exception {
GZIPInputStream gis = null;
ByteArrayOutputStream out = null;
try { try {
GZIPInputStream gis gis = new GZIPInputStream(raw);
= new GZIPInputStream(raw); out = new ByteArrayOutputStream();
ByteArrayOutputStream out
= new ByteArrayOutputStream();
IOUtils.copy(gis, out); IOUtils.copy(gis, out);
return out.toByteArray(); return out.toByteArray();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} finally {
if (out != null) {
out.close();
}
if (gis != null) {
gis.close();
}
} }
return null; return null;
} }
static private BufferedReader toBufferedReader(Reader reader) { static private BufferedReader toBufferedReader(Reader reader) {
return reader instanceof BufferedReader ? (BufferedReader)reader : new BufferedReader( return reader instanceof BufferedReader ? (BufferedReader) reader : new BufferedReader(
reader); reader);
} }

View File

@ -55,6 +55,7 @@ public final class TaskManager implements TaskManagerMBean {
class ProcessRunnable implements Runnable { class ProcessRunnable implements Runnable {
@Override
public void run() { public void run() {
while (!TaskManager.this.closed.get()) { while (!TaskManager.this.closed.get()) {
try { try {
@ -248,6 +249,7 @@ public final class TaskManager implements TaskManagerMBean {
} }
} }
@Override
public String getTaskInfos() { public String getTaskInfos() {
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
for (String taskType : this.taskProcessors.keySet()) { for (String taskType : this.taskProcessors.keySet()) {

View File

@ -94,6 +94,7 @@ public class ConfigInfoBase implements Serializable, Comparable<ConfigInfoBase>
writer.write(this.content); writer.write(this.content);
} }
@Override
public int compareTo(ConfigInfoBase o) { public int compareTo(ConfigInfoBase o) {
if (o == null) { if (o == null) {
return 1; return 1;

View File

@ -54,6 +54,7 @@ public class GroupKey extends GroupKey2 {
this.group = group; this.group = group;
} }
@Override
public String toString() { public String toString() {
return dataId + "+" + group; return dataId + "+" + group;
} }

View File

@ -82,8 +82,6 @@ class PrintMemoryTask implements Runnable {
class NotifyTaskQueueMonitorTask implements Runnable { class NotifyTaskQueueMonitorTask implements Runnable {
final private AsyncNotifyService notifySingleService; final private AsyncNotifyService notifySingleService;
private AtomicInteger notifyTask = new AtomicInteger();
NotifyTaskQueueMonitorTask(AsyncNotifyService notifySingleService) { NotifyTaskQueueMonitorTask(AsyncNotifyService notifySingleService) {
this.notifySingleService = notifySingleService; this.notifySingleService = notifySingleService;

View File

@ -16,7 +16,6 @@
package com.alibaba.nacos.config.server.service; package com.alibaba.nacos.config.server.service;
import com.alibaba.nacos.config.server.utils.PropertyUtil; import com.alibaba.nacos.config.server.utils.PropertyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware; import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@ -31,11 +30,9 @@ import static com.alibaba.nacos.core.utils.SystemUtils.STANDALONE_MODE;
@Component @Component
public class DynamicDataSource implements ApplicationContextAware { public class DynamicDataSource implements ApplicationContextAware {
@Autowired
private PropertyUtil propertyUtil;
private ApplicationContext applicationContext; private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) { public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext; this.applicationContext = applicationContext;
} }
@ -47,7 +44,7 @@ public class DynamicDataSource implements ApplicationContextAware {
public DataSourceService getDataSource() { public DataSourceService getDataSource() {
DataSourceService dataSourceService = null; DataSourceService dataSourceService = null;
if (STANDALONE_MODE && !propertyUtil.isStandaloneUseMysql()) { if (STANDALONE_MODE && !PropertyUtil.isStandaloneUseMysql()) {
dataSourceService = (DataSourceService)applicationContext.getBean("localDataSourceService"); dataSourceService = (DataSourceService)applicationContext.getBean("localDataSourceService");
} else { } else {
dataSourceService = (DataSourceService)applicationContext.getBean("basicDataSourceService"); dataSourceService = (DataSourceService)applicationContext.getBean("basicDataSourceService");

View File

@ -22,7 +22,6 @@ import com.alibaba.nacos.config.server.utils.StringUtils;
import org.apache.commons.dbcp.BasicDataSource; import org.apache.commons.dbcp.BasicDataSource;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@ -62,9 +61,6 @@ public class LocalDataSourceServiceImpl implements DataSourceService {
private JdbcTemplate jt; private JdbcTemplate jt;
private TransactionTemplate tjt; private TransactionTemplate tjt;
@Autowired
private PropertyUtil propertyUtil;
@PostConstruct @PostConstruct
public void init() { public void init() {
BasicDataSource ds = new BasicDataSource(); BasicDataSource ds = new BasicDataSource();
@ -90,7 +86,7 @@ public class LocalDataSourceServiceImpl implements DataSourceService {
tm.setDataSource(ds); tm.setDataSource(ds);
tjt.setTimeout(5000); tjt.setTimeout(5000);
if (STANDALONE_MODE && !propertyUtil.isStandaloneUseMysql()) { if (STANDALONE_MODE && !PropertyUtil.isStandaloneUseMysql()) {
reload(); reload();
} }
} }

View File

@ -371,6 +371,7 @@ public class LongPollingService extends AbstractEventListener {
@Override @Override
public void run() { public void run() {
asyncTimeoutFuture = scheduler.schedule(new Runnable() { asyncTimeoutFuture = scheduler.schedule(new Runnable() {
@Override
public void run() { public void run() {
try { try {
getRetainIps().put(ClientLongPolling.this.ip, System.currentTimeMillis()); getRetainIps().put(ClientLongPolling.this.ip, System.currentTimeMillis());

View File

@ -94,6 +94,7 @@ public class PersistService {
static final class ConfigInfoWrapperRowMapper implements static final class ConfigInfoWrapperRowMapper implements
RowMapper<ConfigInfoWrapper> { RowMapper<ConfigInfoWrapper> {
@Override
public ConfigInfoWrapper mapRow(ResultSet rs, int rowNum) public ConfigInfoWrapper mapRow(ResultSet rs, int rowNum)
throws SQLException { throws SQLException {
ConfigInfoWrapper info = new ConfigInfoWrapper(); ConfigInfoWrapper info = new ConfigInfoWrapper();
@ -128,6 +129,7 @@ public class PersistService {
static final class ConfigInfoBetaWrapperRowMapper implements static final class ConfigInfoBetaWrapperRowMapper implements
RowMapper<ConfigInfoBetaWrapper> { RowMapper<ConfigInfoBetaWrapper> {
@Override
public ConfigInfoBetaWrapper mapRow(ResultSet rs, int rowNum) public ConfigInfoBetaWrapper mapRow(ResultSet rs, int rowNum)
throws SQLException { throws SQLException {
ConfigInfoBetaWrapper info = new ConfigInfoBetaWrapper(); ConfigInfoBetaWrapper info = new ConfigInfoBetaWrapper();
@ -163,6 +165,7 @@ public class PersistService {
static final class ConfigInfoTagWrapperRowMapper implements static final class ConfigInfoTagWrapperRowMapper implements
RowMapper<ConfigInfoTagWrapper> { RowMapper<ConfigInfoTagWrapper> {
@Override
public ConfigInfoTagWrapper mapRow(ResultSet rs, int rowNum) public ConfigInfoTagWrapper mapRow(ResultSet rs, int rowNum)
throws SQLException { throws SQLException {
ConfigInfoTagWrapper info = new ConfigInfoTagWrapper(); ConfigInfoTagWrapper info = new ConfigInfoTagWrapper();
@ -198,6 +201,7 @@ public class PersistService {
static final class ConfigInfoRowMapper implements static final class ConfigInfoRowMapper implements
RowMapper<ConfigInfo> { RowMapper<ConfigInfo> {
@Override
public ConfigInfo mapRow(ResultSet rs, int rowNum) throws SQLException { public ConfigInfo mapRow(ResultSet rs, int rowNum) throws SQLException {
ConfigInfo info = new ConfigInfo(); ConfigInfo info = new ConfigInfo();
@ -227,6 +231,7 @@ public class PersistService {
static final class ConfigKeyRowMapper implements static final class ConfigKeyRowMapper implements
RowMapper<ConfigKey> { RowMapper<ConfigKey> {
@Override
public ConfigKey mapRow(ResultSet rs, int rowNum) throws SQLException { public ConfigKey mapRow(ResultSet rs, int rowNum) throws SQLException {
ConfigKey info = new ConfigKey(); ConfigKey info = new ConfigKey();
@ -239,6 +244,7 @@ public class PersistService {
} }
static final class ConfigAdvanceInfoRowMapper implements RowMapper<ConfigAdvanceInfo> { static final class ConfigAdvanceInfoRowMapper implements RowMapper<ConfigAdvanceInfo> {
@Override
public ConfigAdvanceInfo mapRow(ResultSet rs, int rowNum) throws SQLException { public ConfigAdvanceInfo mapRow(ResultSet rs, int rowNum) throws SQLException {
ConfigAdvanceInfo info = new ConfigAdvanceInfo(); ConfigAdvanceInfo info = new ConfigAdvanceInfo();
info.setCreateTime(rs.getTimestamp("gmt_modified").getTime()); info.setCreateTime(rs.getTimestamp("gmt_modified").getTime());
@ -255,6 +261,7 @@ public class PersistService {
} }
static final class ConfigAllInfoRowMapper implements RowMapper<ConfigAllInfo> { static final class ConfigAllInfoRowMapper implements RowMapper<ConfigAllInfo> {
@Override
public ConfigAllInfo mapRow(ResultSet rs, int rowNum) throws SQLException { public ConfigAllInfo mapRow(ResultSet rs, int rowNum) throws SQLException {
ConfigAllInfo info = new ConfigAllInfo(); ConfigAllInfo info = new ConfigAllInfo();
info.setDataId(rs.getString("data_id")); info.setDataId(rs.getString("data_id"));
@ -291,6 +298,7 @@ public class PersistService {
static final class ConfigInfo4BetaRowMapper implements static final class ConfigInfo4BetaRowMapper implements
RowMapper<ConfigInfo4Beta> { RowMapper<ConfigInfo4Beta> {
@Override
public ConfigInfo4Beta mapRow(ResultSet rs, int rowNum) throws SQLException { public ConfigInfo4Beta mapRow(ResultSet rs, int rowNum) throws SQLException {
ConfigInfo4Beta info = new ConfigInfo4Beta(); ConfigInfo4Beta info = new ConfigInfo4Beta();
@ -320,6 +328,7 @@ public class PersistService {
static final class ConfigInfo4TagRowMapper implements static final class ConfigInfo4TagRowMapper implements
RowMapper<ConfigInfo4Tag> { RowMapper<ConfigInfo4Tag> {
@Override
public ConfigInfo4Tag mapRow(ResultSet rs, int rowNum) throws SQLException { public ConfigInfo4Tag mapRow(ResultSet rs, int rowNum) throws SQLException {
ConfigInfo4Tag info = new ConfigInfo4Tag(); ConfigInfo4Tag info = new ConfigInfo4Tag();
@ -349,6 +358,7 @@ public class PersistService {
static final class ConfigInfoBaseRowMapper implements static final class ConfigInfoBaseRowMapper implements
RowMapper<ConfigInfoBase> { RowMapper<ConfigInfoBase> {
@Override
public ConfigInfoBase mapRow(ResultSet rs, int rowNum) throws SQLException { public ConfigInfoBase mapRow(ResultSet rs, int rowNum) throws SQLException {
ConfigInfoBase info = new ConfigInfoBase(); ConfigInfoBase info = new ConfigInfoBase();
@ -371,6 +381,7 @@ public class PersistService {
static final class ConfigInfoAggrRowMapper implements static final class ConfigInfoAggrRowMapper implements
RowMapper<ConfigInfoAggr> { RowMapper<ConfigInfoAggr> {
@Override
public ConfigInfoAggr mapRow(ResultSet rs, int rowNum) public ConfigInfoAggr mapRow(ResultSet rs, int rowNum)
throws SQLException { throws SQLException {
ConfigInfoAggr info = new ConfigInfoAggr(); ConfigInfoAggr info = new ConfigInfoAggr();
@ -385,6 +396,7 @@ public class PersistService {
} }
static final class ConfigInfoChangedRowMapper implements RowMapper<ConfigInfoChanged> { static final class ConfigInfoChangedRowMapper implements RowMapper<ConfigInfoChanged> {
@Override
public ConfigInfoChanged mapRow(ResultSet rs, int rowNum) throws SQLException { public ConfigInfoChanged mapRow(ResultSet rs, int rowNum) throws SQLException {
ConfigInfoChanged info = new ConfigInfoChanged(); ConfigInfoChanged info = new ConfigInfoChanged();
info.setDataId(rs.getString("data_id")); info.setDataId(rs.getString("data_id"));
@ -395,6 +407,7 @@ public class PersistService {
} }
static final class ConfigHistoryRowMapper implements RowMapper<ConfigHistoryInfo> { static final class ConfigHistoryRowMapper implements RowMapper<ConfigHistoryInfo> {
@Override
public ConfigHistoryInfo mapRow(ResultSet rs, int rowNum) throws SQLException { public ConfigHistoryInfo mapRow(ResultSet rs, int rowNum) throws SQLException {
ConfigHistoryInfo configHistoryInfo = new ConfigHistoryInfo(); ConfigHistoryInfo configHistoryInfo = new ConfigHistoryInfo();
configHistoryInfo.setId(rs.getLong("nid")); configHistoryInfo.setId(rs.getLong("nid"));
@ -411,6 +424,7 @@ public class PersistService {
} }
static final class ConfigHistoryDetailRowMapper implements RowMapper<ConfigHistoryInfo> { static final class ConfigHistoryDetailRowMapper implements RowMapper<ConfigHistoryInfo> {
@Override
public ConfigHistoryInfo mapRow(ResultSet rs, int rowNum) throws SQLException { public ConfigHistoryInfo mapRow(ResultSet rs, int rowNum) throws SQLException {
ConfigHistoryInfo configHistoryInfo = new ConfigHistoryInfo(); ConfigHistoryInfo configHistoryInfo = new ConfigHistoryInfo();
configHistoryInfo.setId(rs.getLong("nid")); configHistoryInfo.setId(rs.getLong("nid"));
@ -432,6 +446,7 @@ public class PersistService {
; ;
static final class TenantInfoRowMapper implements RowMapper<TenantInfo> { static final class TenantInfoRowMapper implements RowMapper<TenantInfo> {
@Override
public TenantInfo mapRow(ResultSet rs, int rowNum) throws SQLException { public TenantInfo mapRow(ResultSet rs, int rowNum) throws SQLException {
TenantInfo info = new TenantInfo(); TenantInfo info = new TenantInfo();
info.setTenantId(rs.getString("tenant_id")); info.setTenantId(rs.getString("tenant_id"));
@ -442,6 +457,7 @@ public class PersistService {
} }
static final class UserRowMapper implements RowMapper<User> { static final class UserRowMapper implements RowMapper<User> {
@Override
public User mapRow(ResultSet rs, int rowNum) throws SQLException { public User mapRow(ResultSet rs, int rowNum) throws SQLException {
User user = new User(); User user = new User();
user.setUsername(rs.getString("username")); user.setUsername(rs.getString("username"));
@ -799,6 +815,7 @@ public class PersistService {
try { try {
this.jt.update(sql, new PreparedStatementSetter() { this.jt.update(sql, new PreparedStatementSetter() {
@Override
public void setValues(PreparedStatement ps) throws SQLException { public void setValues(PreparedStatement ps) throws SQLException {
int index = 1; int index = 1;
ps.setString(index++, dataId); ps.setString(index++, dataId);
@ -822,6 +839,7 @@ public class PersistService {
try { try {
this.jt.update(sql, new PreparedStatementSetter() { this.jt.update(sql, new PreparedStatementSetter() {
@Override
public void setValues(PreparedStatement ps) throws SQLException { public void setValues(PreparedStatement ps) throws SQLException {
int index = 1; int index = 1;
ps.setString(index++, dataId); ps.setString(index++, dataId);
@ -2637,6 +2655,7 @@ public class PersistService {
try { try {
jt.update(new PreparedStatementCreator() { jt.update(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
PreparedStatement ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS); PreparedStatement ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
ps.setString(1, configInfo.getDataId()); ps.setString(1, configInfo.getDataId());

View File

@ -319,10 +319,12 @@ public class AsyncNotifyService extends AbstractEventListener {
// this.executor = executor; // this.executor = executor;
} }
@Override
public void setFailCount(int count) { public void setFailCount(int count) {
this.failCount = count; this.failCount = count;
} }
@Override
public int getFailCount() { public int getFailCount() {
return failCount; return failCount;
} }

View File

@ -35,6 +35,7 @@ public class SimpleFlowData {
@SuppressWarnings("PMD.ThreadPoolCreationRule") @SuppressWarnings("PMD.ThreadPoolCreationRule")
private ScheduledExecutorService timer = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() { private ScheduledExecutorService timer = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
@Override
public Thread newThread(Runnable r) { public Thread newThread(Runnable r) {
Thread t = new Thread(r); Thread t = new Thread(r);
t.setName("nacos flow control thread"); t.setName("nacos flow control thread");
@ -52,6 +53,7 @@ public class SimpleFlowData {
} }
timer.scheduleAtFixedRate(new Runnable() { timer.scheduleAtFixedRate(new Runnable() {
@Override
public void run() { public void run() {
rotateSlot(); rotateSlot();
} }

View File

@ -38,6 +38,7 @@ public class SimpleIPFlowData {
@SuppressWarnings("PMD.ThreadPoolCreationRule") @SuppressWarnings("PMD.ThreadPoolCreationRule")
private ScheduledExecutorService timer = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() { private ScheduledExecutorService timer = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
@Override
public Thread newThread(Runnable r) { public Thread newThread(Runnable r) {
Thread t = new Thread(r); Thread t = new Thread(r);
t.setName("nacos ip flow control thread"); t.setName("nacos ip flow control thread");
@ -49,6 +50,7 @@ public class SimpleIPFlowData {
class DefaultIPFlowDataManagerTask implements Runnable { class DefaultIPFlowDataManagerTask implements Runnable {
@Override
public void run() { public void run() {
rotateSlot(); rotateSlot();
} }

View File

@ -34,8 +34,6 @@ public class DiskServiceUnitTest {
private DiskUtil diskService; private DiskUtil diskService;
private ServletContext servletContext;
private File tempFile; private File tempFile;
private String path; private String path;

View File

@ -114,8 +114,7 @@ public class InetUtils {
log.info("Testing interface: " + ifc.getDisplayName()); log.info("Testing interface: " + ifc.getDisplayName());
if (ifc.getIndex() < lowest || result == null) { if (ifc.getIndex() < lowest || result == null) {
lowest = ifc.getIndex(); lowest = ifc.getIndex();
} } else if (result != null) {
else if (result != null) {
continue; continue;
} }

View File

@ -42,7 +42,7 @@ public class SystemUtils {
/** /**
* Standalone mode or not * Standalone mode or not
*/ */
public static boolean STANDALONE_MODE = Boolean.getBoolean(STANDALONE_MODE_PROPERTY_NAME); public static final boolean STANDALONE_MODE = Boolean.getBoolean(STANDALONE_MODE_PROPERTY_NAME);
public static final String STANDALONE_MODE_ALONE = "standalone"; public static final String STANDALONE_MODE_ALONE = "standalone";
public static final String STANDALONE_MODE_CLUSTER = "cluster"; public static final String STANDALONE_MODE_CLUSTER = "cluster";
@ -50,7 +50,7 @@ public class SystemUtils {
/** /**
* server * server
*/ */
public static String FUNCTION_MODE = System.getProperty(FUNCTION_MODE_PROPERTY_NAME); public static final String FUNCTION_MODE = System.getProperty(FUNCTION_MODE_PROPERTY_NAME);
public static final String FUNCTION_MODE_CONFIG = "config"; public static final String FUNCTION_MODE_CONFIG = "config";
public static final String FUNCTION_MODE_NAMING = "naming"; public static final String FUNCTION_MODE_NAMING = "naming";

View File

@ -56,7 +56,7 @@ public class ServerListManager {
private Set<String> liveSites = new HashSet<>(); private Set<String> liveSites = new HashSet<>();
public final String LOCALHOST_SITE = UtilsAndCommons.UNKNOWN_SITE; private final static String LOCALHOST_SITE = UtilsAndCommons.UNKNOWN_SITE;
private long lastHealthServerMillis = 0L; private long lastHealthServerMillis = 0L;

View File

@ -27,6 +27,8 @@ import java.io.UnsupportedEncodingException;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import static org.apache.commons.lang3.CharEncoding.UTF_8;
/** /**
* Use FastJSON to serialize data * Use FastJSON to serialize data
* *
@ -44,7 +46,7 @@ public class FastJsonSerializer implements Serializer {
@Override @Override
public <T> T deserialize(byte[] data, Class<T> clazz) { public <T> T deserialize(byte[] data, Class<T> clazz) {
try { try {
return JSON.parseObject(new String(data, "UTF-8"), clazz); return JSON.parseObject(new String(data, UTF_8), clazz);
} catch (UnsupportedEncodingException e) { } catch (UnsupportedEncodingException e) {
return null; return null;
} }
@ -53,7 +55,7 @@ public class FastJsonSerializer implements Serializer {
@Override @Override
public <T> T deserialize(byte[] data, TypeReference<T> clazz) { public <T> T deserialize(byte[] data, TypeReference<T> clazz) {
try { try {
String dataString = new String(data, "UTF-8"); String dataString = new String(data, UTF_8);
return JSON.parseObject(dataString, clazz); return JSON.parseObject(dataString, clazz);
} catch (Exception e) { } catch (Exception e) {
Loggers.SRV_LOG.error("deserialize data failed.", e); Loggers.SRV_LOG.error("deserialize data failed.", e);
@ -64,7 +66,7 @@ public class FastJsonSerializer implements Serializer {
@Override @Override
public <T extends Record> Map<String, Datum<T>> deserializeMap(byte[] data, Class<T> clazz) { public <T extends Record> Map<String, Datum<T>> deserializeMap(byte[] data, Class<T> clazz) {
try { try {
String dataString = new String(data, "UTF-8"); String dataString = new String(data, UTF_8);
Map<String, JSONObject> dataMap = JSON.parseObject(dataString, new TypeReference<Map<String, JSONObject>>() { Map<String, JSONObject> dataMap = JSON.parseObject(dataString, new TypeReference<Map<String, JSONObject>>() {
}); });

View File

@ -28,6 +28,7 @@ import com.alibaba.nacos.naming.core.*;
import com.alibaba.nacos.naming.exception.NacosException; import com.alibaba.nacos.naming.exception.NacosException;
import com.alibaba.nacos.naming.misc.Loggers; import com.alibaba.nacos.naming.misc.Loggers;
import com.alibaba.nacos.naming.misc.UtilsAndCommons; import com.alibaba.nacos.naming.misc.UtilsAndCommons;
import com.alibaba.nacos.naming.pojo.Subscriber;
import com.alibaba.nacos.naming.selector.LabelSelector; import com.alibaba.nacos.naming.selector.LabelSelector;
import com.alibaba.nacos.naming.selector.NoneSelector; import com.alibaba.nacos.naming.selector.NoneSelector;
import com.alibaba.nacos.naming.selector.Selector; import com.alibaba.nacos.naming.selector.Selector;
@ -40,7 +41,6 @@ import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URLDecoder; import java.net.URLDecoder;
import java.util.*; import java.util.*;
@ -62,6 +62,9 @@ public class ServiceController {
@Autowired @Autowired
private ServerListManager serverListManager; private ServerListManager serverListManager;
@Autowired
private SubscribeManager subscribeManager;
@RequestMapping(value = "", method = RequestMethod.POST) @RequestMapping(value = "", method = RequestMethod.POST)
public String create(HttpServletRequest request) throws Exception { public String create(HttpServletRequest request) throws Exception {
@ -365,6 +368,31 @@ public class ServiceController {
return result; return result;
} }
/**
* get subscriber list
*
* @param request
* @return
*/
@RequestMapping(value = "/subscribers", method = RequestMethod.GET)
public JSONObject subscribers(HttpServletRequest request) {
String namespaceId = WebUtils.optional(request, CommonParams.NAMESPACE_ID,
Constants.DEFAULT_NAMESPACE_ID);
String serviceName = WebUtils.required(request, CommonParams.SERVICE_NAME);
boolean aggregation = Boolean.valueOf(WebUtils.optional(request, "aggregation", String.valueOf(Boolean.TRUE)));
JSONObject result = new JSONObject();
try {
List<Subscriber> subscribers = subscribeManager.getSubscribers(serviceName, namespaceId, aggregation);
result.put("subscribers", subscribers);
return result;
} catch (InterruptedException e) {
}
return result;
}
private List<String> filterInstanceMetadata(String namespaceId, List<String> serviceNames, String key, String value) { private List<String> filterInstanceMetadata(String namespaceId, List<String> serviceNames, String key, String value) {
List<String> filteredServiceNames = new ArrayList<>(); List<String> filteredServiceNames = new ArrayList<>();

View File

@ -34,7 +34,7 @@ import java.util.regex.Pattern;
public class Instance extends com.alibaba.nacos.api.naming.pojo.Instance implements Comparable { public class Instance extends com.alibaba.nacos.api.naming.pojo.Instance implements Comparable {
private static final double MAX_WEIGHT_VALUE = 10000.0D; private static final double MAX_WEIGHT_VALUE = 10000.0D;
private static final double MIN_POSTIVE_WEIGHT_VALUE = 0.01D; private static final double MIN_POSITIVE_WEIGHT_VALUE = 0.01D;
private static final double MIN_WEIGHT_VALUE = 0.00D; private static final double MIN_WEIGHT_VALUE = 0.00D;
private volatile long lastBeat = System.currentTimeMillis(); private volatile long lastBeat = System.currentTimeMillis();
@ -48,13 +48,13 @@ public class Instance extends com.alibaba.nacos.api.naming.pojo.Instance impleme
private String app; private String app;
public static final Pattern IP_PATTERN private static final Pattern IP_PATTERN
= Pattern.compile("(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}):?(\\d{1,5})?"); = Pattern.compile("(\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}):?(\\d{1,5})?");
public static final Pattern ONLY_DIGIT_AND_DOT private static final Pattern ONLY_DIGIT_AND_DOT
= Pattern.compile("(\\d|\\.)+"); = Pattern.compile("(\\d|\\.)+");
public static final String SPLITER = "_"; private static final String SPLITER = "_";
public Instance() { public Instance() {
} }
@ -191,8 +191,8 @@ public class Instance extends com.alibaba.nacos.api.naming.pojo.Instance impleme
ip.setWeight(MAX_WEIGHT_VALUE); ip.setWeight(MAX_WEIGHT_VALUE);
} }
if (ip.getWeight() < MIN_POSTIVE_WEIGHT_VALUE && ip.getWeight() > MIN_WEIGHT_VALUE) { if (ip.getWeight() < MIN_POSITIVE_WEIGHT_VALUE && ip.getWeight() > MIN_WEIGHT_VALUE) {
ip.setWeight(MIN_POSTIVE_WEIGHT_VALUE); ip.setWeight(MIN_POSITIVE_WEIGHT_VALUE);
} else if (ip.getWeight() < MIN_WEIGHT_VALUE) { } else if (ip.getWeight() < MIN_WEIGHT_VALUE) {
ip.setWeight(0.0D); ip.setWeight(0.0D);
} }

View File

@ -427,6 +427,7 @@ public class Service extends com.alibaba.nacos.api.naming.pojo.Service implement
recalculateChecksum(); recalculateChecksum();
} }
@Override
public String getChecksum() { public String getChecksum() {
if (StringUtils.isEmpty(checksum)) { if (StringUtils.isEmpty(checksum)) {
recalculateChecksum(); recalculateChecksum();

View File

@ -0,0 +1,107 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.naming.core;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.naming.CommonParams;
import com.alibaba.nacos.naming.boot.RunningConfig;
import com.alibaba.nacos.naming.cluster.ServerListManager;
import com.alibaba.nacos.naming.cluster.servers.Server;
import com.alibaba.nacos.naming.misc.HttpClient;
import com.alibaba.nacos.naming.misc.Loggers;
import com.alibaba.nacos.naming.misc.NetUtils;
import com.alibaba.nacos.naming.misc.UtilsAndCommons;
import com.alibaba.nacos.naming.pojo.Subscriber;
import com.alibaba.nacos.naming.pojo.Subscribers;
import com.alibaba.nacos.naming.push.PushService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.net.HttpURLConnection;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
/**
* @author Nicholas
* @since 1.0.1
*/
@Service
public class SubscribeManager {
private static final String SUBSCRIBER_ON_SYNC_URL = "/service/subscribers";
@Autowired
private PushService pushService;
@Autowired
private ServerListManager serverListManager;
private List<Subscriber> getSubscribers(String serviceName, String namespaceId) {
return pushService.getClients(serviceName, namespaceId);
}
/**
* @param serviceName
* @param namespaceId
* @param aggregation
* @return
* @throws InterruptedException
*/
public List<Subscriber> getSubscribers(String serviceName, String namespaceId, boolean aggregation) throws InterruptedException {
if (aggregation) {
// size = 1 means only myself in the list, we need at least one another server alive:
if (serverListManager.getHealthyServers().size() <= 1) {
return getSubscribers(serviceName, namespaceId);
}
List<Subscriber> subscriberList = new ArrayList<Subscriber>();
// try sync data from remote server:
for (Server server : serverListManager.getHealthyServers()) {
Map<String, String> paramValues = new HashMap<>(128);
paramValues.put(CommonParams.SERVICE_NAME, serviceName);
paramValues.put(CommonParams.NAMESPACE_ID, namespaceId);
paramValues.put("aggregation", String.valueOf(Boolean.FALSE));
if (NetUtils.localServer().equals(server.getKey())) {
subscriberList.addAll(getSubscribers(serviceName, namespaceId));
}
HttpClient.HttpResult result = HttpClient.httpGet("http://" + server.getKey() + RunningConfig.getContextPath()
+ UtilsAndCommons.NACOS_NAMING_CONTEXT + SUBSCRIBER_ON_SYNC_URL, new ArrayList<>(), paramValues);
if (HttpURLConnection.HTTP_OK == result.code) {
Subscribers subscribers = (Subscribers) JSONObject.parseObject(result.content, Subscribers.class);
subscriberList.addAll(subscribers.getSubscribers());
}
return subscriberList.stream().filter(distinctByKey(Subscriber::toString)).collect(Collectors.toList());
}
} else {
// local server
return getSubscribers(serviceName, namespaceId);
}
return Collections.emptyList();
}
public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
Map<Object, Boolean> seen = new ConcurrentHashMap<>(128);
return object -> seen.putIfAbsent(keyExtractor.apply(object), Boolean.TRUE) == null;
}
}

View File

@ -55,7 +55,7 @@ public class HttpHealthCheckProcessor implements HealthCheckProcessor {
private static AsyncHttpClient asyncHttpClient; private static AsyncHttpClient asyncHttpClient;
public static final int CONNECT_TIMEOUT_MS = 500; private static final int CONNECT_TIMEOUT_MS = 500;
static { static {
try { try {

View File

@ -143,6 +143,7 @@ public class RsInfo {
this.metadata = metadata; this.metadata = metadata;
} }
@Override
public String toString() { public String toString() {
return JSON.toJSONString(this); return JSON.toJSONString(this);
} }

View File

@ -59,13 +59,13 @@ public class TcpSuperSenseProcessor implements HealthCheckProcessor, Runnable {
/** /**
* this value has been carefully tuned, do not modify unless you're confident * this value has been carefully tuned, do not modify unless you're confident
*/ */
public static final int NIO_THREAD_COUNT = Runtime.getRuntime().availableProcessors() <= 1 ? private static final int NIO_THREAD_COUNT = Runtime.getRuntime().availableProcessors() <= 1 ?
1 : Runtime.getRuntime().availableProcessors() / 2; 1 : Runtime.getRuntime().availableProcessors() / 2;
/** /**
* because some hosts doesn't support keep-alive connections, disabled temporarily * because some hosts doesn't support keep-alive connections, disabled temporarily
*/ */
public static final long TCP_KEEP_ALIVE_MILLIS = 0; private static final long TCP_KEEP_ALIVE_MILLIS = 0;
private static ScheduledExecutorService TCP_CHECK_EXECUTOR private static ScheduledExecutorService TCP_CHECK_EXECUTOR
= new ScheduledThreadPoolExecutor(1, new ThreadFactory() { = new ScheduledThreadPoolExecutor(1, new ThreadFactory() {
@ -111,7 +111,6 @@ public class TcpSuperSenseProcessor implements HealthCheckProcessor, Runnable {
if (CollectionUtils.isEmpty(ips)) { if (CollectionUtils.isEmpty(ips)) {
return; return;
} }
Service service = task.getCluster().getService();
for (Instance ip : ips) { for (Instance ip : ips) {

View File

@ -54,15 +54,13 @@ import java.util.zip.GZIPInputStream;
* @author nacos * @author nacos
*/ */
public class HttpClient { public class HttpClient {
public static final int TIME_OUT_MILLIS = 10000; private static final int TIME_OUT_MILLIS = 10000;
public static final int CON_TIME_OUT_MILLIS = 5000; private static final int CON_TIME_OUT_MILLIS = 5000;
private static AsyncHttpClient asyncHttpClient; private static AsyncHttpClient asyncHttpClient;
private static CloseableHttpClient postClient; private static CloseableHttpClient postClient;
private static PoolingHttpClientConnectionManager connectionManager;
static { static {
AsyncHttpClientConfig.Builder builder = new AsyncHttpClientConfig.Builder(); AsyncHttpClientConfig.Builder builder = new AsyncHttpClientConfig.Builder();
builder.setMaximumConnectionsTotal(-1); builder.setMaximumConnectionsTotal(-1);

View File

@ -134,7 +134,6 @@ public class PerformanceLoggerThread {
try { try {
int serviceCount = serviceManager.getServiceCount(); int serviceCount = serviceManager.getServiceCount();
int ipCount = serviceManager.getInstanceCount(); int ipCount = serviceManager.getInstanceCount();
long maxPushMaxCost = getMaxPushCost();
long maxPushCost = getMaxPushCost(); long maxPushCost = getMaxPushCost();
long avgPushCost = getAvgPushCost(); long avgPushCost = getAvgPushCost();

View File

@ -0,0 +1,94 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.naming.pojo;
import java.io.Serializable;
/**
* @author nicholas
* @version $Id: Subscriber.java, v 0.1 2019-05-28 下午10:47 nicholas Exp $$
*/
public class Subscriber implements Serializable {
private String addrStr;
private String agent;
private String app;
private String ip;
private String namespaceId;
private String serviceName;
public Subscriber(String addrStr, String agent, String app, String ip, String namespaceId, String serviceName) {
this.addrStr = addrStr;
this.agent = agent;
this.app = app;
this.ip = ip;
this.namespaceId = namespaceId;
this.serviceName = serviceName;
}
public String getAddrStr() {
return addrStr;
}
public void setAddrStr(String addrStr) {
this.addrStr = addrStr;
}
public String getAgent() {
return agent;
}
public void setAgent(String agent) {
this.agent = agent;
}
public String getApp() {
return app;
}
public void setApp(String app) {
this.app = app;
}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public String getNamespaceId() {
return namespaceId;
}
public void setNamespaceId(String namespaceId) {
this.namespaceId = namespaceId;
}
public String getServiceName() {
return serviceName;
}
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
}

View File

@ -0,0 +1,36 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.naming.pojo;
import java.io.Serializable;
import java.util.List;
/**
* @author nicholas
* @version $Id: Subscribers.java, v 0.1 2019-05-28 下午10:47 nicholas Exp $$
*/
public class Subscribers implements Serializable {
private List<Subscriber> subscribers;
public List<Subscriber> getSubscribers() {
return subscribers;
}
public void setSubscribers(List<Subscriber> subscribers) {
this.subscribers = subscribers;
}
}

View File

@ -19,6 +19,7 @@ import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.naming.misc.Loggers; import com.alibaba.nacos.naming.misc.Loggers;
import com.alibaba.nacos.naming.misc.SwitchDomain; import com.alibaba.nacos.naming.misc.SwitchDomain;
import com.alibaba.nacos.naming.misc.UtilsAndCommons; import com.alibaba.nacos.naming.misc.UtilsAndCommons;
import com.alibaba.nacos.naming.pojo.Subscriber;
import org.apache.commons.collections.MapUtils; import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.util.VersionUtil; import org.codehaus.jackson.util.VersionUtil;
@ -46,7 +47,7 @@ public class PushService {
@Autowired @Autowired
private SwitchDomain switchDomain; private SwitchDomain switchDomain;
public static final long ACK_TIMEOUT_NANOS = TimeUnit.SECONDS.toNanos(10L); private static final long ACK_TIMEOUT_NANOS = TimeUnit.SECONDS.toNanos(10L);
private static final int MAX_RETRY_TIMES = 1; private static final int MAX_RETRY_TIMES = 1;
@ -133,7 +134,7 @@ public class PushService {
String tenant, String tenant,
String app) { String app) {
PushClient client = new PushService.PushClient(namespaceId, PushClient client = new PushClient(namespaceId,
serviceName, serviceName,
clusters, clusters,
agent, agent,
@ -166,6 +167,19 @@ public class PushService {
} }
} }
public List<Subscriber> getClients(String serviceName, String namespaceId) {
String serviceKey = UtilsAndCommons.assembleFullServiceName(namespaceId, serviceName);
ConcurrentMap<String, PushClient> clientConcurrentMap = clientMap.get(serviceKey);
if (Objects.isNull(clientConcurrentMap)) {
return null;
}
List<Subscriber> clients = new ArrayList<Subscriber>();
clientConcurrentMap.forEach((key, client) -> {
clients.add(new Subscriber(client.getAddrStr(),client.getAgent(),client.getApp(),client.getIp(),namespaceId,serviceName));
});
return clients;
}
public static void removeClientIfZombie() { public static void removeClientIfZombie() {
int size = 0; int size = 0;

View File

@ -73,6 +73,7 @@ public class OverrideParameterRequestWrapper extends HttpServletRequestWrapper {
return params; return params;
} }
@Override
public String[] getParameterValues(String name) { public String[] getParameterValues(String name) {
return params.get(name); return params.get(name);
} }

View File

@ -0,0 +1,97 @@
package com.alibaba.nacos.naming.core;
import com.alibaba.nacos.naming.BaseTest;
import com.alibaba.nacos.naming.cluster.ServerListManager;
import com.alibaba.nacos.naming.cluster.servers.Server;
import com.alibaba.nacos.naming.pojo.Subscriber;
import com.alibaba.nacos.naming.push.PushService;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.ArrayList;
import java.util.List;
/**
* @author Nicholas
*/
@SpringBootTest
@RunWith(SpringRunner.class)
public class SubscribeManagerTest extends BaseTest {
@Mock
private SubscribeManager subscribeManager;
@Mock
private PushService pushService;
@Mock
private ServerListManager serverListManager;
@Before
public void before() {
super.before();
subscribeManager = new SubscribeManager();
}
@Test
public void getSubscribersWithFalse() {
String serviceName = "test";
String namespaceId = "public";
boolean aggregation = Boolean.FALSE;
try {
List<Subscriber> clients = new ArrayList<Subscriber>();
Subscriber subscriber = new Subscriber("127.0.0.1:8080", "test", "app", "127.0.0.1", namespaceId, serviceName);
clients.add(subscriber);
Mockito.when(pushService.getClients(Mockito.anyString(), Mockito.anyString())).thenReturn(clients);
List<Subscriber> list = subscribeManager.getSubscribers(serviceName, namespaceId, aggregation);
Assert.assertNotNull(list);
Assert.assertEquals(1, list.size());
Assert.assertEquals("public", list.get(0).getNamespaceId());
} catch (Exception e) {
}
}
@Test
public void getSubscribersWithTrue() {
String serviceName = "test";
String namespaceId = "public";
boolean aggregation = Boolean.TRUE;
try {
List<Subscriber> clients = new ArrayList<Subscriber>();
Subscriber subscriber = new Subscriber("127.0.0.1:8080", "test", "app", "127.0.0.1", namespaceId, serviceName);
clients.add(subscriber);
List<Server> healthyServers = new ArrayList<>();
for (int i = 0; i <= 2; i++) {
Server server = new Server();
server.setIp("127.0.0.1");
server.setServePort(8080 + i);
server.setAlive(Boolean.TRUE);
server.setAdWeight(10);
server.setLastRefTime(System.currentTimeMillis());
server.setLastRefTimeStr(String.valueOf(System.currentTimeMillis()));
server.setSite("site");
server.setWeight(1);
healthyServers.add(server);
}
Mockito.when(serverListManager.getHealthyServers()).thenReturn(healthyServers);
//Mockito.doReturn(3).when(serverListManager.getHealthyServers().size());
List<Subscriber> list = subscribeManager.getSubscribers(serviceName, namespaceId, aggregation);
Assert.assertNotNull(list);
Assert.assertEquals(2, list.size());
Assert.assertEquals("public", list.get(0).getNamespaceId());
} catch (Exception e) {
}
}
}

View File

@ -0,0 +1,46 @@
package com.alibaba.nacos.naming.pojo;
import org.junit.Assert;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
/**
* @author Nicholas
*/
public class SubscriberTest {
@Test
public void subscriberBeanTest() {
Subscriber subscriber = new Subscriber("127.0.0.1:8080", "agent", "app", "127.0.0.1", "public", "test");
subscriber.setAddrStr("127.0.0.1:8080");
subscriber.setIp("127.0.0.1");
subscriber.setApp("app");
subscriber.setAgent("agent");
subscriber.setNamespaceId("public");
subscriber.setServiceName("test");
subscriber.getAddrStr();
subscriber.getIp();
subscriber.getAgent();
subscriber.getApp();
subscriber.getNamespaceId();
subscriber.getServiceName();
Subscribers subscribers = new Subscribers();
List<Subscriber> subscriberList = new ArrayList<>();
subscriberList.add(subscriber);
subscribers.setSubscribers(subscriberList);
subscribers.getSubscribers();
Assert.assertNotNull(subscriberList);
Assert.assertEquals(1, subscriberList.size());
Assert.assertEquals("127.0.0.1:8080", subscriberList.get(0).getAddrStr());
Assert.assertEquals("127.0.0.1", subscriberList.get(0).getIp());
Assert.assertEquals("app", subscriberList.get(0).getApp());
Assert.assertEquals("agent", subscriberList.get(0).getAgent());
Assert.assertEquals("public", subscriberList.get(0).getNamespaceId());
Assert.assertEquals("test", subscriberList.get(0).getServiceName());
}
}

View File

@ -435,6 +435,96 @@ public class ConfigAPI_ITCase {
iconfig.removeListener(dataId, group, ml); iconfig.removeListener(dataId, group, ml);
} }
/**
* @TCDescription : nacos_在主动拉取配置后并注册Listener在更新配置后才触发Listener监听事件(使用特定接口)
* @TestStep : TODO Test steps
* @ExpectResult : TODO expect results
* @author xiaochun.xxc
* @since 3.6.8
*/
@Test
public void nacos_addListener_5() throws InterruptedException, NacosException {
final AtomicInteger count = new AtomicInteger(0);
final String content = "test-abc";
final String newContent = "new-test-def";
boolean result = iconfig.publishConfig(dataId, group, content);
Assert.assertTrue(result);
Thread.sleep(2000);
Listener ml = new AbstractListener() {
@Override
public void receiveConfigInfo(String configInfo) {
count.incrementAndGet();
System.out.println("Listener receive : [" + configInfo + "]");
Assert.assertEquals(content, newContent);
}
};
String receiveContent = iconfig.getConfigAndSignListener(dataId, group, 1000, ml);
System.out.println(receiveContent);
result = iconfig.publishConfig(dataId, group, newContent);
Assert.assertTrue(result);
Assert.assertEquals(content, receiveContent);
Thread.sleep(2000);
Assert.assertEquals(1, count.get());
iconfig.removeListener(dataId, group, ml);
}
/**
* @TCDescription : nacos_在主动拉取配置后并注册Listener在更新配置后才触发Listener监听事件(进行配置参数设置)
* @TestStep : TODO Test steps
* @ExpectResult : TODO expect results
* @author xiaochun.xxc
* @since 3.6.8
*/
@Test
public void nacos_addListener_6() throws InterruptedException, NacosException {
Properties properties = new Properties();
properties.put(PropertyKeyConst.SERVER_ADDR, "127.0.0.1"+":"+port);
properties.put(PropertyKeyConst.ENABLE_REMOTE_SYNC_CONFIG, "true");
ConfigService iconfig = NacosFactory.createConfigService(properties);
final AtomicInteger count = new AtomicInteger(0);
final String content = "test-abc";
final String newContent = "new-test-def";
boolean result = iconfig.publishConfig(dataId, group, content);
Assert.assertTrue(result);
Thread.sleep(2000);
Listener ml = new AbstractListener() {
@Override
public void receiveConfigInfo(String configInfo) {
count.incrementAndGet();
System.out.println("Listener receive : [" + configInfo + "]");
Assert.assertEquals(content, newContent);
}
};
iconfig.addListener(dataId, group, ml);
String receiveContent = iconfig.getConfig(dataId, group, 1000);
System.out.println(receiveContent);
result = iconfig.publishConfig(dataId, group, newContent);
Assert.assertTrue(result);
Thread.sleep(2000);
receiveContent = iconfig.getConfig(dataId, group, 1000);
Assert.assertEquals(newContent, receiveContent);
Assert.assertEquals(1, count.get());
iconfig.removeListener(dataId, group, ml);
}
/** /**
* @TCDescription : nacos_正常移除监听器 * @TCDescription : nacos_正常移除监听器
* @TestStep : TODO Test steps * @TestStep : TODO Test steps

View File

@ -83,7 +83,7 @@ public class ConfigLongPoll_ITCase {
} }
}); });
TimeUnit.SECONDS.sleep(30); TimeUnit.SECONDS.sleep(10);
} }