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

Merge pull request #155 from mengxiangrui007/master

optimize nacos config client code
This commit is contained in:
xiaojing 2018-12-16 13:03:27 +08:00 committed by GitHub
commit 9097ceaa12
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
7 changed files with 103 additions and 85 deletions

View File

@ -16,14 +16,11 @@
package org.springframework.cloud.alibaba.nacos; package org.springframework.cloud.alibaba.nacos;
import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.alibaba.nacos.refresh.NacosContextRefresher; import org.springframework.cloud.alibaba.nacos.refresh.NacosContextRefresher;
import org.springframework.cloud.alibaba.nacos.refresh.NacosRefreshHistory; import org.springframework.cloud.alibaba.nacos.refresh.NacosRefreshHistory;
import org.springframework.cloud.alibaba.nacos.refresh.NacosRefreshProperties; import org.springframework.cloud.alibaba.nacos.refresh.NacosRefreshProperties;
import org.springframework.cloud.context.refresh.ContextRefresher;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
@ -31,19 +28,23 @@ import org.springframework.context.annotation.Configuration;
* @author juven.xuxb * @author juven.xuxb
*/ */
@Configuration @Configuration
public class NacosConfigAutoConfiguration implements ApplicationContextAware { public class NacosConfigAutoConfiguration {
private ApplicationContext applicationContext; @Bean
public NacosConfigProperties nacosConfigProperties(ApplicationContext context) {
@Autowired if (context.getParent() != null
private NacosConfigProperties nacosConfigProperties; && BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
context.getParent(), NacosConfigProperties.class).length > 0) {
@Autowired return BeanFactoryUtils.beanOfTypeIncludingAncestors(context.getParent(),
private NacosRefreshProperties nacosRefreshProperties; NacosConfigProperties.class);
}
NacosConfigProperties nacosConfigProperties = new NacosConfigProperties();
return nacosConfigProperties;
}
@Bean @Bean
public NacosPropertySourceRepository nacosPropertySourceRepository() { public NacosPropertySourceRepository nacosPropertySourceRepository() {
return new NacosPropertySourceRepository(applicationContext); return new NacosPropertySourceRepository();
} }
@Bean @Bean
@ -57,17 +58,12 @@ public class NacosConfigAutoConfiguration implements ApplicationContextAware {
} }
@Bean @Bean
public NacosContextRefresher nacosContextRefresher(ContextRefresher contextRefresher, public NacosContextRefresher nacosContextRefresher(
NacosConfigProperties nacosConfigProperties,
NacosRefreshProperties nacosRefreshProperties,
NacosRefreshHistory refreshHistory, NacosRefreshHistory refreshHistory,
NacosPropertySourceRepository propertySourceRepository) { NacosPropertySourceRepository propertySourceRepository) {
return new NacosContextRefresher(contextRefresher, nacosConfigProperties, return new NacosContextRefresher(nacosRefreshProperties, refreshHistory,
nacosRefreshProperties, refreshHistory, propertySourceRepository, propertySourceRepository, nacosConfigProperties.configServiceInstance());
nacosConfigProperties.configServiceInstance());
}
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
this.applicationContext = applicationContext;
} }
} }

View File

