1
0
mirror of https://gitee.com/mirrors/Spring-Cloud-Alibaba.git synced 2021-06-26 13:25:11 +08:00

Merge remote-tracking branch 'upstream/master'

This commit is contained in:
fangjian0423 2019-09-05 15:10:57 +08:00
commit 9344473e51
40 changed files with 1151 additions and 226 deletions

View File

@ -33,6 +33,7 @@ import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Predicate; import java.util.function.Predicate;
import java.util.stream.Stream; import java.util.stream.Stream;
import com.alibaba.cloud.nacos.NacosNamingManager;
import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.listen.Listenable; import org.apache.curator.framework.listen.Listenable;
import org.apache.curator.framework.listen.ListenerContainer; import org.apache.curator.framework.listen.ListenerContainer;
@ -504,8 +505,8 @@ public class DubboServiceDiscoveryAutoConfiguration {
*/ */
private final Set<String> listeningServices; private final Set<String> listeningServices;
NacosConfiguration(NacosDiscoveryProperties nacosDiscoveryProperties) { NacosConfiguration(NacosNamingManager nacosNamingManager) {
this.namingService = nacosDiscoveryProperties.namingServiceInstance(); this.namingService = nacosNamingManager.getNamingService();
this.listeningServices = new ConcurrentSkipListSet<>(); this.listeningServices = new ConcurrentSkipListSet<>();
} }

View File

@ -5,6 +5,7 @@ import java.io.StringReader;
import java.util.Properties; import java.util.Properties;
import java.util.concurrent.Executor; import java.util.concurrent.Executor;
import com.alibaba.cloud.nacos.NacosConfigManager;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationArguments;
@ -24,7 +25,6 @@ import com.alibaba.nacos.api.config.listener.Listener;
*/ */
@SpringBootApplication @SpringBootApplication
public class Application { public class Application {
public static void main(String[] args) { public static void main(String[] args) {
SpringApplication.run(Application.class, args); SpringApplication.run(Application.class, args);
} }
@ -40,14 +40,14 @@ class SampleRunner implements ApplicationRunner {
int userAge; int userAge;
@Autowired @Autowired
private NacosConfigProperties nacosConfigProperties; private NacosConfigManager nacosConfigManager;
@Override @Override
public void run(ApplicationArguments args) throws Exception { public void run(ApplicationArguments args) throws Exception {
System.out.println( System.out.println(
String.format("Initial username=%s, userAge=%d", userName, userAge)); String.format("Initial username=%s, userAge=%d", userName, userAge));
nacosConfigProperties.configServiceInstance().addListener( nacosConfigManager.getConfigService().addListener(
"nacos-config-example.properties", "DEFAULT_GROUP", new Listener() { "nacos-config-example.properties", "DEFAULT_GROUP", new Listener() {
/** /**

View File

@ -44,6 +44,11 @@ public class NacosConfigAutoConfiguration {
return new NacosConfigProperties(); return new NacosConfigProperties();
} }
@Bean
public NacosConfigManager nacosConfigManager() {
return new NacosConfigManager();
}
@Bean @Bean
public NacosRefreshProperties nacosRefreshProperties() { public NacosRefreshProperties nacosRefreshProperties() {
return new NacosRefreshProperties(); return new NacosRefreshProperties();
@ -56,10 +61,10 @@ public class NacosConfigAutoConfiguration {
@Bean @Bean
public NacosContextRefresher nacosContextRefresher( public NacosContextRefresher nacosContextRefresher(
NacosConfigProperties nacosConfigProperties, NacosConfigManager nacosConfigManager,
NacosRefreshProperties nacosRefreshProperties, NacosRefreshProperties nacosRefreshProperties,
NacosRefreshHistory refreshHistory) { NacosRefreshHistory refreshHistory) {
return new NacosContextRefresher(nacosRefreshProperties, refreshHistory, return new NacosContextRefresher(nacosRefreshProperties, refreshHistory,
nacosConfigProperties.configServiceInstance()); nacosConfigManager.getConfigService());
} }
} }

View File

@ -36,10 +36,17 @@ public class NacosConfigBootstrapConfiguration {
return new NacosConfigProperties(); return new NacosConfigProperties();
} }
@Bean
@ConditionalOnMissingBean
public NacosConfigManager nacosConfigManager() {
return new NacosConfigManager();
}
@Bean @Bean
public NacosPropertySourceLocator nacosPropertySourceLocator( public NacosPropertySourceLocator nacosPropertySourceLocator(
NacosConfigManager nacosConfigManager,
NacosConfigProperties nacosConfigProperties) { NacosConfigProperties nacosConfigProperties) {
return new NacosPropertySourceLocator(nacosConfigProperties); return new NacosPropertySourceLocator(nacosConfigManager, nacosConfigProperties);
} }
} }

View File

@ -0,0 +1,42 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.cloud.nacos;
import com.alibaba.nacos.api.config.ConfigService;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/**
* @author <a href="mailto:liaochunyhm@live.com">liaochuntao</a>
*/
public class NacosConfigManager implements ApplicationContextAware {
private ConfigService configService;
public ConfigService getConfigService() {
return configService;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
NacosConfigProperties properties = applicationContext
.getBean(NacosConfigProperties.class);
configService = properties.configServiceInstance();
}
}

View File

@ -72,9 +72,11 @@ public class NacosConfigProperties {
private void overrideFromEnv() { private void overrideFromEnv() {
if (StringUtils.isEmpty(this.getServerAddr())) { if (StringUtils.isEmpty(this.getServerAddr())) {
String serverAddr = environment.resolvePlaceholders("${spring.cloud.nacos.config.server-addr:}"); String serverAddr = environment
if(StringUtils.isEmpty(serverAddr)) { .resolvePlaceholders("${spring.cloud.nacos.config.server-addr:}");
serverAddr = environment.resolvePlaceholders("${spring.cloud.nacos.server-addr}"); if (StringUtils.isEmpty(serverAddr)) {
serverAddr = environment
.resolvePlaceholders("${spring.cloud.nacos.server-addr}");
} }
this.setServerAddr(serverAddr); this.setServerAddr(serverAddr);
} }
@ -125,10 +127,11 @@ public class NacosConfigProperties {
private String configRetryTime; private String configRetryTime;
/** /**
* If you want to pull it yourself when the program starts to get the configuration for the first time, * If you want to pull it yourself when the program starts to get the configuration
* and the registered Listener is used for future configuration updates, you can keep the original * for the first time, and the registered Listener is used for future configuration
* code unchanged, just add the system parameter: enableRemoteSyncConfig = "true" ( But there is network overhead); * updates, you can keep the original code unchanged, just add the system parameter:
* therefore we recommend that you use {@link ConfigService#getConfigAndSignListener} directly. * enableRemoteSyncConfig = "true" ( But there is network overhead); therefore we
* recommend that you use {@link ConfigService#getConfigAndSignListener} directly.
*/ */
private boolean enableRemoteSyncConfig = false; private boolean enableRemoteSyncConfig = false;
@ -400,6 +403,7 @@ public class NacosConfigProperties {
+ refreshableDataids + '\'' + ", extConfig=" + extConfig + '}'; + refreshableDataids + '\'' + ", extConfig=" + extConfig + '}';
} }
@Deprecated
public ConfigService configServiceInstance() { public ConfigService configServiceInstance() {
if (null != configService) { if (null != configService) {
@ -415,9 +419,11 @@ public class NacosConfigProperties {
properties.put(CONTEXT_PATH, Objects.toString(this.contextPath, "")); properties.put(CONTEXT_PATH, Objects.toString(this.contextPath, ""));
properties.put(CLUSTER_NAME, Objects.toString(this.clusterName, "")); properties.put(CLUSTER_NAME, Objects.toString(this.clusterName, ""));
properties.put(MAX_RETRY, Objects.toString(this.maxRetry, "")); properties.put(MAX_RETRY, Objects.toString(this.maxRetry, ""));
properties.put(CONFIG_LONG_POLL_TIMEOUT, Objects.toString(this.configLongPollTimeout, "")); properties.put(CONFIG_LONG_POLL_TIMEOUT,
Objects.toString(this.configLongPollTimeout, ""));
properties.put(CONFIG_RETRY_TIME, Objects.toString(this.configRetryTime, "")); properties.put(CONFIG_RETRY_TIME, Objects.toString(this.configRetryTime, ""));
properties.put(ENABLE_REMOTE_SYNC_CONFIG, Objects.toString(this.enableRemoteSyncConfig, "")); properties.put(ENABLE_REMOTE_SYNC_CONFIG,
Objects.toString(this.enableRemoteSyncConfig, ""));
String endpoint = Objects.toString(this.endpoint, ""); String endpoint = Objects.toString(this.endpoint, "");
if (endpoint.contains(":")) { if (endpoint.contains(":")) {

View File

@ -16,7 +16,6 @@
package com.alibaba.cloud.nacos.client; package com.alibaba.cloud.nacos.client;
import java.io.StringReader;
import java.util.Date; import java.util.Date;
import java.util.Enumeration; import java.util.Enumeration;
import java.util.HashMap; import java.util.HashMap;
@ -25,11 +24,10 @@ import java.util.Properties;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import com.alibaba.cloud.nacos.NacosPropertySourceRepository; import com.alibaba.cloud.nacos.NacosPropertySourceRepository;
import com.alibaba.cloud.nacos.parser.NacosDataParserHandler;
import com.alibaba.nacos.api.config.ConfigService; import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.exception.NacosException;
@ -84,24 +82,18 @@ public class NacosPropertySourceBuilder {
try { try {
data = configService.getConfig(dataId, group, timeout); data = configService.getConfig(dataId, group, timeout);
if (StringUtils.isEmpty(data)) { if (StringUtils.isEmpty(data)) {
log.warn(
"Ignore the empty nacos configuration and get it based on dataId[{}] & group[{}]",
dataId, group);
return EMPTY_PROPERTIES; return EMPTY_PROPERTIES;
} }
log.info(String.format(
"Loading nacos data, dataId: '%s', group: '%s', data: %s", dataId,
group, data));
log.info(String.format("Loading nacos data, dataId: '%s', group: '%s'", Properties properties = NacosDataParserHandler.getInstance()
dataId, group)); .parseNacosData(data, fileExtension);
return properties == null ? EMPTY_PROPERTIES : properties;
if ("properties".equalsIgnoreCase(fileExtension)) {
Properties properties = new Properties();
properties.load(new StringReader(data));
return properties;
}
else if ("yaml".equalsIgnoreCase(fileExtension)
|| "yml".equalsIgnoreCase(fileExtension)) {
YamlPropertiesFactoryBean yamlFactory = new YamlPropertiesFactoryBean();
yamlFactory.setResources(new ByteArrayResource(data.getBytes()));
return yamlFactory.getObject();
}
} }
catch (NacosException e) { catch (NacosException e) {
log.error("get data from Nacos error,dataId:{}, ", dataId, e); log.error("get data from Nacos error,dataId:{}, ", dataId, e);

View File

@ -16,9 +16,9 @@
package com.alibaba.cloud.nacos.client; package com.alibaba.cloud.nacos.client;
import java.util.Arrays;
import java.util.List; import java.util.List;
import com.alibaba.cloud.nacos.NacosConfigManager;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.cloud.bootstrap.config.PropertySourceLocator; import org.springframework.cloud.bootstrap.config.PropertySourceLocator;
@ -31,6 +31,7 @@ import org.springframework.util.StringUtils;
import com.alibaba.cloud.nacos.NacosConfigProperties; import com.alibaba.cloud.nacos.NacosConfigProperties;
import com.alibaba.cloud.nacos.NacosPropertySourceRepository; import com.alibaba.cloud.nacos.NacosPropertySourceRepository;
import com.alibaba.cloud.nacos.parser.NacosDataParserHandler;
import com.alibaba.cloud.nacos.refresh.NacosContextRefresher; import com.alibaba.cloud.nacos.refresh.NacosContextRefresher;
import com.alibaba.nacos.api.config.ConfigService; import com.alibaba.nacos.api.config.ConfigService;
@ -47,21 +48,23 @@ public class NacosPropertySourceLocator implements PropertySourceLocator {
private static final String SEP1 = "-"; private static final String SEP1 = "-";
private static final String DOT = "."; private static final String DOT = ".";
private static final String SHARED_CONFIG_SEPARATOR_CHAR = "[,]"; private static final String SHARED_CONFIG_SEPARATOR_CHAR = "[,]";
private static final List<String> SUPPORT_FILE_EXTENSION = Arrays.asList("properties",
"yaml", "yml");
private NacosPropertySourceBuilder nacosPropertySourceBuilder; private NacosPropertySourceBuilder nacosPropertySourceBuilder;
private NacosConfigProperties nacosConfigProperties; private NacosConfigProperties nacosConfigProperties;
public NacosPropertySourceLocator(NacosConfigProperties nacosConfigProperties) { private NacosConfigManager nacosConfigManager;
public NacosPropertySourceLocator(NacosConfigManager nacosConfigManager,
NacosConfigProperties nacosConfigProperties) {
this.nacosConfigManager = nacosConfigManager;
this.nacosConfigProperties = nacosConfigProperties; this.nacosConfigProperties = nacosConfigProperties;
} }
@Override @Override
public PropertySource<?> locate(Environment env) { public PropertySource<?> locate(Environment env) {
ConfigService configService = nacosConfigProperties.configServiceInstance(); ConfigService configService = nacosConfigManager.getConfigService();
if (null == configService) { if (null == configService) {
log.warn("no instance of config service found, can't load config from nacos"); log.warn("no instance of config service found, can't load config from nacos");
@ -126,7 +129,7 @@ public class NacosPropertySourceLocator implements PropertySourceLocator {
for (NacosConfigProperties.Config config : extConfigs) { for (NacosConfigProperties.Config config : extConfigs) {
String dataId = config.getDataId(); String dataId = config.getDataId();
String fileExtension = dataId.substring(dataId.lastIndexOf(".") + 1); String fileExtension = dataId.substring(dataId.lastIndexOf(DOT) + 1);
loadNacosDataIfPresent(compositePropertySource, dataId, config.getGroup(), loadNacosDataIfPresent(compositePropertySource, dataId, config.getGroup(),
fileExtension, config.isRefresh()); fileExtension, config.isRefresh());
} }
@ -184,30 +187,14 @@ public class NacosPropertySourceLocator implements PropertySourceLocator {
} }
private static void checkDataIdFileExtension(String[] dataIdArray) { private static void checkDataIdFileExtension(String[] dataIdArray) {
StringBuilder stringBuilder = new StringBuilder(); if (dataIdArray == null || dataIdArray.length < 1) {
throw new IllegalStateException("The dataId cannot be empty");
for (String dataId : dataIdArray) {
if (!canLoadFileExtension(dataId)) {
stringBuilder.append(dataId).append(",");
} }
// Just decide that the current dataId must have a suffix
NacosDataParserHandler.getInstance().checkDataId(dataIdArray);
} }
if (stringBuilder.length() > 0) { private boolean checkDataIdIsRefreshable(String refreshDataIds, String sharedDataId) {
String result = stringBuilder.substring(0, stringBuilder.length() - 1);
throw new IllegalStateException(String.format(
"[%s] must end file extension with properties|yaml|yml",
result));
}
}
private static boolean canLoadFileExtension(String dataId) {
return SUPPORT_FILE_EXTENSION.stream()
.anyMatch((fileExtension) -> StringUtils.endsWithIgnoreCase(dataId,
fileExtension));
}
private boolean checkDataIdIsRefreshable(String refreshDataIds,
String sharedDataId) {
if (StringUtils.isEmpty(refreshDataIds)) { if (StringUtils.isEmpty(refreshDataIds)) {
return false; return false;
} }

View File

@ -42,8 +42,8 @@ public class NacosConfigEndpoint {
private final NacosRefreshHistory refreshHistory; private final NacosRefreshHistory refreshHistory;
private ThreadLocal<DateFormat> dateFormat = ThreadLocal.withInitial(() -> private ThreadLocal<DateFormat> dateFormat = ThreadLocal
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); .withInitial(() -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
public NacosConfigEndpoint(NacosConfigProperties properties, public NacosConfigEndpoint(NacosConfigProperties properties,
NacosRefreshHistory refreshHistory) { NacosRefreshHistory refreshHistory) {

View File

@ -16,6 +16,7 @@
package com.alibaba.cloud.nacos.endpoint; package com.alibaba.cloud.nacos.endpoint;
import com.alibaba.cloud.nacos.NacosConfigManager;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.autoconfigure.endpoint.condition.ConditionalOnEnabledEndpoint; import org.springframework.boot.actuate.autoconfigure.endpoint.condition.ConditionalOnEnabledEndpoint;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint; import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
@ -39,6 +40,9 @@ public class NacosConfigEndpointAutoConfiguration {
@Autowired @Autowired
private NacosConfigProperties nacosConfigProperties; private NacosConfigProperties nacosConfigProperties;
@Autowired
private NacosConfigManager nacosConfigManager;
@Autowired @Autowired
private NacosRefreshHistory nacosRefreshHistory; private NacosRefreshHistory nacosRefreshHistory;
@ -51,6 +55,6 @@ public class NacosConfigEndpointAutoConfiguration {
@Bean @Bean
public NacosConfigHealthIndicator nacosConfigHealthIndicator() { public NacosConfigHealthIndicator nacosConfigHealthIndicator() {
return new NacosConfigHealthIndicator(nacosConfigProperties.configServiceInstance()); return new NacosConfigHealthIndicator(nacosConfigManager.getConfigService());
} }
} }

View File

@ -0,0 +1,141 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* 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.cloud.nacos.parser;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import com.alibaba.nacos.client.utils.StringUtils;
/**
* @author zkz
*/
public abstract class AbstractNacosDataParser {
protected static final String DOT = ".";
protected static final String VALUE = "value";
private String extension;
private AbstractNacosDataParser nextParser;
protected AbstractNacosDataParser(String extension) {
if (StringUtils.isEmpty(extension)) {
throw new IllegalArgumentException("extension cannot be empty");
}
this.extension = extension.toLowerCase();
}
/** Verify file extensions */
public final boolean checkFileExtension(String extension) {
if (this.isLegal(extension.toLowerCase())) {
return true;
}
if (this.nextParser == null) {
return false;
}
return this.nextParser.checkFileExtension(extension);
}
/** Parsing nacos configuration content */
public final Properties parseNacosData(String data, String extension)
throws IOException {
if (extension == null || extension.length() < 1) {
throw new IllegalStateException("The file extension cannot be empty");
}
if (this.isLegal(extension.toLowerCase())) {
return this.doParse(data);
}
if (this.nextParser == null) {
throw new IllegalStateException(getTips(extension));
}
return this.nextParser.parseNacosData(data, extension);
}
/** Core logic for parsing */
protected abstract Properties doParse(String data) throws IOException;
protected AbstractNacosDataParser setNextParser(AbstractNacosDataParser nextParser) {
this.nextParser = nextParser;
return this;
}
/** add the next parser */
public AbstractNacosDataParser addNextParser(AbstractNacosDataParser nextParser) {
if (this.nextParser == null) {
this.nextParser = nextParser;
}
else {
this.nextParser.addNextParser(nextParser);
}
return this;
}
protected boolean isLegal(String extension) {
return this.extension.equalsIgnoreCase(extension)
|| this.extension.contains(extension);
}
/**
* Generate key-value pairs from the map
*/
protected Properties generateProperties(Map<String, String> map) {
if (null == map || map.isEmpty()) {
return null;
}
Properties properties = new Properties();
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
if (StringUtils.isBlank(key)) {
continue;
}
key = key.startsWith(DOT) ? key.replaceFirst("\\.", "") : key;
properties.put(key, entry.getValue());
}
return properties;
}
/**
* Reload the key ending in `value`,if you need
*/
protected Map<String, String> reloadMap(Map<String, String> map) {
if (map == null || map.isEmpty()) {
return null;
}
Map<String, String> result = new HashMap<>(map);
for (Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
if (key.contains(DOT)) {
int idx = key.lastIndexOf(DOT);
String suffix = key.substring(idx + 1);
if (VALUE.equalsIgnoreCase(suffix)) {
result.put(key.substring(0, idx), entry.getValue());
}
}
}
return result;
}
public static String getTips(String fileName) {
return String.format(
"[%s] must contains file extension with properties|yaml|yml|xml|json",
fileName);
}
}

View File

@ -0,0 +1,90 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* 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.cloud.nacos.parser;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import com.alibaba.nacos.client.utils.StringUtils;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
* @author zkz
*/
public class NacosDataJsonParser extends AbstractNacosDataParser {
protected NacosDataJsonParser() {
super("json");
}
@Override
protected Properties doParse(String data) throws IOException {
if (StringUtils.isEmpty(data)) {
return null;
}
Map<String, String> map = parseJSON2Map(data);
return this.generateProperties(this.reloadMap(map));
}
/**
* JSON to Map
*/
public static Map<String, String> parseJSON2Map(String json) throws IOException {
Map<String, String> map = new HashMap<>(32);
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readTree(json);
if (null == jsonNode) {
return map;
}
parseJsonNode(map, jsonNode, "");
return map;
}
private static void parseJsonNode(Map<String, String> jsonMap, JsonNode jsonNode,
String parentKey) {
Iterator<String> fieldNames = jsonNode.fieldNames();
while (fieldNames.hasNext()) {
String name = fieldNames.next();
String fullKey = StringUtils.isEmpty(parentKey) ? name
: parentKey + DOT + name;
JsonNode resultValue = jsonNode.findValue(name);
if (null == resultValue) {
continue;
}
if (resultValue.isArray()) {
Iterator<JsonNode> iterator = resultValue.elements();
while (iterator != null && iterator.hasNext()) {
JsonNode next = iterator.next();
if (null == next) {
continue;
}
parseJsonNode(jsonMap, next, fullKey);
}
continue;
}
if (resultValue.isObject()) {
parseJsonNode(jsonMap, resultValue, fullKey);
continue;
}
jsonMap.put(fullKey, resultValue.asText());
}
}
}

View File

@ -0,0 +1,74 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* 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.cloud.nacos.parser;
import java.io.IOException;
import java.util.Properties;
/**
* @author zkz
*/
public class NacosDataParserHandler {
private static final NacosDataParserHandler HANDLER = new NacosDataParserHandler();
private AbstractNacosDataParser parser;
private NacosDataParserHandler() {
parser = this.createParser();
}
/** Parsing nacos configuration content */
public Properties parseNacosData(String data, String extension) throws IOException {
if (null == parser) {
parser = this.createParser();
}
return parser.parseNacosData(data, extension);
}
/** check the validity of file extensions in dataid */
public boolean checkDataId(String... dataIdAry) {
StringBuilder stringBuilder = new StringBuilder();
for (String dataId : dataIdAry) {
int idx = dataId.lastIndexOf(AbstractNacosDataParser.DOT);
if (idx > 0 && idx < dataId.length() - 1) {
String extension = dataId.substring(idx + 1);
if (parser.checkFileExtension(extension)) {
break;
}
}
// add tips
stringBuilder.append(dataId).append(",");
}
if (stringBuilder.length() > 0) {
String result = stringBuilder.substring(0, stringBuilder.length() - 1);
throw new IllegalStateException(AbstractNacosDataParser.getTips(result));
}
return true;
}
private AbstractNacosDataParser createParser() {
return new NacosDataPropertiesParser().addNextParser(new NacosDataYamlParser())
.addNextParser(new NacosDataXmlParser())
.addNextParser(new NacosDataJsonParser());
}
public static NacosDataParserHandler getInstance() {
return HANDLER;
}
}

View File

@ -0,0 +1,38 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* 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.cloud.nacos.parser;
import java.io.IOException;
import java.io.StringReader;
import java.util.Properties;
/**
* @author zkz
*/
public class NacosDataPropertiesParser extends AbstractNacosDataParser {
public NacosDataPropertiesParser() {
super("properties");
}
@Override
protected Properties doParse(String data) throws IOException {
Properties properties = new Properties();
properties.load(new StringReader(data));
return properties;
}
}

View File

@ -0,0 +1,132 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* 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.cloud.nacos.parser;
import java.io.IOException;
import java.io.StringReader;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import com.alibaba.nacos.client.utils.StringUtils;
/**
* With relatively few usage scenarios, only simple parsing is performed to reduce jar
* dependencies
*
* @author zkz
*/
public class NacosDataXmlParser extends AbstractNacosDataParser {
public NacosDataXmlParser() {
super("xml");
}
@Override
protected Properties doParse(String data) throws IOException {
if (StringUtils.isEmpty(data)) {
return null;
}
Map<String, String> map = parseXml2Map(data);
return this.generateProperties(this.reloadMap(map));
}
private Map<String, String> parseXml2Map(String xml) throws IOException {
xml = xml.replaceAll("\\r", "")
.replaceAll("\\n", "")
.replaceAll("\\t", "");
Map<String, String> map = new HashMap<>(32);
try {
DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance()
.newDocumentBuilder();
Document document = documentBuilder
.parse(new InputSource(new StringReader(xml)));
if (null == document) {
return null;
}
parseNodeList(document.getChildNodes(), map, "");
}
catch (Exception e) {
throw new IOException("The xml content parse error.", e.getCause());
}
return map;
}
private void parseNodeList(NodeList nodeList, Map<String, String> map,
String parentKey) {
if (nodeList == null || nodeList.getLength() < 1) {
return;
}
parentKey = parentKey == null ? "" : parentKey;
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
String value = node.getNodeValue();
value = value == null ? "" : value.trim();
String name = node.getNodeName();
name = name == null ? "" : name.trim();
if (StringUtils.isEmpty(name)) {
continue;
}
String key = StringUtils.isEmpty(parentKey) ? name : parentKey + DOT + name;
NamedNodeMap nodeMap = node.getAttributes();
parseNodeAttr(nodeMap, map, key);
if (node.getNodeType() == Node.ELEMENT_NODE && node.hasChildNodes()) {
parseNodeList(node.getChildNodes(), map, key);
continue;
}
if (value.length() < 1) {
continue;
}
map.put(parentKey, value);
}
}
private void parseNodeAttr(NamedNodeMap nodeMap, Map<String, String> map,
String parentKey) {
if (null == nodeMap || nodeMap.getLength() < 1) {
return;
}
for (int i = 0; i < nodeMap.getLength(); i++) {
Node node = nodeMap.item(i);
if (null == node) {
continue;
}
if (node.getNodeType() == Node.ATTRIBUTE_NODE) {
if (StringUtils.isEmpty(node.getNodeName())) {
continue;
}
if (StringUtils.isEmpty(node.getNodeValue())) {
continue;
}
map.put(String.join(DOT, parentKey, node.getNodeName()),
node.getNodeValue());
}
}
}
}

View File

@ -0,0 +1,39 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* 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.cloud.nacos.parser;
import java.util.Properties;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.io.ByteArrayResource;
/**
* @author zkz
*/
public class NacosDataYamlParser extends AbstractNacosDataParser {
public NacosDataYamlParser() {
super(",yml,yaml,");
}
@Override
protected Properties doParse(String data) {
YamlPropertiesFactoryBean yamlFactory = new YamlPropertiesFactoryBean();
yamlFactory.setResources(new ByteArrayResource(data.getBytes()));
return yamlFactory.getObject();
}
}

View File

@ -20,8 +20,7 @@ import com.alibaba.cloud.nacos.endpoint.NacosConfigEndpointAutoConfiguration;
@RunWith(SpringRunner.class) @RunWith(SpringRunner.class)
@SpringBootTest(classes = NacosConfigPropertiesServerAddressBothLevelTests.TestConfig.class, properties = { @SpringBootTest(classes = NacosConfigPropertiesServerAddressBothLevelTests.TestConfig.class, properties = {
"spring.cloud.nacos.config.server-addr=321,321,321,321:8848", "spring.cloud.nacos.config.server-addr=321,321,321,321:8848",
"spring.cloud.nacos.server-addr=123.123.123.123:8848" "spring.cloud.nacos.server-addr=123.123.123.123:8848" }, webEnvironment = RANDOM_PORT)
}, webEnvironment = RANDOM_PORT)
public class NacosConfigPropertiesServerAddressBothLevelTests { public class NacosConfigPropertiesServerAddressBothLevelTests {
@Autowired @Autowired
@ -29,7 +28,8 @@ public class NacosConfigPropertiesServerAddressBothLevelTests {
@Test @Test
public void testGetServerAddr() { public void testGetServerAddr() {
assertEquals("NacosConfigProperties server address was wrong","321,321,321,321:8848", properties.getServerAddr()); assertEquals("NacosConfigProperties server address was wrong",
"321,321,321,321:8848", properties.getServerAddr());
} }
@Configuration @Configuration

View File

@ -19,8 +19,7 @@ import com.alibaba.cloud.nacos.endpoint.NacosConfigEndpointAutoConfiguration;
*/ */
@RunWith(SpringRunner.class) @RunWith(SpringRunner.class)
@SpringBootTest(classes = NacosConfigPropertiesServerAddressTopLevelTests.TestConfig.class, properties = { @SpringBootTest(classes = NacosConfigPropertiesServerAddressTopLevelTests.TestConfig.class, properties = {
"spring.cloud.nacos.server-addr=123.123.123.123:8848" "spring.cloud.nacos.server-addr=123.123.123.123:8848" }, webEnvironment = RANDOM_PORT)
}, webEnvironment = RANDOM_PORT)
public class NacosConfigPropertiesServerAddressTopLevelTests { public class NacosConfigPropertiesServerAddressTopLevelTests {
@Autowired @Autowired
@ -28,7 +27,8 @@ public class NacosConfigPropertiesServerAddressTopLevelTests {
@Test @Test
public void testGetServerAddr() { public void testGetServerAddr() {
assertEquals("NacosConfigProperties server address was wrong","123.123.123.123:8848", properties.getServerAddr()); assertEquals("NacosConfigProperties server address was wrong",
"123.123.123.123:8848", properties.getServerAddr());
} }
@Configuration @Configuration

View File

@ -0,0 +1,258 @@
/*
* Copyright (C) 2018 the original author or authors.
*
* 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.cloud.nacos;
import com.alibaba.cloud.nacos.client.NacosPropertySourceLocator;
import com.alibaba.cloud.nacos.endpoint.NacosConfigEndpoint;
import com.alibaba.cloud.nacos.endpoint.NacosConfigEndpointAutoConfiguration;
import com.alibaba.cloud.nacos.refresh.NacosRefreshHistory;
import com.alibaba.nacos.client.config.NacosConfigService;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.api.support.MethodProxy;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.modules.junit4.PowerMockRunnerDelegate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.ImportAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.test.context.junit4.SpringRunner;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE;
/**
* @author zkz
*/
@RunWith(PowerMockRunner.class)
@PowerMockIgnore("javax.management.*")
@PowerMockRunnerDelegate(SpringRunner.class)
@PrepareForTest({ NacosConfigService.class })
@SpringBootTest(classes = NacosConfigurationXmlJsonTest.TestConfig.class, properties = {
"spring.application.name=xmlApp", "spring.profiles.active=dev"
,"spring.cloud.nacos.config.server-addr=127.0.0.1:8848"
,"spring.cloud.nacos.config.namespace=test-namespace"
,"spring.cloud.nacos.config.encode=utf-8"
,"spring.cloud.nacos.config.timeout=1000"
,"spring.cloud.nacos.config.group=test-group"
,"spring.cloud.nacos.config.name=test-name"
,"spring.cloud.nacos.config.cluster-name=test-cluster"
,"spring.cloud.nacos.config.file-extension=xml"
,"spring.cloud.nacos.config.contextPath=test-contextpath"
,"spring.cloud.nacos.config.ext-config[0].data-id=ext-json-test.json"
,"spring.cloud.nacos.config.ext-config[1].data-id=ext-common02.properties"
,"spring.cloud.nacos.config.ext-config[1].group=GLOBAL_GROUP"
,"spring.cloud.nacos.config.shared-dataids=shared-data1.properties"
,"spring.cloud.nacos.config.accessKey=test-accessKey"
,"spring.cloud.nacos.config.secretKey=test-secretKey"
}, webEnvironment = NONE)
public class NacosConfigurationXmlJsonTest {
static {
try {
Method method = PowerMockito.method(NacosConfigService.class, "getConfig",
String.class, String.class, long.class);
MethodProxy.proxy(method, new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if ("xmlApp.xml".equals(args[0]) && "test-group".equals(args[1])) {
return "<top>\n" +
" <first>one</first>\n" +
" <sencond value=\"two\">\n" +
" <third>three</third>\n" +
" </sencond>\n" +
"</top>";
}
if ("test-name.xml".equals(args[0]) && "test-group".equals(args[1])) {
return "<Server port=\"8005\" shutdown=\"SHUTDOWN\"> \n" +
" <Service name=\"Catalina\"> \n" +
" <Connector value=\"第二个连接器\"> \n" +
" <open>开启服务</open> \n" +
" <init>初始化一下</init> \n" +
" <process>\n" +
" <top>\n" +
" <first>one</first>\n" +
" <sencond value=\"two\">\n" +
" <third>three</third>\n" +
" </sencond>\n" +
" </top>\n" +
" </process> \n" +
" <destory>销毁一下</destory> \n" +
" <close>关闭服务</close> \n" +
" </Connector> \n" +
" </Service> \n" +
"</Server> ";
}
if ("test-name-dev.xml".equals(args[0]) && "test-group".equals(args[1])) {
return "<application android:label=\"@string/app_name\" android:icon=\"@drawable/osg\">\n" +
" <activity android:name=\".osgViewer\"\n" +
" android:label=\"@string/app_name\" android:screenOrientation=\"landscape\">\n" +
" <intent-filter>\n" +
" <action android:name=\"android.intent.action.MAIN\" />\n" +
" <category android:name=\"android.intent.category.LAUNCHER\" />\n" +
" </intent-filter>\n" +
" </activity>\n" +
"</application>";
}
if ("ext-json-test.json".equals(args[0]) && "DEFAULT_GROUP".equals(args[1])) {
return "{\n" +
" \"people\":{\n" +
" \"firstName\":\"Brett\",\n" +
" \"lastName\":\"McLaughlin\"\n" +
" }\n" +
"}";
}
if ("ext-config-common02.properties".equals(args[0]) && "GLOBAL_GROUP".equals(args[1])) {
return "global-ext-config=global-config-value-2";
}
if ("shared-data1.properties".equals(args[0]) && "DEFAULT_GROUP".equals(args[1])) {
return "shared-name=shared-value-1";
}
return "";
}
});
}
catch (Exception ignore) {
ignore.printStackTrace();
}
}
@Autowired
private NacosPropertySourceLocator locator;
@Autowired
private NacosConfigProperties properties;
@Autowired
private NacosRefreshHistory refreshHistory;
@Test
public void contextLoads() throws Exception {
assertNotNull("NacosPropertySourceLocator was not created", locator);
assertNotNull("NacosConfigProperties was not created", properties);
checkoutNacosConfigServerAddr();
checkoutNacosConfigNamespace();
checkoutNacosConfigClusterName();
checkoutNacosConfigAccessKey();
checkoutNacosConfigSecrectKey();
checkoutNacosConfigName();
checkoutNacosConfigGroup();
checkoutNacosConfigContextPath();
checkoutNacosConfigFileExtension();
checkoutNacosConfigTimeout();
checkoutNacosConfigEncode();
checkoutEndpoint();
}
private void checkoutNacosConfigServerAddr() {
assertEquals("NacosConfigProperties server address is wrong", "127.0.0.1:8848",
properties.getServerAddr());
}
private void checkoutNacosConfigNamespace() {
assertEquals("NacosConfigProperties namespace is wrong", "test-namespace",
properties.getNamespace());
}
private void checkoutNacosConfigClusterName() {
assertEquals("NacosConfigProperties' cluster is wrong", "test-cluster",
properties.getClusterName());
}
private void checkoutNacosConfigAccessKey() {
assertEquals("NacosConfigProperties' is access key is wrong", "test-accessKey",
properties.getAccessKey());
}
private void checkoutNacosConfigSecrectKey() {
assertEquals("NacosConfigProperties' is secret key is wrong", "test-secretKey",
properties.getSecretKey());
}
private void checkoutNacosConfigContextPath() {
assertEquals("NacosConfigProperties' context path is wrong", "test-contextpath",
properties.getContextPath());
}
private void checkoutNacosConfigName() {
assertEquals("NacosConfigProperties' name is wrong", "test-name",
properties.getName());
}
private void checkoutNacosConfigGroup() {
assertEquals("NacosConfigProperties' group is wrong", "test-group",
properties.getGroup());
}
private void checkoutNacosConfigFileExtension() {
assertEquals("NacosConfigProperties' file extension is wrong", "xml",
properties.getFileExtension());
}
private void checkoutNacosConfigTimeout() {
assertEquals("NacosConfigProperties' timeout is wrong", 1000,
properties.getTimeout());
}
private void checkoutNacosConfigEncode() {
assertEquals("NacosConfigProperties' encode is wrong", "utf-8",
properties.getEncode());
}
private void checkoutEndpoint() throws Exception {
NacosConfigEndpoint nacosConfigEndpoint = new NacosConfigEndpoint(properties,
refreshHistory);
Map<String, Object> map = nacosConfigEndpoint.invoke();
assertEquals(map.get("NacosConfigProperties"), properties);
assertEquals(map.get("RefreshHistory"), refreshHistory.getRecords());
}
@Configuration
@EnableAutoConfiguration
@ImportAutoConfiguration({ NacosConfigEndpointAutoConfiguration.class,
NacosConfigAutoConfiguration.class, NacosConfigBootstrapConfiguration.class })
public static class TestConfig {
}
}

View File

@ -22,6 +22,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.Map; import java.util.Map;
import com.alibaba.cloud.nacos.NacosConfigManager;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito; import org.powermock.api.mockito.PowerMockito;
@ -83,6 +84,9 @@ public class NacosConfigEndpointTests {
@Autowired @Autowired
private NacosConfigProperties properties; private NacosConfigProperties properties;
@Autowired
private NacosConfigManager nacosConfigManager;
@Autowired @Autowired
private NacosRefreshHistory refreshHistory; private NacosRefreshHistory refreshHistory;
@ -99,7 +103,7 @@ public class NacosConfigEndpointTests {
Builder builder = new Builder(); Builder builder = new Builder();
NacosConfigHealthIndicator healthIndicator = new NacosConfigHealthIndicator( NacosConfigHealthIndicator healthIndicator = new NacosConfigHealthIndicator(
properties.configServiceInstance()); nacosConfigManager.getConfigService());
healthIndicator.doHealthCheck(builder); healthIndicator.doHealthCheck(builder);
Builder builder1 = new Builder(); Builder builder1 = new Builder();

View File

@ -45,16 +45,23 @@ public class NacosDiscoveryAutoConfiguration {
@Bean @Bean
public NacosServiceRegistry nacosServiceRegistry( public NacosServiceRegistry nacosServiceRegistry(
NacosNamingManager nacosNamingManager,
NacosDiscoveryProperties nacosDiscoveryProperties) { NacosDiscoveryProperties nacosDiscoveryProperties) {
return new NacosServiceRegistry(nacosDiscoveryProperties); return new NacosServiceRegistry(nacosNamingManager, nacosDiscoveryProperties);
}
@Bean
public NacosNamingManager nacosNamingManager() {
return new NacosNamingManager();
} }
@Bean @Bean
@ConditionalOnBean(AutoServiceRegistrationProperties.class) @ConditionalOnBean(AutoServiceRegistrationProperties.class)
public NacosRegistration nacosRegistration( public NacosRegistration nacosRegistration(NacosNamingManager nacosNamingManager,
NacosDiscoveryProperties nacosDiscoveryProperties, NacosDiscoveryProperties nacosDiscoveryProperties,
ApplicationContext context) { ApplicationContext context) {
return new NacosRegistration(nacosDiscoveryProperties, context); return new NacosRegistration(nacosNamingManager, nacosDiscoveryProperties,
context);
} }
@Bean @Bean

View File

@ -427,7 +427,8 @@ public class NacosDiscoveryProperties {
public void overrideFromEnv(Environment env) { public void overrideFromEnv(Environment env) {
if (StringUtils.isEmpty(this.getServerAddr())) { if (StringUtils.isEmpty(this.getServerAddr())) {
String serverAddr = env.resolvePlaceholders("${spring.cloud.nacos.discovery.server-addr:}"); String serverAddr = env
.resolvePlaceholders("${spring.cloud.nacos.discovery.server-addr:}");
if (StringUtils.isEmpty(serverAddr)) { if (StringUtils.isEmpty(serverAddr)) {
serverAddr = env.resolvePlaceholders("${spring.cloud.nacos.server-addr}"); serverAddr = env.resolvePlaceholders("${spring.cloud.nacos.server-addr}");
} }
@ -463,6 +464,7 @@ public class NacosDiscoveryProperties {
} }
} }
@Deprecated
public NamingService namingServiceInstance() { public NamingService namingServiceInstance() {
if (null != namingService) { if (null != namingService) {
@ -479,6 +481,7 @@ public class NacosDiscoveryProperties {
return namingService; return namingService;
} }
@Deprecated
public NamingMaintainService namingMaintainServiceInstance() { public NamingMaintainService namingMaintainServiceInstance() {
if (null != namingMaintainService) { if (null != namingMaintainService) {

View File

@ -0,0 +1,49 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.cloud.nacos;
import com.alibaba.nacos.api.naming.NamingMaintainService;
import com.alibaba.nacos.api.naming.NamingService;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/**
* @author <a href="mailto:liaochunyhm@live.com">liaochuntao</a>
*/
public class NacosNamingManager implements ApplicationContextAware {
private NamingService namingService;
private NamingMaintainService namingMaintainService;
public NamingService getNamingService() {
return namingService;
}
public NamingMaintainService getNamingMaintainService() {
return namingMaintainService;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
NacosDiscoveryProperties properties = applicationContext
.getBean(NacosDiscoveryProperties.class);
namingService = properties.namingServiceInstance();
namingMaintainService = properties.namingMaintainServiceInstance();
}
}

View File

@ -17,6 +17,7 @@
package com.alibaba.cloud.nacos.discovery; package com.alibaba.cloud.nacos.discovery;
import com.alibaba.cloud.nacos.NacosDiscoveryProperties; import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.NacosNamingManager;
import com.alibaba.cloud.nacos.NacosServiceInstance; import com.alibaba.cloud.nacos.NacosServiceInstance;
import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.pojo.ListView; import com.alibaba.nacos.api.naming.pojo.ListView;
@ -40,9 +41,12 @@ public class NacosDiscoveryClient implements DiscoveryClient {
private static final Logger log = LoggerFactory.getLogger(NacosDiscoveryClient.class); private static final Logger log = LoggerFactory.getLogger(NacosDiscoveryClient.class);
public static final String DESCRIPTION = "Spring Cloud Nacos Discovery Client"; public static final String DESCRIPTION = "Spring Cloud Nacos Discovery Client";
private NacosNamingManager nacosNamingManager;
private NacosDiscoveryProperties discoveryProperties; private NacosDiscoveryProperties discoveryProperties;
public NacosDiscoveryClient(NacosDiscoveryProperties discoveryProperties) { public NacosDiscoveryClient(NacosNamingManager nacosNamingManager,
NacosDiscoveryProperties discoveryProperties) {
this.nacosNamingManager = nacosNamingManager;
this.discoveryProperties = discoveryProperties; this.discoveryProperties = discoveryProperties;
} }
@ -55,10 +59,11 @@ public class NacosDiscoveryClient implements DiscoveryClient {
public List<ServiceInstance> getInstances(String serviceId) { public List<ServiceInstance> getInstances(String serviceId) {
try { try {
String group = discoveryProperties.getGroup(); String group = discoveryProperties.getGroup();
List<Instance> instances = discoveryProperties.namingServiceInstance() List<Instance> instances = nacosNamingManager.getNamingService()
.selectInstances(serviceId, group, true); .selectInstances(serviceId, group, true);
return hostToServiceInstanceList(instances, serviceId); return hostToServiceInstanceList(instances, serviceId);
} catch (Exception e) { }
catch (Exception e) {
throw new RuntimeException( throw new RuntimeException(
"Can not get hosts from nacos server. serviceId: " + serviceId, e); "Can not get hosts from nacos server. serviceId: " + serviceId, e);
} }
@ -106,10 +111,11 @@ public class NacosDiscoveryClient implements DiscoveryClient {
try { try {
String group = discoveryProperties.getGroup(); String group = discoveryProperties.getGroup();
ListView<String> services = discoveryProperties.namingServiceInstance() ListView<String> services = nacosNamingManager.getNamingService()
.getServicesOfServer(1, Integer.MAX_VALUE, group); .getServicesOfServer(1, Integer.MAX_VALUE, group);
return services.getData(); return services.getData();
} catch (Exception e) { }
catch (Exception e) {
log.error("get service name from nacos server fail,", e); log.error("get service name from nacos server fail,", e);
return Collections.emptyList(); return Collections.emptyList();
} }

View File

@ -16,6 +16,7 @@
package com.alibaba.cloud.nacos.discovery; package com.alibaba.cloud.nacos.discovery;
import com.alibaba.cloud.nacos.NacosNamingManager;
import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
@ -44,9 +45,9 @@ public class NacosDiscoveryClientAutoConfiguration {
} }
@Bean @Bean
public DiscoveryClient nacosDiscoveryClient( public DiscoveryClient nacosDiscoveryClient(NacosNamingManager nacosNamingManager,
NacosDiscoveryProperties discoveryProperties) { NacosDiscoveryProperties discoveryProperties) {
return new NacosDiscoveryClient(discoveryProperties); return new NacosDiscoveryClient(nacosNamingManager, discoveryProperties);
} }
@Bean @Bean

View File

@ -21,6 +21,7 @@ import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import com.alibaba.cloud.nacos.NacosNamingManager;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint; import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
@ -40,9 +41,12 @@ public class NacosDiscoveryEndpoint {
private static final Logger log = LoggerFactory private static final Logger log = LoggerFactory
.getLogger(NacosDiscoveryEndpoint.class); .getLogger(NacosDiscoveryEndpoint.class);
private NacosNamingManager nacosNamingManager;
private NacosDiscoveryProperties nacosDiscoveryProperties; private NacosDiscoveryProperties nacosDiscoveryProperties;
public NacosDiscoveryEndpoint(NacosDiscoveryProperties nacosDiscoveryProperties) { public NacosDiscoveryEndpoint(NacosNamingManager nacosNamingManager,
NacosDiscoveryProperties nacosDiscoveryProperties) {
this.nacosNamingManager = nacosNamingManager;
this.nacosDiscoveryProperties = nacosDiscoveryProperties; this.nacosDiscoveryProperties = nacosDiscoveryProperties;
} }
@ -54,7 +58,7 @@ public class NacosDiscoveryEndpoint {
Map<String, Object> result = new HashMap<>(); Map<String, Object> result = new HashMap<>();
result.put("NacosDiscoveryProperties", nacosDiscoveryProperties); result.put("NacosDiscoveryProperties", nacosDiscoveryProperties);
NamingService namingService = nacosDiscoveryProperties.namingServiceInstance(); NamingService namingService = nacosNamingManager.getNamingService();
List<ServiceInfo> subscribe = Collections.emptyList(); List<ServiceInfo> subscribe = Collections.emptyList();
try { try {

View File

@ -16,6 +16,7 @@
package com.alibaba.cloud.nacos.endpoint; package com.alibaba.cloud.nacos.endpoint;
import com.alibaba.cloud.nacos.NacosNamingManager;
import org.springframework.boot.actuate.autoconfigure.endpoint.condition.ConditionalOnEnabledEndpoint; import org.springframework.boot.actuate.autoconfigure.endpoint.condition.ConditionalOnEnabledEndpoint;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint; import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
@ -38,8 +39,9 @@ public class NacosDiscoveryEndpointAutoConfiguration {
@ConditionalOnMissingBean @ConditionalOnMissingBean
@ConditionalOnEnabledEndpoint @ConditionalOnEnabledEndpoint
public NacosDiscoveryEndpoint nacosDiscoveryEndpoint( public NacosDiscoveryEndpoint nacosDiscoveryEndpoint(
NacosNamingManager nacosNamingManager,
NacosDiscoveryProperties nacosDiscoveryProperties) { NacosDiscoveryProperties nacosDiscoveryProperties) {
return new NacosDiscoveryEndpoint(nacosDiscoveryProperties); return new NacosDiscoveryEndpoint(nacosNamingManager, nacosDiscoveryProperties);
} }
} }

View File

@ -21,6 +21,7 @@ import java.util.Map;
import javax.annotation.PostConstruct; import javax.annotation.PostConstruct;
import com.alibaba.cloud.nacos.NacosNamingManager;
import org.springframework.cloud.client.DefaultServiceInstance; import org.springframework.cloud.client.DefaultServiceInstance;
import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.ManagementServerPortUtils; import org.springframework.cloud.client.discovery.ManagementServerPortUtils;
@ -43,12 +44,15 @@ public class NacosRegistration implements Registration, ServiceInstance {
public static final String MANAGEMENT_ADDRESS = "management.address"; public static final String MANAGEMENT_ADDRESS = "management.address";
public static final String MANAGEMENT_ENDPOINT_BASE_PATH = "management.endpoints.web.base-path"; public static final String MANAGEMENT_ENDPOINT_BASE_PATH = "management.endpoints.web.base-path";
private NacosNamingManager nacosNamingManager;
private NacosDiscoveryProperties nacosDiscoveryProperties; private NacosDiscoveryProperties nacosDiscoveryProperties;
private ApplicationContext context; private ApplicationContext context;
public NacosRegistration(NacosDiscoveryProperties nacosDiscoveryProperties, public NacosRegistration(NacosNamingManager nacosNamingManager,
NacosDiscoveryProperties nacosDiscoveryProperties,
ApplicationContext context) { ApplicationContext context) {
this.nacosNamingManager = nacosNamingManager;
this.nacosDiscoveryProperties = nacosDiscoveryProperties; this.nacosDiscoveryProperties = nacosDiscoveryProperties;
this.context = context; this.context = context;
} }
@ -143,7 +147,7 @@ public class NacosRegistration implements Registration, ServiceInstance {
} }
public NamingService getNacosNamingService() { public NamingService getNacosNamingService() {
return nacosDiscoveryProperties.namingServiceInstance(); return nacosNamingManager.getNamingService();
} }
@Override @Override

View File

@ -18,6 +18,7 @@ package com.alibaba.cloud.nacos.registry;
import java.util.List; import java.util.List;
import com.alibaba.cloud.nacos.NacosNamingManager;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.cloud.client.serviceregistry.Registration; import org.springframework.cloud.client.serviceregistry.Registration;
@ -36,13 +37,16 @@ public class NacosServiceRegistry implements ServiceRegistry<Registration> {
private static final Logger log = LoggerFactory.getLogger(NacosServiceRegistry.class); private static final Logger log = LoggerFactory.getLogger(NacosServiceRegistry.class);
private final NacosNamingManager nacosNamingManager;
private final NacosDiscoveryProperties nacosDiscoveryProperties; private final NacosDiscoveryProperties nacosDiscoveryProperties;
private final NamingService namingService; private final NamingService namingService;
public NacosServiceRegistry(NacosDiscoveryProperties nacosDiscoveryProperties) { public NacosServiceRegistry(NacosNamingManager nacosNamingManager,
NacosDiscoveryProperties nacosDiscoveryProperties) {
this.nacosNamingManager = nacosNamingManager;
this.nacosDiscoveryProperties = nacosDiscoveryProperties; this.nacosDiscoveryProperties = nacosDiscoveryProperties;
this.namingService = nacosDiscoveryProperties.namingServiceInstance(); this.namingService = nacosNamingManager.getNamingService();
} }
@Override @Override
@ -79,7 +83,7 @@ public class NacosServiceRegistry implements ServiceRegistry<Registration> {
return; return;
} }
NamingService namingService = nacosDiscoveryProperties.namingServiceInstance(); NamingService namingService = nacosNamingManager.getNamingService();
String serviceId = registration.getServiceId(); String serviceId = registration.getServiceId();
String group = nacosDiscoveryProperties.getGroup(); String group = nacosDiscoveryProperties.getGroup();
@ -120,8 +124,8 @@ public class NacosServiceRegistry implements ServiceRegistry<Registration> {
} }
try { try {
nacosDiscoveryProperties.namingMaintainServiceInstance() nacosNamingManager.getNamingMaintainService().updateInstance(serviceId,
.updateInstance(serviceId, instance); instance);
} }
catch (Exception e) { catch (Exception e) {
throw new RuntimeException("update nacos instance status fail", e); throw new RuntimeException("update nacos instance status fail", e);
@ -134,7 +138,7 @@ public class NacosServiceRegistry implements ServiceRegistry<Registration> {
String serviceName = registration.getServiceId(); String serviceName = registration.getServiceId();
try { try {
List<Instance> instances = nacosDiscoveryProperties.namingServiceInstance() List<Instance> instances = nacosNamingManager.getNamingService()
.getAllInstances(serviceName); .getAllInstances(serviceName);
for (Instance instance : instances) { for (Instance instance : instances) {
if (instance.getIp().equalsIgnoreCase(nacosDiscoveryProperties.getIp()) if (instance.getIp().equalsIgnoreCase(nacosDiscoveryProperties.getIp())

View File

@ -16,6 +16,7 @@
package com.alibaba.cloud.nacos.ribbon; package com.alibaba.cloud.nacos.ribbon;
import com.alibaba.cloud.nacos.NacosNamingManager;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
@ -36,8 +37,10 @@ public class NacosRibbonClientConfiguration {
@Bean @Bean
@ConditionalOnMissingBean @ConditionalOnMissingBean
public ServerList<?> ribbonServerList(IClientConfig config, public ServerList<?> ribbonServerList(IClientConfig config,
NacosNamingManager nacosNamingManager,
NacosDiscoveryProperties nacosDiscoveryProperties) { NacosDiscoveryProperties nacosDiscoveryProperties) {
NacosServerList serverList = new NacosServerList(nacosDiscoveryProperties); NacosServerList serverList = new NacosServerList(nacosNamingManager,
nacosDiscoveryProperties);
serverList.initWithNiwsConfig(config); serverList.initWithNiwsConfig(config);
return serverList; return serverList;
} }

View File

@ -4,6 +4,7 @@ import java.util.List;
import java.util.Objects; import java.util.Objects;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import com.alibaba.cloud.nacos.NacosNamingManager;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -31,6 +32,9 @@ public class NacosRule extends AbstractLoadBalancerRule {
@Autowired @Autowired
private NacosDiscoveryProperties nacosDiscoveryProperties; private NacosDiscoveryProperties nacosDiscoveryProperties;
@Autowired
private NacosNamingManager nacosNamingManager;
@Override @Override
public Server choose(Object key) { public Server choose(Object key) {
try { try {
@ -38,8 +42,7 @@ public class NacosRule extends AbstractLoadBalancerRule {
DynamicServerListLoadBalancer loadBalancer = (DynamicServerListLoadBalancer) getLoadBalancer(); DynamicServerListLoadBalancer loadBalancer = (DynamicServerListLoadBalancer) getLoadBalancer();
String name = loadBalancer.getName(); String name = loadBalancer.getName();
NamingService namingService = this.nacosDiscoveryProperties NamingService namingService = this.nacosNamingManager.getNamingService();
.namingServiceInstance();
List<Instance> instances = namingService.selectInstances(name, true); List<Instance> instances = namingService.selectInstances(name, true);
if (CollectionUtils.isEmpty(instances)) { if (CollectionUtils.isEmpty(instances)) {
LOGGER.warn("no instance in service {}", name); LOGGER.warn("no instance in service {}", name);

View File

@ -20,6 +20,7 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import com.alibaba.cloud.nacos.NacosDiscoveryProperties; import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.NacosNamingManager;
import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.client.naming.utils.CollectionUtils; import com.alibaba.nacos.client.naming.utils.CollectionUtils;
@ -32,11 +33,14 @@ import com.netflix.loadbalancer.AbstractServerList;
*/ */
public class NacosServerList extends AbstractServerList<NacosServer> { public class NacosServerList extends AbstractServerList<NacosServer> {
private NacosNamingManager nacosNamingManager;
private NacosDiscoveryProperties discoveryProperties; private NacosDiscoveryProperties discoveryProperties;
private String serviceId; private String serviceId;
public NacosServerList(NacosDiscoveryProperties discoveryProperties) { public NacosServerList(NacosNamingManager nacosNamingManager,
NacosDiscoveryProperties discoveryProperties) {
this.nacosNamingManager = nacosNamingManager;
this.discoveryProperties = discoveryProperties; this.discoveryProperties = discoveryProperties;
} }
@ -53,8 +57,8 @@ public class NacosServerList extends AbstractServerList<NacosServer> {
private List<NacosServer> getServers() { private List<NacosServer> getServers() {
try { try {
String group = discoveryProperties.getGroup(); String group = discoveryProperties.getGroup();
List<Instance> instances = discoveryProperties.namingServiceInstance() List<Instance> instances = nacosNamingManager.getNamingService()
.selectInstances(serviceId, group,true); .selectInstances(serviceId, group, true);
return instancesToServerList(instances); return instancesToServerList(instances);
} }
catch (Exception e) { catch (Exception e) {

View File

@ -56,16 +56,17 @@ public class NacosDiscoveryClientTests {
NacosDiscoveryProperties nacosDiscoveryProperties = mock( NacosDiscoveryProperties nacosDiscoveryProperties = mock(
NacosDiscoveryProperties.class); NacosDiscoveryProperties.class);
NacosNamingManager nacosNamingManager = mock(NacosNamingManager.class);
NamingService namingService = mock(NamingService.class); NamingService namingService = mock(NamingService.class);
when(nacosDiscoveryProperties.namingServiceInstance()).thenReturn(namingService); when(nacosNamingManager.getNamingService()).thenReturn(namingService);
when(nacosDiscoveryProperties.getGroup()).thenReturn("DEFAULT"); when(nacosDiscoveryProperties.getGroup()).thenReturn("DEFAULT");
when(namingService.selectInstances(eq(serviceName),eq("DEFAULT"), eq(true))) when(namingService.selectInstances(eq(serviceName), eq("DEFAULT"), eq(true)))
.thenReturn(instances); .thenReturn(instances);
NacosDiscoveryClient discoveryClient = new NacosDiscoveryClient( NacosDiscoveryClient discoveryClient = new NacosDiscoveryClient(
nacosDiscoveryProperties); nacosNamingManager, nacosDiscoveryProperties);
List<ServiceInstance> serviceInstances = discoveryClient List<ServiceInstance> serviceInstances = discoveryClient
.getInstances(serviceName); .getInstances(serviceName);
@ -97,16 +98,17 @@ public class NacosDiscoveryClientTests {
NacosDiscoveryProperties nacosDiscoveryProperties = mock( NacosDiscoveryProperties nacosDiscoveryProperties = mock(
NacosDiscoveryProperties.class); NacosDiscoveryProperties.class);
NacosNamingManager nacosNamingManager = mock(NacosNamingManager.class);
NamingService namingService = mock(NamingService.class); NamingService namingService = mock(NamingService.class);
NacosDiscoveryClient discoveryClient = new NacosDiscoveryClient( NacosDiscoveryClient discoveryClient = new NacosDiscoveryClient(
nacosDiscoveryProperties); nacosNamingManager, nacosDiscoveryProperties);
when(nacosDiscoveryProperties.namingServiceInstance()).thenReturn(namingService); when(nacosNamingManager.getNamingService()).thenReturn(namingService);
when(nacosDiscoveryProperties.getGroup()).thenReturn("DEFAULT"); when(nacosDiscoveryProperties.getGroup()).thenReturn("DEFAULT");
when(namingService.getServicesOfServer(eq(1), eq(Integer.MAX_VALUE),eq("DEFAULT"))) when(namingService.getServicesOfServer(eq(1), eq(Integer.MAX_VALUE),
.thenReturn(nacosServices); eq("DEFAULT"))).thenReturn(nacosServices);
List<String> services = discoveryClient.getServices(); List<String> services = discoveryClient.getServices();

View File

@ -23,8 +23,7 @@ import com.alibaba.cloud.nacos.discovery.NacosDiscoveryClientAutoConfiguration;
@RunWith(SpringRunner.class) @RunWith(SpringRunner.class)
@SpringBootTest(classes = NacosDiscoveryPropertiesServerAddressBothLevelTests.TestConfig.class, properties = { @SpringBootTest(classes = NacosDiscoveryPropertiesServerAddressBothLevelTests.TestConfig.class, properties = {
"spring.cloud.nacos.discovery.server-addr=321.321.321.321:8848", "spring.cloud.nacos.discovery.server-addr=321.321.321.321:8848",
"spring.cloud.nacos.server-addr=123.123.123.123:8848" "spring.cloud.nacos.server-addr=123.123.123.123:8848" }, webEnvironment = RANDOM_PORT)
}, webEnvironment = RANDOM_PORT)
public class NacosDiscoveryPropertiesServerAddressBothLevelTests { public class NacosDiscoveryPropertiesServerAddressBothLevelTests {
@Autowired @Autowired
@ -32,7 +31,8 @@ public class NacosDiscoveryPropertiesServerAddressBothLevelTests {
@Test @Test
public void testGetServerAddr() { public void testGetServerAddr() {
assertEquals("NacosDiscoveryProperties server address was wrong","321.321.321.321:8848", properties.getServerAddr()); assertEquals("NacosDiscoveryProperties server address was wrong",
"321.321.321.321:8848", properties.getServerAddr());
} }
@Configuration @Configuration

View File

@ -24,8 +24,7 @@ import com.alibaba.cloud.nacos.discovery.NacosDiscoveryClientAutoConfiguration;
*/ */
@RunWith(SpringRunner.class) @RunWith(SpringRunner.class)
@SpringBootTest(classes = NacosDiscoveryPropertiesServerAddressTopLevelTests.TestConfig.class, properties = { @SpringBootTest(classes = NacosDiscoveryPropertiesServerAddressTopLevelTests.TestConfig.class, properties = {
"spring.cloud.nacos.server-addr=123.123.123.123:8848" "spring.cloud.nacos.server-addr=123.123.123.123:8848" }, webEnvironment = RANDOM_PORT)
}, webEnvironment = RANDOM_PORT)
public class NacosDiscoveryPropertiesServerAddressTopLevelTests { public class NacosDiscoveryPropertiesServerAddressTopLevelTests {
@ -34,7 +33,8 @@ public class NacosDiscoveryPropertiesServerAddressTopLevelTests {
@Test @Test
public void testGetServerAddr() { public void testGetServerAddr() {
assertEquals("NacosDiscoveryProperties server address was wrong","123.123.123.123:8848", properties.getServerAddr()); assertEquals("NacosDiscoveryProperties server address was wrong",
"123.123.123.123:8848", properties.getServerAddr());
} }
@Configuration @Configuration

View File

@ -23,6 +23,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
import java.util.Map; import java.util.Map;
import com.alibaba.cloud.nacos.NacosNamingManager;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -74,6 +75,9 @@ public class NacosAutoServiceRegistrationTests {
@Autowired @Autowired
private NacosDiscoveryProperties properties; private NacosDiscoveryProperties properties;
@Autowired
private NacosNamingManager nacosNamingManager;
@Autowired @Autowired
private InetUtils inetUtils; private InetUtils inetUtils;
@ -204,11 +208,11 @@ public class NacosAutoServiceRegistrationTests {
private void checkoutEndpoint() throws Exception { private void checkoutEndpoint() throws Exception {
NacosDiscoveryEndpoint nacosDiscoveryEndpoint = new NacosDiscoveryEndpoint( NacosDiscoveryEndpoint nacosDiscoveryEndpoint = new NacosDiscoveryEndpoint(
properties); nacosNamingManager, properties);
Map<String, Object> map = nacosDiscoveryEndpoint.nacosDiscovery(); Map<String, Object> map = nacosDiscoveryEndpoint.nacosDiscovery();
assertEquals(map.get("NacosDiscoveryProperties"), properties); assertEquals(map.get("NacosDiscoveryProperties"), properties);
assertEquals(map.get("subscribe").toString(), assertEquals(map.get("subscribe").toString(),
properties.namingServiceInstance().getSubscribeServices().toString()); nacosNamingManager.getNamingService().getSubscribeServices().toString());
} }
@Configuration @Configuration

View File

@ -28,6 +28,7 @@ import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import com.alibaba.cloud.nacos.NacosNamingManager;
import org.junit.Test; import org.junit.Test;
import com.alibaba.cloud.nacos.NacosDiscoveryProperties; import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
@ -48,14 +49,16 @@ public class NacosServerListTests {
public void testEmptyInstancesReturnsEmptyList() throws Exception { public void testEmptyInstancesReturnsEmptyList() throws Exception {
NacosDiscoveryProperties nacosDiscoveryProperties = mock( NacosDiscoveryProperties nacosDiscoveryProperties = mock(
NacosDiscoveryProperties.class); NacosDiscoveryProperties.class);
NacosNamingManager nacosNamingManager = mock(NacosNamingManager.class);
NamingService namingService = mock(NamingService.class); NamingService namingService = mock(NamingService.class);
when(nacosDiscoveryProperties.namingServiceInstance()).thenReturn(namingService); when(nacosNamingManager.getNamingService()).thenReturn(namingService);
when(namingService.selectInstances(anyString(), eq("DEFAULT"), eq(true))) when(namingService.selectInstances(anyString(), eq("DEFAULT"), eq(true)))
.thenReturn(null); .thenReturn(null);
NacosServerList serverList = new NacosServerList(nacosDiscoveryProperties); NacosServerList serverList = new NacosServerList(nacosNamingManager,
nacosDiscoveryProperties);
List<NacosServer> servers = serverList.getInitialListOfServers(); List<NacosServer> servers = serverList.getInitialListOfServers();
assertThat(servers).isEmpty(); assertThat(servers).isEmpty();
} }
@ -70,10 +73,11 @@ public class NacosServerListTests {
NacosDiscoveryProperties nacosDiscoveryProperties = mock( NacosDiscoveryProperties nacosDiscoveryProperties = mock(
NacosDiscoveryProperties.class); NacosDiscoveryProperties.class);
NacosNamingManager nacosNamingManager = mock(NacosNamingManager.class);
NamingService namingService = mock(NamingService.class); NamingService namingService = mock(NamingService.class);
when(nacosDiscoveryProperties.namingServiceInstance()).thenReturn(namingService); when(nacosNamingManager.getNamingService()).thenReturn(namingService);
when(nacosDiscoveryProperties.getGroup()).thenReturn("DEFAULT"); when(nacosDiscoveryProperties.getGroup()).thenReturn("DEFAULT");
when(nacosDiscoveryProperties.getGroup()).thenReturn("DEFAULT"); when(nacosDiscoveryProperties.getGroup()).thenReturn("DEFAULT");
when(namingService.selectInstances(eq("test-service"), eq("DEFAULT"), eq(true))) when(namingService.selectInstances(eq("test-service"), eq("DEFAULT"), eq(true)))
@ -81,7 +85,8 @@ public class NacosServerListTests {
IClientConfig clientConfig = mock(IClientConfig.class); IClientConfig clientConfig = mock(IClientConfig.class);
when(clientConfig.getClientName()).thenReturn("test-service"); when(clientConfig.getClientName()).thenReturn("test-service");
NacosServerList serverList = new NacosServerList(nacosDiscoveryProperties); NacosServerList serverList = new NacosServerList(nacosNamingManager,
nacosDiscoveryProperties);
serverList.initWithNiwsConfig(clientConfig); serverList.initWithNiwsConfig(clientConfig);
List<NacosServer> servers = serverList.getInitialListOfServers(); List<NacosServer> servers = serverList.getInitialListOfServers();
assertThat(servers).hasSize(1); assertThat(servers).hasSize(1);
@ -104,10 +109,11 @@ public class NacosServerListTests {
NacosDiscoveryProperties nacosDiscoveryProperties = mock( NacosDiscoveryProperties nacosDiscoveryProperties = mock(
NacosDiscoveryProperties.class); NacosDiscoveryProperties.class);
NacosNamingManager nacosNamingManager = mock(NacosNamingManager.class);
NamingService namingService = mock(NamingService.class); NamingService namingService = mock(NamingService.class);
when(nacosDiscoveryProperties.namingServiceInstance()).thenReturn(namingService); when(nacosNamingManager.getNamingService()).thenReturn(namingService);
when(nacosDiscoveryProperties.getGroup()).thenReturn("DEFAULT"); when(nacosDiscoveryProperties.getGroup()).thenReturn("DEFAULT");
when(namingService.selectInstances(eq("test-service"), eq("DEFAULT"), eq(true))) when(namingService.selectInstances(eq("test-service"), eq("DEFAULT"), eq(true)))
.thenReturn(instances.stream().filter(Instance::isHealthy) .thenReturn(instances.stream().filter(Instance::isHealthy)
@ -115,7 +121,8 @@ public class NacosServerListTests {
IClientConfig clientConfig = mock(IClientConfig.class); IClientConfig clientConfig = mock(IClientConfig.class);
when(clientConfig.getClientName()).thenReturn("test-service"); when(clientConfig.getClientName()).thenReturn("test-service");
NacosServerList serverList = new NacosServerList(nacosDiscoveryProperties); NacosServerList serverList = new NacosServerList(nacosNamingManager,
nacosDiscoveryProperties);
serverList.initWithNiwsConfig(clientConfig); serverList.initWithNiwsConfig(clientConfig);
List<NacosServer> servers = serverList.getInitialListOfServers(); List<NacosServer> servers = serverList.getInitialListOfServers();
assertThat(servers).hasSize(1); assertThat(servers).hasSize(1);
@ -142,10 +149,11 @@ public class NacosServerListTests {
NacosDiscoveryProperties nacosDiscoveryProperties = mock( NacosDiscoveryProperties nacosDiscoveryProperties = mock(
NacosDiscoveryProperties.class); NacosDiscoveryProperties.class);
NacosNamingManager nacosNamingManager = mock(NacosNamingManager.class);
NamingService namingService = mock(NamingService.class); NamingService namingService = mock(NamingService.class);
when(nacosDiscoveryProperties.namingServiceInstance()).thenReturn(namingService); when(nacosNamingManager.getNamingService()).thenReturn(namingService);
when(nacosDiscoveryProperties.getGroup()).thenReturn("DEFAULT"); when(nacosDiscoveryProperties.getGroup()).thenReturn("DEFAULT");
when(namingService.selectInstances(eq("test-service"), eq("DEFAULT"), eq(true))) when(namingService.selectInstances(eq("test-service"), eq("DEFAULT"), eq(true)))
.thenReturn(instances.stream().filter(Instance::isHealthy) .thenReturn(instances.stream().filter(Instance::isHealthy)
@ -153,7 +161,8 @@ public class NacosServerListTests {
IClientConfig clientConfig = mock(IClientConfig.class); IClientConfig clientConfig = mock(IClientConfig.class);
when(clientConfig.getClientName()).thenReturn("test-service"); when(clientConfig.getClientName()).thenReturn("test-service");
NacosServerList serverList = new NacosServerList(nacosDiscoveryProperties); NacosServerList serverList = new NacosServerList(nacosNamingManager,
nacosDiscoveryProperties);
serverList.initWithNiwsConfig(clientConfig); serverList.initWithNiwsConfig(clientConfig);
List<NacosServer> servers = serverList.getUpdatedListOfServers(); List<NacosServer> servers = serverList.getUpdatedListOfServers();