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:
commit
9344473e51
@ -33,6 +33,7 @@ import java.util.concurrent.atomic.AtomicReference;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import com.alibaba.cloud.nacos.NacosNamingManager;
|
||||
import org.apache.curator.framework.CuratorFramework;
|
||||
import org.apache.curator.framework.listen.Listenable;
|
||||
import org.apache.curator.framework.listen.ListenerContainer;
|
||||
@ -504,8 +505,8 @@ public class DubboServiceDiscoveryAutoConfiguration {
|
||||
*/
|
||||
private final Set<String> listeningServices;
|
||||
|
||||
NacosConfiguration(NacosDiscoveryProperties nacosDiscoveryProperties) {
|
||||
this.namingService = nacosDiscoveryProperties.namingServiceInstance();
|
||||
NacosConfiguration(NacosNamingManager nacosNamingManager) {
|
||||
this.namingService = nacosNamingManager.getNamingService();
|
||||
this.listeningServices = new ConcurrentSkipListSet<>();
|
||||
}
|
||||
|
||||
|
@ -5,6 +5,7 @@ import java.io.StringReader;
|
||||
import java.util.Properties;
|
||||
import java.util.concurrent.Executor;
|
||||
|
||||
import com.alibaba.cloud.nacos.NacosConfigManager;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.boot.ApplicationArguments;
|
||||
@ -24,7 +25,6 @@ import com.alibaba.nacos.api.config.listener.Listener;
|
||||
*/
|
||||
@SpringBootApplication
|
||||
public class Application {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(Application.class, args);
|
||||
}
|
||||
@ -40,14 +40,14 @@ class SampleRunner implements ApplicationRunner {
|
||||
int userAge;
|
||||
|
||||
@Autowired
|
||||
private NacosConfigProperties nacosConfigProperties;
|
||||
private NacosConfigManager nacosConfigManager;
|
||||
|
||||
@Override
|
||||
public void run(ApplicationArguments args) throws Exception {
|
||||
System.out.println(
|
||||
String.format("Initial username=%s, userAge=%d", userName, userAge));
|
||||
|
||||
nacosConfigProperties.configServiceInstance().addListener(
|
||||
nacosConfigManager.getConfigService().addListener(
|
||||
"nacos-config-example.properties", "DEFAULT_GROUP", new Listener() {
|
||||
|
||||
/**
|
||||
@ -58,7 +58,7 @@ class SampleRunner implements ApplicationRunner {
|
||||
* user.name=Nacos user.age=25
|
||||
*
|
||||
* @param configInfo latest config data for specific dataId in Nacos
|
||||
* server
|
||||
* server
|
||||
*/
|
||||
@Override
|
||||
public void receiveConfigInfo(String configInfo) {
|
||||
|
@ -48,8 +48,8 @@ public class ConsumerApplication {
|
||||
String divide(@RequestParam("a") Integer a, @RequestParam("b") Integer b);
|
||||
|
||||
default String divide(Integer a) {
|
||||
return divide(a, 0);
|
||||
}
|
||||
return divide(a, 0);
|
||||
}
|
||||
|
||||
@GetMapping(value = "/notFound")
|
||||
String notFound();
|
||||
|
@ -71,10 +71,10 @@ public class TestController {
|
||||
return echoService.divide(a, b);
|
||||
}
|
||||
|
||||
@GetMapping(value = "/divide-feign2")
|
||||
public String divide(@RequestParam Integer a) {
|
||||
return echoService.divide(a);
|
||||
}
|
||||
@GetMapping(value = "/divide-feign2")
|
||||
public String divide(@RequestParam Integer a) {
|
||||
return echoService.divide(a);
|
||||
}
|
||||
|
||||
@GetMapping(value = "/echo-feign/{str}")
|
||||
public String feign(@PathVariable String str) {
|
||||
|
@ -1,12 +1,12 @@
|
||||
package com.alibaba.cloud.examples;
|
||||
|
||||
public class UrlCleaner {
|
||||
public static String clean(String url) {
|
||||
System.out.println("enter urlCleaner");
|
||||
if (url.matches(".*/echo/.*")) {
|
||||
System.out.println("change url");
|
||||
url = url.replaceAll("/echo/.*", "/echo/{str}");
|
||||
}
|
||||
return url;
|
||||
}
|
||||
public static String clean(String url) {
|
||||
System.out.println("enter urlCleaner");
|
||||
if (url.matches(".*/echo/.*")) {
|
||||
System.out.println("change url");
|
||||
url = url.replaceAll("/echo/.*", "/echo/{str}");
|
||||
}
|
||||
return url;
|
||||
}
|
||||
}
|
||||
|
@ -44,6 +44,11 @@ public class NacosConfigAutoConfiguration {
|
||||
return new NacosConfigProperties();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public NacosConfigManager nacosConfigManager() {
|
||||
return new NacosConfigManager();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public NacosRefreshProperties nacosRefreshProperties() {
|
||||
return new NacosRefreshProperties();
|
||||
@ -56,10 +61,10 @@ public class NacosConfigAutoConfiguration {
|
||||
|
||||
@Bean
|
||||
public NacosContextRefresher nacosContextRefresher(
|
||||
NacosConfigProperties nacosConfigProperties,
|
||||
NacosConfigManager nacosConfigManager,
|
||||
NacosRefreshProperties nacosRefreshProperties,
|
||||
NacosRefreshHistory refreshHistory) {
|
||||
return new NacosContextRefresher(nacosRefreshProperties, refreshHistory,
|
||||
nacosConfigProperties.configServiceInstance());
|
||||
nacosConfigManager.getConfigService());
|
||||
}
|
||||
}
|
||||
|
@ -36,10 +36,17 @@ public class NacosConfigBootstrapConfiguration {
|
||||
return new NacosConfigProperties();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public NacosConfigManager nacosConfigManager() {
|
||||
return new NacosConfigManager();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public NacosPropertySourceLocator nacosPropertySourceLocator(
|
||||
NacosConfigManager nacosConfigManager,
|
||||
NacosConfigProperties nacosConfigProperties) {
|
||||
return new NacosPropertySourceLocator(nacosConfigProperties);
|
||||
return new NacosPropertySourceLocator(nacosConfigManager, nacosConfigProperties);
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -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();
|
||||
}
|
||||
}
|
@ -64,17 +64,19 @@ public class NacosConfigProperties {
|
||||
|
||||
@Autowired
|
||||
private Environment environment;
|
||||
|
||||
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
this.overrideFromEnv();
|
||||
}
|
||||
|
||||
|
||||
private void overrideFromEnv() {
|
||||
if (StringUtils.isEmpty(this.getServerAddr())) {
|
||||
String serverAddr = environment.resolvePlaceholders("${spring.cloud.nacos.config.server-addr:}");
|
||||
if(StringUtils.isEmpty(serverAddr)) {
|
||||
serverAddr = environment.resolvePlaceholders("${spring.cloud.nacos.server-addr}");
|
||||
String serverAddr = environment
|
||||
.resolvePlaceholders("${spring.cloud.nacos.config.server-addr:}");
|
||||
if (StringUtils.isEmpty(serverAddr)) {
|
||||
serverAddr = environment
|
||||
.resolvePlaceholders("${spring.cloud.nacos.server-addr}");
|
||||
}
|
||||
this.setServerAddr(serverAddr);
|
||||
}
|
||||
@ -110,25 +112,26 @@ public class NacosConfigProperties {
|
||||
private int timeout = 3000;
|
||||
|
||||
/**
|
||||
* nacos maximum number of tolerable server reconnection errors.
|
||||
*/
|
||||
* nacos maximum number of tolerable server reconnection errors.
|
||||
*/
|
||||
private String maxRetry;
|
||||
|
||||
/**
|
||||
* nacos get config long poll timeout.
|
||||
*/
|
||||
* nacos get config long poll timeout.
|
||||
*/
|
||||
private String configLongPollTimeout;
|
||||
|
||||
/**
|
||||
* nacos get config failure retry time.
|
||||
*/
|
||||
* nacos get config failure retry time.
|
||||
*/
|
||||
private String configRetryTime;
|
||||
|
||||
/**
|
||||
* 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 {@link ConfigService#getConfigAndSignListener} directly.
|
||||
* 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 {@link ConfigService#getConfigAndSignListener} directly.
|
||||
*/
|
||||
private boolean enableRemoteSyncConfig = false;
|
||||
|
||||
@ -163,9 +166,9 @@ public class NacosConfigProperties {
|
||||
*/
|
||||
private String clusterName;
|
||||
|
||||
/**
|
||||
* nacos config dataId name.
|
||||
*/
|
||||
/**
|
||||
* nacos config dataId name.
|
||||
*/
|
||||
private String name;
|
||||
|
||||
/**
|
||||
@ -233,27 +236,27 @@ public class NacosConfigProperties {
|
||||
}
|
||||
|
||||
public void setMaxRetry(String maxRetry) {
|
||||
this.maxRetry = maxRetry;
|
||||
this.maxRetry = maxRetry;
|
||||
}
|
||||
|
||||
public String getConfigLongPollTimeout() {
|
||||
return configLongPollTimeout;
|
||||
return configLongPollTimeout;
|
||||
}
|
||||
|
||||
public void setConfigLongPollTimeout(String configLongPollTimeout) {
|
||||
this.configLongPollTimeout = configLongPollTimeout;
|
||||
this.configLongPollTimeout = configLongPollTimeout;
|
||||
}
|
||||
|
||||
public String getConfigRetryTime() {
|
||||
return configRetryTime;
|
||||
return configRetryTime;
|
||||
}
|
||||
|
||||
public void setConfigRetryTime(String configRetryTime) {
|
||||
this.configRetryTime = configRetryTime;
|
||||
this.configRetryTime = configRetryTime;
|
||||
}
|
||||
|
||||
public Boolean getEnableRemoteSyncConfig() {
|
||||
return enableRemoteSyncConfig;
|
||||
return enableRemoteSyncConfig;
|
||||
}
|
||||
|
||||
public void setEnableRemoteSyncConfig(Boolean enableRemoteSyncConfig) {
|
||||
@ -400,6 +403,7 @@ public class NacosConfigProperties {
|
||||
+ refreshableDataids + '\'' + ", extConfig=" + extConfig + '}';
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public ConfigService configServiceInstance() {
|
||||
|
||||
if (null != configService) {
|
||||
@ -415,9 +419,11 @@ public class NacosConfigProperties {
|
||||
properties.put(CONTEXT_PATH, Objects.toString(this.contextPath, ""));
|
||||
properties.put(CLUSTER_NAME, Objects.toString(this.clusterName, ""));
|
||||
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(ENABLE_REMOTE_SYNC_CONFIG, Objects.toString(this.enableRemoteSyncConfig, ""));
|
||||
properties.put(ENABLE_REMOTE_SYNC_CONFIG,
|
||||
Objects.toString(this.enableRemoteSyncConfig, ""));
|
||||
|
||||
String endpoint = Objects.toString(this.endpoint, "");
|
||||
if (endpoint.contains(":")) {
|
||||
|
@ -16,7 +16,6 @@
|
||||
|
||||
package com.alibaba.cloud.nacos.client;
|
||||
|
||||
import java.io.StringReader;
|
||||
import java.util.Date;
|
||||
import java.util.Enumeration;
|
||||
import java.util.HashMap;
|
||||
@ -25,11 +24,10 @@ import java.util.Properties;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
|
||||
import org.springframework.core.io.ByteArrayResource;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
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.exception.NacosException;
|
||||
|
||||
@ -84,24 +82,18 @@ public class NacosPropertySourceBuilder {
|
||||
try {
|
||||
data = configService.getConfig(dataId, group, timeout);
|
||||
if (StringUtils.isEmpty(data)) {
|
||||
log.warn(
|
||||
"Ignore the empty nacos configuration and get it based on dataId[{}] & group[{}]",
|
||||
dataId, group);
|
||||
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'",
|
||||
dataId, group));
|
||||
|
||||
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();
|
||||
}
|
||||
Properties properties = NacosDataParserHandler.getInstance()
|
||||
.parseNacosData(data, fileExtension);
|
||||
return properties == null ? EMPTY_PROPERTIES : properties;
|
||||
}
|
||||
catch (NacosException e) {
|
||||
log.error("get data from Nacos error,dataId:{}, ", dataId, e);
|
||||
|
@ -16,9 +16,9 @@
|
||||
|
||||
package com.alibaba.cloud.nacos.client;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import com.alibaba.cloud.nacos.NacosConfigManager;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
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.NacosPropertySourceRepository;
|
||||
import com.alibaba.cloud.nacos.parser.NacosDataParserHandler;
|
||||
import com.alibaba.cloud.nacos.refresh.NacosContextRefresher;
|
||||
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 DOT = ".";
|
||||
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 NacosConfigProperties nacosConfigProperties;
|
||||
|
||||
public NacosPropertySourceLocator(NacosConfigProperties nacosConfigProperties) {
|
||||
private NacosConfigManager nacosConfigManager;
|
||||
|
||||
public NacosPropertySourceLocator(NacosConfigManager nacosConfigManager,
|
||||
NacosConfigProperties nacosConfigProperties) {
|
||||
this.nacosConfigManager = nacosConfigManager;
|
||||
this.nacosConfigProperties = nacosConfigProperties;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PropertySource<?> locate(Environment env) {
|
||||
|
||||
ConfigService configService = nacosConfigProperties.configServiceInstance();
|
||||
ConfigService configService = nacosConfigManager.getConfigService();
|
||||
|
||||
if (null == configService) {
|
||||
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) {
|
||||
String dataId = config.getDataId();
|
||||
String fileExtension = dataId.substring(dataId.lastIndexOf(".") + 1);
|
||||
String fileExtension = dataId.substring(dataId.lastIndexOf(DOT) + 1);
|
||||
loadNacosDataIfPresent(compositePropertySource, dataId, config.getGroup(),
|
||||
fileExtension, config.isRefresh());
|
||||
}
|
||||
@ -184,30 +187,14 @@ public class NacosPropertySourceLocator implements PropertySourceLocator {
|
||||
}
|
||||
|
||||
private static void checkDataIdFileExtension(String[] dataIdArray) {
|
||||
StringBuilder stringBuilder = new StringBuilder();
|
||||
|
||||
for (String dataId : dataIdArray) {
|
||||
if (!canLoadFileExtension(dataId)) {
|
||||
stringBuilder.append(dataId).append(",");
|
||||
}
|
||||
}
|
||||
|
||||
if (stringBuilder.length() > 0) {
|
||||
String result = stringBuilder.substring(0, stringBuilder.length() - 1);
|
||||
throw new IllegalStateException(String.format(
|
||||
"[%s] must end file extension with properties|yaml|yml",
|
||||
result));
|
||||
if (dataIdArray == null || dataIdArray.length < 1) {
|
||||
throw new IllegalStateException("The dataId cannot be empty");
|
||||
}
|
||||
// Just decide that the current dataId must have a suffix
|
||||
NacosDataParserHandler.getInstance().checkDataId(dataIdArray);
|
||||
}
|
||||
|
||||
private static boolean canLoadFileExtension(String dataId) {
|
||||
return SUPPORT_FILE_EXTENSION.stream()
|
||||
.anyMatch((fileExtension) -> StringUtils.endsWithIgnoreCase(dataId,
|
||||
fileExtension));
|
||||
}
|
||||
|
||||
private boolean checkDataIdIsRefreshable(String refreshDataIds,
|
||||
String sharedDataId) {
|
||||
private boolean checkDataIdIsRefreshable(String refreshDataIds, String sharedDataId) {
|
||||
if (StringUtils.isEmpty(refreshDataIds)) {
|
||||
return false;
|
||||
}
|
||||
|
@ -42,8 +42,8 @@ public class NacosConfigEndpoint {
|
||||
|
||||
private final NacosRefreshHistory refreshHistory;
|
||||
|
||||
private ThreadLocal<DateFormat> dateFormat = ThreadLocal.withInitial(() ->
|
||||
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
|
||||
private ThreadLocal<DateFormat> dateFormat = ThreadLocal
|
||||
.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
|
||||
|
||||
public NacosConfigEndpoint(NacosConfigProperties properties,
|
||||
NacosRefreshHistory refreshHistory) {
|
||||
|
@ -16,6 +16,7 @@
|
||||
|
||||
package com.alibaba.cloud.nacos.endpoint;
|
||||
|
||||
import com.alibaba.cloud.nacos.NacosConfigManager;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.actuate.autoconfigure.endpoint.condition.ConditionalOnEnabledEndpoint;
|
||||
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
|
||||
@ -39,6 +40,9 @@ public class NacosConfigEndpointAutoConfiguration {
|
||||
@Autowired
|
||||
private NacosConfigProperties nacosConfigProperties;
|
||||
|
||||
@Autowired
|
||||
private NacosConfigManager nacosConfigManager;
|
||||
|
||||
@Autowired
|
||||
private NacosRefreshHistory nacosRefreshHistory;
|
||||
|
||||
@ -51,6 +55,6 @@ public class NacosConfigEndpointAutoConfiguration {
|
||||
|
||||
@Bean
|
||||
public NacosConfigHealthIndicator nacosConfigHealthIndicator() {
|
||||
return new NacosConfigHealthIndicator(nacosConfigProperties.configServiceInstance());
|
||||
return new NacosConfigHealthIndicator(nacosConfigManager.getConfigService());
|
||||
}
|
||||
}
|
||||
|
@ -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);
|
||||
}
|
||||
|
||||
}
|
@ -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());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -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;
|
||||
}
|
||||
|
||||
}
|
@ -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;
|
||||
}
|
||||
}
|
@ -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());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -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();
|
||||
}
|
||||
}
|
@ -20,18 +20,18 @@ import com.alibaba.cloud.nacos.endpoint.NacosConfigEndpointAutoConfiguration;
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = NacosConfigPropertiesServerAddressBothLevelTests.TestConfig.class, properties = {
|
||||
"spring.cloud.nacos.config.server-addr=321,321,321,321:8848",
|
||||
"spring.cloud.nacos.server-addr=123.123.123.123:8848"
|
||||
}, webEnvironment = RANDOM_PORT)
|
||||
"spring.cloud.nacos.server-addr=123.123.123.123:8848" }, webEnvironment = RANDOM_PORT)
|
||||
public class NacosConfigPropertiesServerAddressBothLevelTests {
|
||||
|
||||
@Autowired
|
||||
private NacosConfigProperties properties;
|
||||
|
||||
|
||||
@Test
|
||||
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
|
||||
@EnableAutoConfiguration
|
||||
@ImportAutoConfiguration({ NacosConfigEndpointAutoConfiguration.class,
|
||||
|
@ -19,18 +19,18 @@ import com.alibaba.cloud.nacos.endpoint.NacosConfigEndpointAutoConfiguration;
|
||||
*/
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = NacosConfigPropertiesServerAddressTopLevelTests.TestConfig.class, properties = {
|
||||
"spring.cloud.nacos.server-addr=123.123.123.123:8848"
|
||||
}, webEnvironment = RANDOM_PORT)
|
||||
"spring.cloud.nacos.server-addr=123.123.123.123:8848" }, webEnvironment = RANDOM_PORT)
|
||||
public class NacosConfigPropertiesServerAddressTopLevelTests {
|
||||
|
||||
@Autowired
|
||||
private NacosConfigProperties properties;
|
||||
|
||||
|
||||
@Test
|
||||
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
|
||||
@EnableAutoConfiguration
|
||||
@ImportAutoConfiguration({ NacosConfigEndpointAutoConfiguration.class,
|
||||
|
@ -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 {
|
||||
}
|
||||
}
|
@ -22,6 +22,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Map;
|
||||
|
||||
import com.alibaba.cloud.nacos.NacosConfigManager;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.powermock.api.mockito.PowerMockito;
|
||||
@ -83,6 +84,9 @@ public class NacosConfigEndpointTests {
|
||||
@Autowired
|
||||
private NacosConfigProperties properties;
|
||||
|
||||
@Autowired
|
||||
private NacosConfigManager nacosConfigManager;
|
||||
|
||||
@Autowired
|
||||
private NacosRefreshHistory refreshHistory;
|
||||
|
||||
@ -99,7 +103,7 @@ public class NacosConfigEndpointTests {
|
||||
Builder builder = new Builder();
|
||||
|
||||
NacosConfigHealthIndicator healthIndicator = new NacosConfigHealthIndicator(
|
||||
properties.configServiceInstance());
|
||||
nacosConfigManager.getConfigService());
|
||||
healthIndicator.doHealthCheck(builder);
|
||||
|
||||
Builder builder1 = new Builder();
|
||||
|
@ -45,16 +45,23 @@ public class NacosDiscoveryAutoConfiguration {
|
||||
|
||||
@Bean
|
||||
public NacosServiceRegistry nacosServiceRegistry(
|
||||
NacosNamingManager nacosNamingManager,
|
||||
NacosDiscoveryProperties nacosDiscoveryProperties) {
|
||||
return new NacosServiceRegistry(nacosDiscoveryProperties);
|
||||
return new NacosServiceRegistry(nacosNamingManager, nacosDiscoveryProperties);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public NacosNamingManager nacosNamingManager() {
|
||||
return new NacosNamingManager();
|
||||
}
|
||||
|
||||
@Bean
|
||||
@ConditionalOnBean(AutoServiceRegistrationProperties.class)
|
||||
public NacosRegistration nacosRegistration(
|
||||
public NacosRegistration nacosRegistration(NacosNamingManager nacosNamingManager,
|
||||
NacosDiscoveryProperties nacosDiscoveryProperties,
|
||||
ApplicationContext context) {
|
||||
return new NacosRegistration(nacosDiscoveryProperties, context);
|
||||
return new NacosRegistration(nacosNamingManager, nacosDiscoveryProperties,
|
||||
context);
|
||||
}
|
||||
|
||||
@Bean
|
||||
|
@ -427,7 +427,8 @@ public class NacosDiscoveryProperties {
|
||||
public void overrideFromEnv(Environment env) {
|
||||
|
||||
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)) {
|
||||
serverAddr = env.resolvePlaceholders("${spring.cloud.nacos.server-addr}");
|
||||
}
|
||||
@ -459,10 +460,11 @@ public class NacosDiscoveryProperties {
|
||||
}
|
||||
if (StringUtils.isEmpty(this.getGroup())) {
|
||||
this.setGroup(
|
||||
env.resolvePlaceholders("${spring.cloud.nacos.discovery.group:}"));
|
||||
env.resolvePlaceholders("${spring.cloud.nacos.discovery.group:}"));
|
||||
}
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public NamingService namingServiceInstance() {
|
||||
|
||||
if (null != namingService) {
|
||||
@ -479,6 +481,7 @@ public class NacosDiscoveryProperties {
|
||||
return namingService;
|
||||
}
|
||||
|
||||
@Deprecated
|
||||
public NamingMaintainService namingMaintainServiceInstance() {
|
||||
|
||||
if (null != namingMaintainService) {
|
||||
|
@ -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();
|
||||
}
|
||||
}
|
@ -17,6 +17,7 @@
|
||||
package com.alibaba.cloud.nacos.discovery;
|
||||
|
||||
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
|
||||
import com.alibaba.cloud.nacos.NacosNamingManager;
|
||||
import com.alibaba.cloud.nacos.NacosServiceInstance;
|
||||
import com.alibaba.nacos.api.naming.pojo.Instance;
|
||||
import com.alibaba.nacos.api.naming.pojo.ListView;
|
||||
@ -37,81 +38,86 @@ import java.util.Map;
|
||||
*/
|
||||
public class NacosDiscoveryClient implements DiscoveryClient {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(NacosDiscoveryClient.class);
|
||||
public static final String DESCRIPTION = "Spring Cloud Nacos Discovery Client";
|
||||
private static final Logger log = LoggerFactory.getLogger(NacosDiscoveryClient.class);
|
||||
public static final String DESCRIPTION = "Spring Cloud Nacos Discovery Client";
|
||||
|
||||
private NacosDiscoveryProperties discoveryProperties;
|
||||
private NacosNamingManager nacosNamingManager;
|
||||
private NacosDiscoveryProperties discoveryProperties;
|
||||
|
||||
public NacosDiscoveryClient(NacosDiscoveryProperties discoveryProperties) {
|
||||
this.discoveryProperties = discoveryProperties;
|
||||
}
|
||||
public NacosDiscoveryClient(NacosNamingManager nacosNamingManager,
|
||||
NacosDiscoveryProperties discoveryProperties) {
|
||||
this.nacosNamingManager = nacosNamingManager;
|
||||
this.discoveryProperties = discoveryProperties;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String description() {
|
||||
return DESCRIPTION;
|
||||
}
|
||||
@Override
|
||||
public String description() {
|
||||
return DESCRIPTION;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ServiceInstance> getInstances(String serviceId) {
|
||||
try {
|
||||
String group = discoveryProperties.getGroup();
|
||||
List<Instance> instances = discoveryProperties.namingServiceInstance()
|
||||
.selectInstances(serviceId, group, true);
|
||||
return hostToServiceInstanceList(instances, serviceId);
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException(
|
||||
"Can not get hosts from nacos server. serviceId: " + serviceId, e);
|
||||
}
|
||||
}
|
||||
@Override
|
||||
public List<ServiceInstance> getInstances(String serviceId) {
|
||||
try {
|
||||
String group = discoveryProperties.getGroup();
|
||||
List<Instance> instances = nacosNamingManager.getNamingService()
|
||||
.selectInstances(serviceId, group, true);
|
||||
return hostToServiceInstanceList(instances, serviceId);
|
||||
}
|
||||
catch (Exception e) {
|
||||
throw new RuntimeException(
|
||||
"Can not get hosts from nacos server. serviceId: " + serviceId, e);
|
||||
}
|
||||
}
|
||||
|
||||
public static ServiceInstance hostToServiceInstance(Instance instance,
|
||||
String serviceId) {
|
||||
if (instance == null || !instance.isEnabled() || !instance.isHealthy()) {
|
||||
return null;
|
||||
}
|
||||
NacosServiceInstance nacosServiceInstance = new NacosServiceInstance();
|
||||
nacosServiceInstance.setHost(instance.getIp());
|
||||
nacosServiceInstance.setPort(instance.getPort());
|
||||
nacosServiceInstance.setServiceId(serviceId);
|
||||
public static ServiceInstance hostToServiceInstance(Instance instance,
|
||||
String serviceId) {
|
||||
if (instance == null || !instance.isEnabled() || !instance.isHealthy()) {
|
||||
return null;
|
||||
}
|
||||
NacosServiceInstance nacosServiceInstance = new NacosServiceInstance();
|
||||
nacosServiceInstance.setHost(instance.getIp());
|
||||
nacosServiceInstance.setPort(instance.getPort());
|
||||
nacosServiceInstance.setServiceId(serviceId);
|
||||
|
||||
Map<String, String> metadata = new HashMap<>();
|
||||
metadata.put("nacos.instanceId", instance.getInstanceId());
|
||||
metadata.put("nacos.weight", instance.getWeight() + "");
|
||||
metadata.put("nacos.healthy", instance.isHealthy() + "");
|
||||
metadata.put("nacos.cluster", instance.getClusterName() + "");
|
||||
metadata.putAll(instance.getMetadata());
|
||||
nacosServiceInstance.setMetadata(metadata);
|
||||
Map<String, String> metadata = new HashMap<>();
|
||||
metadata.put("nacos.instanceId", instance.getInstanceId());
|
||||
metadata.put("nacos.weight", instance.getWeight() + "");
|
||||
metadata.put("nacos.healthy", instance.isHealthy() + "");
|
||||
metadata.put("nacos.cluster", instance.getClusterName() + "");
|
||||
metadata.putAll(instance.getMetadata());
|
||||
nacosServiceInstance.setMetadata(metadata);
|
||||
|
||||
if (metadata.containsKey("secure")) {
|
||||
boolean secure = Boolean.parseBoolean(metadata.get("secure"));
|
||||
nacosServiceInstance.setSecure(secure);
|
||||
}
|
||||
return nacosServiceInstance;
|
||||
}
|
||||
if (metadata.containsKey("secure")) {
|
||||
boolean secure = Boolean.parseBoolean(metadata.get("secure"));
|
||||
nacosServiceInstance.setSecure(secure);
|
||||
}
|
||||
return nacosServiceInstance;
|
||||
}
|
||||
|
||||
public static List<ServiceInstance> hostToServiceInstanceList(
|
||||
List<Instance> instances, String serviceId) {
|
||||
List<ServiceInstance> result = new ArrayList<>(instances.size());
|
||||
for (Instance instance : instances) {
|
||||
ServiceInstance serviceInstance = hostToServiceInstance(instance, serviceId);
|
||||
if (serviceInstance != null) {
|
||||
result.add(serviceInstance);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
public static List<ServiceInstance> hostToServiceInstanceList(
|
||||
List<Instance> instances, String serviceId) {
|
||||
List<ServiceInstance> result = new ArrayList<>(instances.size());
|
||||
for (Instance instance : instances) {
|
||||
ServiceInstance serviceInstance = hostToServiceInstance(instance, serviceId);
|
||||
if (serviceInstance != null) {
|
||||
result.add(serviceInstance);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> getServices() {
|
||||
@Override
|
||||
public List<String> getServices() {
|
||||
|
||||
try {
|
||||
String group = discoveryProperties.getGroup();
|
||||
ListView<String> services = discoveryProperties.namingServiceInstance()
|
||||
.getServicesOfServer(1, Integer.MAX_VALUE, group);
|
||||
return services.getData();
|
||||
} catch (Exception e) {
|
||||
log.error("get service name from nacos server fail,", e);
|
||||
return Collections.emptyList();
|
||||
}
|
||||
}
|
||||
try {
|
||||
String group = discoveryProperties.getGroup();
|
||||
ListView<String> services = nacosNamingManager.getNamingService()
|
||||
.getServicesOfServer(1, Integer.MAX_VALUE, group);
|
||||
return services.getData();
|
||||
}
|
||||
catch (Exception e) {
|
||||
log.error("get service name from nacos server fail,", e);
|
||||
return Collections.emptyList();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -16,6 +16,7 @@
|
||||
|
||||
package com.alibaba.cloud.nacos.discovery;
|
||||
|
||||
import com.alibaba.cloud.nacos.NacosNamingManager;
|
||||
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
@ -44,9 +45,9 @@ public class NacosDiscoveryClientAutoConfiguration {
|
||||
}
|
||||
|
||||
@Bean
|
||||
public DiscoveryClient nacosDiscoveryClient(
|
||||
public DiscoveryClient nacosDiscoveryClient(NacosNamingManager nacosNamingManager,
|
||||
NacosDiscoveryProperties discoveryProperties) {
|
||||
return new NacosDiscoveryClient(discoveryProperties);
|
||||
return new NacosDiscoveryClient(nacosNamingManager, discoveryProperties);
|
||||
}
|
||||
|
||||
@Bean
|
||||
|
@ -21,6 +21,7 @@ import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import com.alibaba.cloud.nacos.NacosNamingManager;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
|
||||
@ -40,9 +41,12 @@ public class NacosDiscoveryEndpoint {
|
||||
private static final Logger log = LoggerFactory
|
||||
.getLogger(NacosDiscoveryEndpoint.class);
|
||||
|
||||
private NacosNamingManager nacosNamingManager;
|
||||
private NacosDiscoveryProperties nacosDiscoveryProperties;
|
||||
|
||||
public NacosDiscoveryEndpoint(NacosDiscoveryProperties nacosDiscoveryProperties) {
|
||||
public NacosDiscoveryEndpoint(NacosNamingManager nacosNamingManager,
|
||||
NacosDiscoveryProperties nacosDiscoveryProperties) {
|
||||
this.nacosNamingManager = nacosNamingManager;
|
||||
this.nacosDiscoveryProperties = nacosDiscoveryProperties;
|
||||
}
|
||||
|
||||
@ -54,7 +58,7 @@ public class NacosDiscoveryEndpoint {
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("NacosDiscoveryProperties", nacosDiscoveryProperties);
|
||||
|
||||
NamingService namingService = nacosDiscoveryProperties.namingServiceInstance();
|
||||
NamingService namingService = nacosNamingManager.getNamingService();
|
||||
List<ServiceInfo> subscribe = Collections.emptyList();
|
||||
|
||||
try {
|
||||
|
@ -16,6 +16,7 @@
|
||||
|
||||
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.endpoint.annotation.Endpoint;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
||||
@ -38,8 +39,9 @@ public class NacosDiscoveryEndpointAutoConfiguration {
|
||||
@ConditionalOnMissingBean
|
||||
@ConditionalOnEnabledEndpoint
|
||||
public NacosDiscoveryEndpoint nacosDiscoveryEndpoint(
|
||||
NacosNamingManager nacosNamingManager,
|
||||
NacosDiscoveryProperties nacosDiscoveryProperties) {
|
||||
return new NacosDiscoveryEndpoint(nacosDiscoveryProperties);
|
||||
return new NacosDiscoveryEndpoint(nacosNamingManager, nacosDiscoveryProperties);
|
||||
}
|
||||
|
||||
}
|
||||
|
@ -21,6 +21,7 @@ import java.util.Map;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
|
||||
import com.alibaba.cloud.nacos.NacosNamingManager;
|
||||
import org.springframework.cloud.client.DefaultServiceInstance;
|
||||
import org.springframework.cloud.client.ServiceInstance;
|
||||
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_ENDPOINT_BASE_PATH = "management.endpoints.web.base-path";
|
||||
|
||||
private NacosNamingManager nacosNamingManager;
|
||||
private NacosDiscoveryProperties nacosDiscoveryProperties;
|
||||
|
||||
private ApplicationContext context;
|
||||
|
||||
public NacosRegistration(NacosDiscoveryProperties nacosDiscoveryProperties,
|
||||
public NacosRegistration(NacosNamingManager nacosNamingManager,
|
||||
NacosDiscoveryProperties nacosDiscoveryProperties,
|
||||
ApplicationContext context) {
|
||||
this.nacosNamingManager = nacosNamingManager;
|
||||
this.nacosDiscoveryProperties = nacosDiscoveryProperties;
|
||||
this.context = context;
|
||||
}
|
||||
@ -143,7 +147,7 @@ public class NacosRegistration implements Registration, ServiceInstance {
|
||||
}
|
||||
|
||||
public NamingService getNacosNamingService() {
|
||||
return nacosDiscoveryProperties.namingServiceInstance();
|
||||
return nacosNamingManager.getNamingService();
|
||||
}
|
||||
|
||||
@Override
|
||||
|
@ -18,6 +18,7 @@ package com.alibaba.cloud.nacos.registry;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.alibaba.cloud.nacos.NacosNamingManager;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
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 final NacosNamingManager nacosNamingManager;
|
||||
private final NacosDiscoveryProperties nacosDiscoveryProperties;
|
||||
|
||||
private final NamingService namingService;
|
||||
|
||||
public NacosServiceRegistry(NacosDiscoveryProperties nacosDiscoveryProperties) {
|
||||
public NacosServiceRegistry(NacosNamingManager nacosNamingManager,
|
||||
NacosDiscoveryProperties nacosDiscoveryProperties) {
|
||||
this.nacosNamingManager = nacosNamingManager;
|
||||
this.nacosDiscoveryProperties = nacosDiscoveryProperties;
|
||||
this.namingService = nacosDiscoveryProperties.namingServiceInstance();
|
||||
this.namingService = nacosNamingManager.getNamingService();
|
||||
}
|
||||
|
||||
@Override
|
||||
@ -79,7 +83,7 @@ public class NacosServiceRegistry implements ServiceRegistry<Registration> {
|
||||
return;
|
||||
}
|
||||
|
||||
NamingService namingService = nacosDiscoveryProperties.namingServiceInstance();
|
||||
NamingService namingService = nacosNamingManager.getNamingService();
|
||||
String serviceId = registration.getServiceId();
|
||||
String group = nacosDiscoveryProperties.getGroup();
|
||||
|
||||
@ -120,8 +124,8 @@ public class NacosServiceRegistry implements ServiceRegistry<Registration> {
|
||||
}
|
||||
|
||||
try {
|
||||
nacosDiscoveryProperties.namingMaintainServiceInstance()
|
||||
.updateInstance(serviceId, instance);
|
||||
nacosNamingManager.getNamingMaintainService().updateInstance(serviceId,
|
||||
instance);
|
||||
}
|
||||
catch (Exception e) {
|
||||
throw new RuntimeException("update nacos instance status fail", e);
|
||||
@ -134,7 +138,7 @@ public class NacosServiceRegistry implements ServiceRegistry<Registration> {
|
||||
|
||||
String serviceName = registration.getServiceId();
|
||||
try {
|
||||
List<Instance> instances = nacosDiscoveryProperties.namingServiceInstance()
|
||||
List<Instance> instances = nacosNamingManager.getNamingService()
|
||||
.getAllInstances(serviceName);
|
||||
for (Instance instance : instances) {
|
||||
if (instance.getIp().equalsIgnoreCase(nacosDiscoveryProperties.getIp())
|
||||
|
@ -16,6 +16,7 @@
|
||||
|
||||
package com.alibaba.cloud.nacos.ribbon;
|
||||
|
||||
import com.alibaba.cloud.nacos.NacosNamingManager;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
@ -36,8 +37,10 @@ public class NacosRibbonClientConfiguration {
|
||||
@Bean
|
||||
@ConditionalOnMissingBean
|
||||
public ServerList<?> ribbonServerList(IClientConfig config,
|
||||
NacosNamingManager nacosNamingManager,
|
||||
NacosDiscoveryProperties nacosDiscoveryProperties) {
|
||||
NacosServerList serverList = new NacosServerList(nacosDiscoveryProperties);
|
||||
NacosServerList serverList = new NacosServerList(nacosNamingManager,
|
||||
nacosDiscoveryProperties);
|
||||
serverList.initWithNiwsConfig(config);
|
||||
return serverList;
|
||||
}
|
||||
|
@ -4,6 +4,7 @@ import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import com.alibaba.cloud.nacos.NacosNamingManager;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@ -31,6 +32,9 @@ public class NacosRule extends AbstractLoadBalancerRule {
|
||||
@Autowired
|
||||
private NacosDiscoveryProperties nacosDiscoveryProperties;
|
||||
|
||||
@Autowired
|
||||
private NacosNamingManager nacosNamingManager;
|
||||
|
||||
@Override
|
||||
public Server choose(Object key) {
|
||||
try {
|
||||
@ -38,8 +42,7 @@ public class NacosRule extends AbstractLoadBalancerRule {
|
||||
DynamicServerListLoadBalancer loadBalancer = (DynamicServerListLoadBalancer) getLoadBalancer();
|
||||
String name = loadBalancer.getName();
|
||||
|
||||
NamingService namingService = this.nacosDiscoveryProperties
|
||||
.namingServiceInstance();
|
||||
NamingService namingService = this.nacosNamingManager.getNamingService();
|
||||
List<Instance> instances = namingService.selectInstances(name, true);
|
||||
if (CollectionUtils.isEmpty(instances)) {
|
||||
LOGGER.warn("no instance in service {}", name);
|
||||
|
@ -20,6 +20,7 @@ import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
|
||||
import com.alibaba.cloud.nacos.NacosNamingManager;
|
||||
import com.alibaba.nacos.api.naming.pojo.Instance;
|
||||
|
||||
import com.alibaba.nacos.client.naming.utils.CollectionUtils;
|
||||
@ -32,11 +33,14 @@ import com.netflix.loadbalancer.AbstractServerList;
|
||||
*/
|
||||
public class NacosServerList extends AbstractServerList<NacosServer> {
|
||||
|
||||
private NacosNamingManager nacosNamingManager;
|
||||
private NacosDiscoveryProperties discoveryProperties;
|
||||
|
||||
private String serviceId;
|
||||
|
||||
public NacosServerList(NacosDiscoveryProperties discoveryProperties) {
|
||||
public NacosServerList(NacosNamingManager nacosNamingManager,
|
||||
NacosDiscoveryProperties discoveryProperties) {
|
||||
this.nacosNamingManager = nacosNamingManager;
|
||||
this.discoveryProperties = discoveryProperties;
|
||||
}
|
||||
|
||||
@ -53,8 +57,8 @@ public class NacosServerList extends AbstractServerList<NacosServer> {
|
||||
private List<NacosServer> getServers() {
|
||||
try {
|
||||
String group = discoveryProperties.getGroup();
|
||||
List<Instance> instances = discoveryProperties.namingServiceInstance()
|
||||
.selectInstances(serviceId, group,true);
|
||||
List<Instance> instances = nacosNamingManager.getNamingService()
|
||||
.selectInstances(serviceId, group, true);
|
||||
return instancesToServerList(instances);
|
||||
}
|
||||
catch (Exception e) {
|
||||
|
@ -56,16 +56,17 @@ public class NacosDiscoveryClientTests {
|
||||
|
||||
NacosDiscoveryProperties nacosDiscoveryProperties = mock(
|
||||
NacosDiscoveryProperties.class);
|
||||
NacosNamingManager nacosNamingManager = mock(NacosNamingManager.class);
|
||||
|
||||
NamingService namingService = mock(NamingService.class);
|
||||
|
||||
when(nacosDiscoveryProperties.namingServiceInstance()).thenReturn(namingService);
|
||||
when(nacosNamingManager.getNamingService()).thenReturn(namingService);
|
||||
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);
|
||||
|
||||
NacosDiscoveryClient discoveryClient = new NacosDiscoveryClient(
|
||||
nacosDiscoveryProperties);
|
||||
nacosNamingManager, nacosDiscoveryProperties);
|
||||
|
||||
List<ServiceInstance> serviceInstances = discoveryClient
|
||||
.getInstances(serviceName);
|
||||
@ -97,16 +98,17 @@ public class NacosDiscoveryClientTests {
|
||||
|
||||
NacosDiscoveryProperties nacosDiscoveryProperties = mock(
|
||||
NacosDiscoveryProperties.class);
|
||||
NacosNamingManager nacosNamingManager = mock(NacosNamingManager.class);
|
||||
|
||||
NamingService namingService = mock(NamingService.class);
|
||||
|
||||
NacosDiscoveryClient discoveryClient = new NacosDiscoveryClient(
|
||||
nacosDiscoveryProperties);
|
||||
nacosNamingManager, nacosDiscoveryProperties);
|
||||
|
||||
when(nacosDiscoveryProperties.namingServiceInstance()).thenReturn(namingService);
|
||||
when(nacosNamingManager.getNamingService()).thenReturn(namingService);
|
||||
when(nacosDiscoveryProperties.getGroup()).thenReturn("DEFAULT");
|
||||
when(namingService.getServicesOfServer(eq(1), eq(Integer.MAX_VALUE),eq("DEFAULT")))
|
||||
.thenReturn(nacosServices);
|
||||
when(namingService.getServicesOfServer(eq(1), eq(Integer.MAX_VALUE),
|
||||
eq("DEFAULT"))).thenReturn(nacosServices);
|
||||
|
||||
List<String> services = discoveryClient.getServices();
|
||||
|
||||
|
@ -23,18 +23,18 @@ import com.alibaba.cloud.nacos.discovery.NacosDiscoveryClientAutoConfiguration;
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = NacosDiscoveryPropertiesServerAddressBothLevelTests.TestConfig.class, properties = {
|
||||
"spring.cloud.nacos.discovery.server-addr=321.321.321.321:8848",
|
||||
"spring.cloud.nacos.server-addr=123.123.123.123:8848"
|
||||
}, webEnvironment = RANDOM_PORT)
|
||||
"spring.cloud.nacos.server-addr=123.123.123.123:8848" }, webEnvironment = RANDOM_PORT)
|
||||
public class NacosDiscoveryPropertiesServerAddressBothLevelTests {
|
||||
|
||||
@Autowired
|
||||
private NacosDiscoveryProperties properties;
|
||||
|
||||
|
||||
@Test
|
||||
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
|
||||
@EnableAutoConfiguration
|
||||
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class,
|
||||
|
@ -24,19 +24,19 @@ import com.alibaba.cloud.nacos.discovery.NacosDiscoveryClientAutoConfiguration;
|
||||
*/
|
||||
@RunWith(SpringRunner.class)
|
||||
@SpringBootTest(classes = NacosDiscoveryPropertiesServerAddressTopLevelTests.TestConfig.class, properties = {
|
||||
"spring.cloud.nacos.server-addr=123.123.123.123:8848"
|
||||
}, webEnvironment = RANDOM_PORT)
|
||||
"spring.cloud.nacos.server-addr=123.123.123.123:8848" }, webEnvironment = RANDOM_PORT)
|
||||
|
||||
public class NacosDiscoveryPropertiesServerAddressTopLevelTests {
|
||||
|
||||
@Autowired
|
||||
private NacosDiscoveryProperties properties;
|
||||
|
||||
|
||||
@Test
|
||||
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
|
||||
@EnableAutoConfiguration
|
||||
@ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class,
|
||||
|
@ -23,6 +23,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import com.alibaba.cloud.nacos.NacosNamingManager;
|
||||
import org.junit.Test;
|
||||
import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
@ -74,6 +75,9 @@ public class NacosAutoServiceRegistrationTests {
|
||||
@Autowired
|
||||
private NacosDiscoveryProperties properties;
|
||||
|
||||
@Autowired
|
||||
private NacosNamingManager nacosNamingManager;
|
||||
|
||||
@Autowired
|
||||
private InetUtils inetUtils;
|
||||
|
||||
@ -204,11 +208,11 @@ public class NacosAutoServiceRegistrationTests {
|
||||
|
||||
private void checkoutEndpoint() throws Exception {
|
||||
NacosDiscoveryEndpoint nacosDiscoveryEndpoint = new NacosDiscoveryEndpoint(
|
||||
properties);
|
||||
nacosNamingManager, properties);
|
||||
Map<String, Object> map = nacosDiscoveryEndpoint.nacosDiscovery();
|
||||
assertEquals(map.get("NacosDiscoveryProperties"), properties);
|
||||
assertEquals(map.get("subscribe").toString(),
|
||||
properties.namingServiceInstance().getSubscribeServices().toString());
|
||||
nacosNamingManager.getNamingService().getSubscribeServices().toString());
|
||||
}
|
||||
|
||||
@Configuration
|
||||
|
@ -28,6 +28,7 @@ import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import com.alibaba.cloud.nacos.NacosNamingManager;
|
||||
import org.junit.Test;
|
||||
|
||||
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
|
||||
@ -48,14 +49,16 @@ public class NacosServerListTests {
|
||||
public void testEmptyInstancesReturnsEmptyList() throws Exception {
|
||||
NacosDiscoveryProperties nacosDiscoveryProperties = mock(
|
||||
NacosDiscoveryProperties.class);
|
||||
NacosNamingManager nacosNamingManager = mock(NacosNamingManager.class);
|
||||
|
||||
NamingService namingService = mock(NamingService.class);
|
||||
|
||||
when(nacosDiscoveryProperties.namingServiceInstance()).thenReturn(namingService);
|
||||
when(nacosNamingManager.getNamingService()).thenReturn(namingService);
|
||||
when(namingService.selectInstances(anyString(), eq("DEFAULT"), eq(true)))
|
||||
.thenReturn(null);
|
||||
|
||||
NacosServerList serverList = new NacosServerList(nacosDiscoveryProperties);
|
||||
NacosServerList serverList = new NacosServerList(nacosNamingManager,
|
||||
nacosDiscoveryProperties);
|
||||
List<NacosServer> servers = serverList.getInitialListOfServers();
|
||||
assertThat(servers).isEmpty();
|
||||
}
|
||||
@ -70,10 +73,11 @@ public class NacosServerListTests {
|
||||
|
||||
NacosDiscoveryProperties nacosDiscoveryProperties = mock(
|
||||
NacosDiscoveryProperties.class);
|
||||
NacosNamingManager nacosNamingManager = mock(NacosNamingManager.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)))
|
||||
@ -81,7 +85,8 @@ public class NacosServerListTests {
|
||||
|
||||
IClientConfig clientConfig = mock(IClientConfig.class);
|
||||
when(clientConfig.getClientName()).thenReturn("test-service");
|
||||
NacosServerList serverList = new NacosServerList(nacosDiscoveryProperties);
|
||||
NacosServerList serverList = new NacosServerList(nacosNamingManager,
|
||||
nacosDiscoveryProperties);
|
||||
serverList.initWithNiwsConfig(clientConfig);
|
||||
List<NacosServer> servers = serverList.getInitialListOfServers();
|
||||
assertThat(servers).hasSize(1);
|
||||
@ -104,10 +109,11 @@ public class NacosServerListTests {
|
||||
|
||||
NacosDiscoveryProperties nacosDiscoveryProperties = mock(
|
||||
NacosDiscoveryProperties.class);
|
||||
NacosNamingManager nacosNamingManager = mock(NacosNamingManager.class);
|
||||
|
||||
NamingService namingService = mock(NamingService.class);
|
||||
|
||||
when(nacosDiscoveryProperties.namingServiceInstance()).thenReturn(namingService);
|
||||
when(nacosNamingManager.getNamingService()).thenReturn(namingService);
|
||||
when(nacosDiscoveryProperties.getGroup()).thenReturn("DEFAULT");
|
||||
when(namingService.selectInstances(eq("test-service"), eq("DEFAULT"), eq(true)))
|
||||
.thenReturn(instances.stream().filter(Instance::isHealthy)
|
||||
@ -115,7 +121,8 @@ public class NacosServerListTests {
|
||||
|
||||
IClientConfig clientConfig = mock(IClientConfig.class);
|
||||
when(clientConfig.getClientName()).thenReturn("test-service");
|
||||
NacosServerList serverList = new NacosServerList(nacosDiscoveryProperties);
|
||||
NacosServerList serverList = new NacosServerList(nacosNamingManager,
|
||||
nacosDiscoveryProperties);
|
||||
serverList.initWithNiwsConfig(clientConfig);
|
||||
List<NacosServer> servers = serverList.getInitialListOfServers();
|
||||
assertThat(servers).hasSize(1);
|
||||
@ -142,10 +149,11 @@ public class NacosServerListTests {
|
||||
|
||||
NacosDiscoveryProperties nacosDiscoveryProperties = mock(
|
||||
NacosDiscoveryProperties.class);
|
||||
NacosNamingManager nacosNamingManager = mock(NacosNamingManager.class);
|
||||
|
||||
NamingService namingService = mock(NamingService.class);
|
||||
|
||||
when(nacosDiscoveryProperties.namingServiceInstance()).thenReturn(namingService);
|
||||
when(nacosNamingManager.getNamingService()).thenReturn(namingService);
|
||||
when(nacosDiscoveryProperties.getGroup()).thenReturn("DEFAULT");
|
||||
when(namingService.selectInstances(eq("test-service"), eq("DEFAULT"), eq(true)))
|
||||
.thenReturn(instances.stream().filter(Instance::isHealthy)
|
||||
@ -153,7 +161,8 @@ public class NacosServerListTests {
|
||||
|
||||
IClientConfig clientConfig = mock(IClientConfig.class);
|
||||
when(clientConfig.getClientName()).thenReturn("test-service");
|
||||
NacosServerList serverList = new NacosServerList(nacosDiscoveryProperties);
|
||||
NacosServerList serverList = new NacosServerList(nacosNamingManager,
|
||||
nacosDiscoveryProperties);
|
||||
serverList.initWithNiwsConfig(clientConfig);
|
||||
|
||||
List<NacosServer> servers = serverList.getUpdatedListOfServers();
|
||||
|
Loading…
x
Reference in New Issue
Block a user