@ -28,8 +28,9 @@ import org.springframework.context.annotation.Configuration;
public class NacosConfigBootstrapConfiguration { public class NacosConfigBootstrapConfiguration {
@Bean @Bean
public NacosPropertySourceLocator nacosPropertySourceLocator() { public NacosPropertySourceLocator nacosPropertySourceLocator(
return new NacosPropertySourceLocator(); NacosConfigProperties nacosConfigProperties) {
return new NacosPropertySourceLocator(nacosConfigProperties);
} }
@Bean @Bean

View File

@ -16,8 +16,15 @@
package org.springframework.cloud.alibaba.nacos; package org.springframework.cloud.alibaba.nacos;
import com.alibaba.nacos.api.NacosFactory; import static com.alibaba.nacos.api.PropertyKeyConst.*;
import com.alibaba.nacos.api.config.ConfigService;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Properties;
import javax.annotation.PostConstruct;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -25,13 +32,8 @@ import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.core.env.Environment; import org.springframework.core.env.Environment;
import javax.annotation.PostConstruct; import com.alibaba.nacos.api.NacosFactory;
import java.util.Arrays; import com.alibaba.nacos.api.config.ConfigService;
import java.util.List;
import java.util.Objects;
import java.util.Properties;
import static com.alibaba.nacos.api.PropertyKeyConst.*;
/** /**
* nacos properties * nacos properties
@ -40,9 +42,11 @@ import static com.alibaba.nacos.api.PropertyKeyConst.*;
* @author xiaojing * @author xiaojing
* @author pbting * @author pbting
*/ */
@ConfigurationProperties("spring.cloud.nacos.config") @ConfigurationProperties(NacosConfigProperties.PREFIX)
public class NacosConfigProperties { public class NacosConfigProperties {
public static final String PREFIX = "spring.cloud.nacos.config";
private static final Logger LOGGER = LoggerFactory private static final Logger LOGGER = LoggerFactory
.getLogger(NacosConfigProperties.class); .getLogger(NacosConfigProperties.class);

View File

@ -21,6 +21,7 @@ import java.util.List;
import org.springframework.cloud.alibaba.nacos.client.NacosPropertySource; import org.springframework.cloud.alibaba.nacos.client.NacosPropertySource;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.CompositePropertySource; import org.springframework.core.env.CompositePropertySource;
import org.springframework.core.env.PropertySource; import org.springframework.core.env.PropertySource;
@ -28,11 +29,12 @@ import org.springframework.core.env.PropertySource;
/** /**
* @author xiaojing * @author xiaojing
*/ */
public class NacosPropertySourceRepository { public class NacosPropertySourceRepository implements ApplicationContextAware {
private final ApplicationContext applicationContext; private ApplicationContext applicationContext;
public NacosPropertySourceRepository(ApplicationContext applicationContext) { @Override
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext; this.applicationContext = applicationContext;
} }
@ -54,7 +56,7 @@ public class NacosPropertySourceRepository {
} }
private void collectNacosPropertySources(CompositePropertySource composite, private void collectNacosPropertySources(CompositePropertySource composite,
List<NacosPropertySource> result) { List<NacosPropertySource> result) {
for (PropertySource p : composite.getPropertySources()) { for (PropertySource p : composite.getPropertySources()) {
if (p instanceof NacosPropertySource) { if (p instanceof NacosPropertySource) {
result.add((NacosPropertySource) p); result.add((NacosPropertySource) p);

View File

@ -16,32 +16,28 @@
package org.springframework.cloud.alibaba.nacos.client; package org.springframework.cloud.alibaba.nacos.client;
import com.alibaba.nacos.api.config.ConfigService; import java.io.StringReader;
import com.alibaba.nacos.api.exception.NacosException; import java.util.*;
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.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.io.ByteArrayResource; import org.springframework.core.io.ByteArrayResource;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import java.io.StringReader; import com.alibaba.nacos.api.config.ConfigService;
import java.util.*; import com.alibaba.nacos.api.exception.NacosException;
/** /**
* @author xiaojing * @author xiaojing
* @author pbting * @author pbting
*/ */
public class NacosPropertySourceBuilder { public class NacosPropertySourceBuilder {
private static final Logger LOGGER = LoggerFactory
private static final Logger logger = LoggerFactory
.getLogger(NacosPropertySourceBuilder.class); .getLogger(NacosPropertySourceBuilder.class);
private ConfigService configService; private ConfigService configService;
private long timeout; private long timeout;
public NacosPropertySourceBuilder() {
}
public NacosPropertySourceBuilder(ConfigService configService, long timeout) { public NacosPropertySourceBuilder(ConfigService configService, long timeout) {
this.configService = configService; this.configService = configService;
this.timeout = timeout; this.timeout = timeout;
@ -82,7 +78,7 @@ 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)) {
logger.info(String.format("Loading nacos data, dataId: '%s', group: '%s'", LOGGER.info(String.format("Loading nacos data, dataId: '%s', group: '%s'",
dataId, group)); dataId, group));
if (fileExtension.equalsIgnoreCase("properties")) { if (fileExtension.equalsIgnoreCase("properties")) {
@ -101,10 +97,10 @@ public class NacosPropertySourceBuilder {
} }
} }
catch (NacosException e) { catch (NacosException e) {
logger.error("get data from Nacos error,dataId:{}, ", dataId, e); LOGGER.error("get data from Nacos error,dataId:{}, ", dataId, e);
} }
catch (Exception e) { catch (Exception e) {
logger.error("parse data from Nacos error,dataId:{},data:{},", dataId, data, LOGGER.error("parse data from Nacos error,dataId:{},data:{},", dataId, data,
e); e);
} }
return null; return null;

View File

@ -16,10 +16,11 @@
package org.springframework.cloud.alibaba.nacos.client; package org.springframework.cloud.alibaba.nacos.client;
import com.alibaba.nacos.api.config.ConfigService; import java.util.Arrays;
import java.util.List;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.alibaba.nacos.NacosConfigProperties; import org.springframework.cloud.alibaba.nacos.NacosConfigProperties;
import org.springframework.cloud.bootstrap.config.PropertySourceLocator; import org.springframework.cloud.bootstrap.config.PropertySourceLocator;
import org.springframework.core.annotation.Order; import org.springframework.core.annotation.Order;
@ -27,8 +28,8 @@ import org.springframework.core.env.CompositePropertySource;
import org.springframework.core.env.Environment; import org.springframework.core.env.Environment;
import org.springframework.core.env.PropertySource; import org.springframework.core.env.PropertySource;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import java.util.Arrays;
import java.util.List; import com.alibaba.nacos.api.config.ConfigService;
/** /**
* @author xiaojing * @author xiaojing
@ -36,7 +37,7 @@ import java.util.List;
@Order(0) @Order(0)
public class NacosPropertySourceLocator implements PropertySourceLocator { public class NacosPropertySourceLocator implements PropertySourceLocator {
private static final Logger logger = LoggerFactory private static final Logger LOGGER = LoggerFactory
.getLogger(NacosPropertySourceLocator.class); .getLogger(NacosPropertySourceLocator.class);
private static final String NACOS_PROPERTY_SOURCE_NAME = "NACOS"; private static final String NACOS_PROPERTY_SOURCE_NAME = "NACOS";
private static final String SEP1 = "-"; private static final String SEP1 = "-";
@ -45,9 +46,12 @@ public class NacosPropertySourceLocator implements PropertySourceLocator {
private static final List<String> SUPPORT_FILE_EXTENSION = Arrays.asList("properties", private static final List<String> SUPPORT_FILE_EXTENSION = Arrays.asList("properties",
"yaml", "yml"); "yaml", "yml");
@Autowired
private NacosConfigProperties nacosConfigProperties; private NacosConfigProperties nacosConfigProperties;
public NacosPropertySourceLocator(NacosConfigProperties nacosConfigProperties) {
this.nacosConfigProperties = nacosConfigProperties;
}
private NacosPropertySourceBuilder nacosPropertySourceBuilder; private NacosPropertySourceBuilder nacosPropertySourceBuilder;
@Override @Override
@ -56,7 +60,7 @@ public class NacosPropertySourceLocator implements PropertySourceLocator {
ConfigService configService = nacosConfigProperties.configServiceInstance(); ConfigService configService = nacosConfigProperties.configServiceInstance();
if (null == configService) { if (null == configService) {
logger.warn( LOGGER.warn(
"no instance of config service found, can't load config from nacos"); "no instance of config service found, can't load config from nacos");
return null; return null;
} }

View File

@ -16,19 +16,6 @@
package org.springframework.cloud.alibaba.nacos.refresh; package org.springframework.cloud.alibaba.nacos.refresh;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.cloud.alibaba.nacos.NacosConfigProperties;
import org.springframework.cloud.alibaba.nacos.NacosPropertySourceRepository;
import org.springframework.cloud.alibaba.nacos.client.NacosPropertySource;
import org.springframework.cloud.context.refresh.ContextRefresher;
import org.springframework.context.ApplicationListener;
import org.springframework.util.StringUtils;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.math.BigInteger; import java.math.BigInteger;
import java.security.MessageDigest; import java.security.MessageDigest;
@ -36,6 +23,22 @@ import java.security.NoSuchAlgorithmException;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor; import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicBoolean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.cloud.alibaba.nacos.NacosPropertySourceRepository;
import org.springframework.cloud.alibaba.nacos.client.NacosPropertySource;
import org.springframework.cloud.endpoint.event.RefreshEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.util.StringUtils;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
/** /**
* On application start up, NacosContextRefresher add nacos listeners to all application * On application start up, NacosContextRefresher add nacos listeners to all application
@ -45,13 +48,11 @@ import java.util.concurrent.Executor;
* @author juven.xuxb * @author juven.xuxb
* @author pbting * @author pbting
*/ */
public class NacosContextRefresher implements ApplicationListener<ApplicationReadyEvent> { public class NacosContextRefresher
implements ApplicationListener<ApplicationReadyEvent>, ApplicationContextAware {
private Logger logger = LoggerFactory.getLogger(NacosContextRefresher.class); private final static Logger LOGGER = LoggerFactory
.getLogger(NacosContextRefresher.class);
private final ContextRefresher contextRefresher;
private final NacosConfigProperties properties;
private final NacosRefreshProperties refreshProperties; private final NacosRefreshProperties refreshProperties;
@ -61,15 +62,16 @@ public class NacosContextRefresher implements ApplicationListener<ApplicationRea
private final ConfigService configService; private final ConfigService configService;
private ApplicationContext applicationContext;
private AtomicBoolean ready = new AtomicBoolean(true);
private Map<String, Listener> listenerMap = new ConcurrentHashMap<>(16); private Map<String, Listener> listenerMap = new ConcurrentHashMap<>(16);
public NacosContextRefresher(ContextRefresher contextRefresher, public NacosContextRefresher(NacosRefreshProperties refreshProperties,
NacosConfigProperties properties, NacosRefreshProperties refreshProperties,
NacosRefreshHistory refreshHistory, NacosRefreshHistory refreshHistory,
NacosPropertySourceRepository nacosPropertySourceRepository, NacosPropertySourceRepository nacosPropertySourceRepository,
ConfigService configService) { ConfigService configService) {
this.contextRefresher = contextRefresher;
this.properties = properties;
this.refreshProperties = refreshProperties; this.refreshProperties = refreshProperties;
this.refreshHistory = refreshHistory; this.refreshHistory = refreshHistory;
this.nacosPropertySourceRepository = nacosPropertySourceRepository; this.nacosPropertySourceRepository = nacosPropertySourceRepository;
@ -78,7 +80,16 @@ public class NacosContextRefresher implements ApplicationListener<ApplicationRea
@Override @Override
public void onApplicationEvent(ApplicationReadyEvent event) { public void onApplicationEvent(ApplicationReadyEvent event) {
this.registerNacosListenersForApplications(); // many Spring context
if (this.ready.get()) {
this.registerNacosListenersForApplications();
this.ready.compareAndSet(true, false);
}
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
} }
private void registerNacosListenersForApplications() { private void registerNacosListenersForApplications() {
@ -108,11 +119,15 @@ public class NacosContextRefresher implements ApplicationListener<ApplicationRea
.toString(16); .toString(16);
} }
catch (NoSuchAlgorithmException | UnsupportedEncodingException e) { catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
logger.warn("[Nacos] unable to get md5 for dataId: " + dataId, e); LOGGER.warn("[Nacos] unable to get md5 for dataId: " + dataId, e);
} }
} }
refreshHistory.add(dataId, md5); refreshHistory.add(dataId, md5);
contextRefresher.refresh(); applicationContext.publishEvent(
new RefreshEvent(this, null, "Refresh Nacos config"));
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Refresh Nacos config group{},dataId{}", group, dataId);
}
} }
@Override @Override