提交 50b3ac34 authored 作者: 陈世营's avatar 陈世营

合并分支 'master' 到 'release-0.1'

Master 查看合并请求 !1
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
......@@ -40,30 +42,51 @@
<properties>
<!-- Project revision -->
<revision>2.0.2.RELEASE</revision>
<!-- Dependency Versions -->
<spring-cloud-commons.version>2.0.4.RELEASE</spring-cloud-commons.version>
<spring-cloud-netflix.version>2.0.4.RELEASE</spring-cloud-netflix.version>
<spring-cloud-openfeign.version>2.0.4.RELEASE</spring-cloud-openfeign.version>
<spring-cloud-bus.version>2.0.2.RELEASE</spring-cloud-bus.version>
<spring-cloud-gateway.version>2.0.4.RELEASE</spring-cloud-gateway.version>
<spring-cloud-stream.version>Elmhurst.SR3</spring-cloud-stream.version>
<spring-cloud-consul.version>2.0.3.RELEASE</spring-cloud-consul.version>
<spring-cloud-config.version>2.0.5.RELEASE</spring-cloud-config.version>
<spring-cloud-zookeeper.version>2.0.2.RELEASE</spring-cloud-zookeeper.version>
<junit.version>4.12</junit.version>
<javax-servlet-api>3.0</javax-servlet-api>
<slf4j-api.version>1.7.25</slf4j-api.version>
<!-- Apache RocketMQ -->
<rocketmq.starter.version>2.0.2</rocketmq.starter.version>
<!-- Maven Plugin Versions -->
<maven-compiler-plugin.version>3.7.0</maven-compiler-plugin.version>
<maven-deploy-plugin.version>2.8.2</maven-deploy-plugin.version>
<maven-surefire-plugin.version>2.21.0</maven-surefire-plugin.version>
<gmavenplus-plugin.version>1.6</gmavenplus-plugin.version>
<jacoco.version>0.8.3</jacoco.version>
<spring-javaformat.version>0.0.9</spring-javaformat.version>
<maven-source-plugin.version>2.2.1</maven-source-plugin.version>
<maven-javadoc-plugin.version>3.1.1</maven-javadoc-plugin.version>
<maven-gpg-plugin.version>1.6</maven-gpg-plugin.version>
<flatten-maven-plugin.version>1.1.0</flatten-maven-plugin.version>
<!-- checkstyle -->
<puppycrawl-tools-checkstyle.version>8.18</puppycrawl-tools-checkstyle.version>
<spring-javaformat-checkstyle.version>0.0.7</spring-javaformat-checkstyle.version>
<maven-checkstyle-plugin.version>3.0.0</maven-checkstyle-plugin.version>
<nohttp-checkstyle.version>0.0.2.RELEASE</nohttp-checkstyle.version>
</properties>
<dependencyManagement>
<dependencies>
<!-- Spring Boot -->
<!-- Spring Dependencies -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
......@@ -75,7 +98,7 @@
<dependency>
<groupId>com.timeloit.cloud</groupId>
<artifactId>spring-cloud-timeloit-dependencies</artifactId>
<version>${project.version}</version>
<version>0.0.1-SNAPSHOT</version>
<type>pom</type>
<scope>import</scope>
</dependency>
......@@ -111,6 +134,14 @@
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-dependencies</artifactId>
<version>${spring-cloud-config.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-bus-dependencies</artifactId>
......@@ -126,11 +157,38 @@
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-stream-dependencies</artifactId>
<version>${spring-cloud-stream.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-consul-dependencies</artifactId>
<version>${spring-cloud-consul.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-zookeeper-dependencies</artifactId>
<version>${spring-cloud-zookeeper.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
......@@ -152,6 +210,34 @@
<reuseForks>false</reuseForks>
</configuration>
</plugin>
<!--<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>flatten-maven-plugin</artifactId>
<version>${flatten-maven-plugin.version}</version>
<configuration>
<updatePomFile>true</updatePomFile>
<flattenMode>resolveCiFriendliesOnly</flattenMode>
</configuration>
<executions>
<execution>
<id>flatten</id>
<phase>process-resources</phase>
<goals>
<goal>flatten</goal>
</goals>
</execution>
<execution>
<id>flatten.clean</id>
<phase>clean</phase>
<goals>
<goal>clean</goal>
</goals>
</execution>
</executions>
</plugin>-->
</plugins>
</build>
......
......@@ -15,71 +15,83 @@
<dependencies>
<dependency>
<groupId>com.alibaba.nacos</groupId>
<artifactId>nacos-client</artifactId>
</dependency>
<!--spring cloud-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-commons</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-context</artifactId>
</dependency>
<!--spring boot-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-actuator</artifactId>
<scope>provided</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-actuator-autoconfigure</artifactId>
<scope>provided</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<scope>provided</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot</artifactId>
<scope>provided</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<scope>provided</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.alibaba.spring</groupId>
<artifactId>spring-context-support</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.nacos</groupId>
<artifactId>nacos-client</artifactId>
</dependency>
<!--spring cloud-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-commons</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-context</artifactId>
</dependency>
<!-- Testing -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-test-support</artifactId>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.powermock.modules.test.powermockito/powermock-modules-test-powermockito -->
<dependency>
<groupId>org.powermock</groupId>
......@@ -87,6 +99,7 @@
<version>2.0.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito2</artifactId>
......@@ -95,4 +108,7 @@
</dependency>
</dependencies>
</project>
/*
* Copyright (C) 2018 the original author or authors.
* Copyright 2013-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
* https://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,
......@@ -19,13 +19,13 @@ package com.timeloit.cloud.nacos;
import com.timeloit.cloud.nacos.refresh.NacosContextRefresher;
import com.timeloit.cloud.nacos.refresh.NacosRefreshHistory;
import com.timeloit.cloud.nacos.refresh.NacosRefreshProperties;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author juven.xuxb
*/
......@@ -41,8 +41,7 @@ public class NacosConfigAutoConfiguration {
return BeanFactoryUtils.beanOfTypeIncludingAncestors(context.getParent(),
NacosConfigProperties.class);
}
NacosConfigProperties nacosConfigProperties = new NacosConfigProperties();
return nacosConfigProperties;
return new NacosConfigProperties();
}
@Bean
......@@ -55,12 +54,20 @@ public class NacosConfigAutoConfiguration {
return new NacosRefreshHistory();
}
@Bean
public NacosConfigManager nacosConfigManager(
NacosConfigProperties nacosConfigProperties) {
return new NacosConfigManager(nacosConfigProperties);
}
@Bean
public NacosContextRefresher nacosContextRefresher(
NacosConfigProperties nacosConfigProperties,
NacosRefreshProperties nacosRefreshProperties,
NacosRefreshHistory refreshHistory) {
return new NacosContextRefresher(nacosRefreshProperties, refreshHistory,
nacosConfigProperties.configServiceInstance());
NacosConfigManager nacosConfigManager,
NacosRefreshHistory nacosRefreshHistory) {
// Consider that it is not necessary to be compatible with the previous
// configuration
// and use the new configuration if necessary.
return new NacosContextRefresher(nacosConfigManager, nacosRefreshHistory);
}
}
/*
* Copyright (C) 2018 the original author or authors.
* Copyright 2013-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
* https://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,
......@@ -17,12 +17,12 @@
package com.timeloit.cloud.nacos;
import com.timeloit.cloud.nacos.client.NacosPropertySourceLocator;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author xiaojing
*/
......@@ -37,9 +37,16 @@ public class NacosConfigBootstrapConfiguration {
}
@Bean
public NacosPropertySourceLocator nacosPropertySourceLocator(
@ConditionalOnMissingBean
public NacosConfigManager nacosConfigManager(
NacosConfigProperties nacosConfigProperties) {
return new NacosPropertySourceLocator(nacosConfigProperties);
return new NacosConfigManager(nacosConfigProperties);
}
@Bean
public NacosPropertySourceLocator nacosPropertySourceLocator(
NacosConfigManager nacosConfigManager) {
return new NacosPropertySourceLocator(nacosConfigManager);
}
}
/*
* Copyright 2013-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
*
* https://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.timeloit.cloud.nacos;
import java.util.Objects;
import com.timeloit.cloud.nacos.diagnostics.analyzer.NacosConnectionFailureException;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author zkzlx
*/
public class NacosConfigManager {
private static final Logger log = LoggerFactory.getLogger(NacosConfigManager.class);
private static ConfigService service = null;
private NacosConfigProperties nacosConfigProperties;
public NacosConfigManager(NacosConfigProperties nacosConfigProperties) {
this.nacosConfigProperties = nacosConfigProperties;
// Compatible with older code in NacosConfigProperties,It will be deleted in the
// future.
createConfigService(nacosConfigProperties);
}
/**
* Compatible with old design,It will be perfected in the future.
*/
static ConfigService createConfigService(
NacosConfigProperties nacosConfigProperties) {
if (Objects.isNull(service)) {
synchronized (NacosConfigManager.class) {
try {
if (Objects.isNull(service)) {
service = NacosFactory.createConfigService(
nacosConfigProperties.assembleConfigServiceProperties());
}
}
catch (NacosException e) {
log.error(e.getMessage());
throw new NacosConnectionFailureException(
nacosConfigProperties.getServerAddr(), e.getMessage(), e);
}
}
}
return service;
}
public ConfigService getConfigService() {
if (Objects.isNull(service)) {
createConfigService(this.nacosConfigProperties);
}
return service;
}
public NacosConfigProperties getNacosConfigProperties() {
return nacosConfigProperties;
}
}
/*
* Copyright (C) 2018 the original author or authors.
* Copyright 2013-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
* https://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,
......@@ -16,37 +16,68 @@
package com.timeloit.cloud.nacos;
import com.timeloit.cloud.nacos.client.NacosPropertySource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import com.timeloit.cloud.nacos.client.NacosPropertySource;
/**
* @author xiaojing
* @author pbting
*/
public class NacosPropertySourceRepository {
public final class NacosPropertySourceRepository {
private final static ConcurrentHashMap<String, NacosPropertySource> NACOS_PROPERTY_SOURCE_REPOSITORY = new ConcurrentHashMap<>();
private NacosPropertySourceRepository() {
}
/**
* @return all nacos properties from application context
* @return all nacos properties from application context.
*/
public static List<NacosPropertySource> getAll() {
List<NacosPropertySource> result = new ArrayList<>();
result.addAll(NACOS_PROPERTY_SOURCE_REPOSITORY.values());
return result;
return new ArrayList<>(NACOS_PROPERTY_SOURCE_REPOSITORY.values());
}
/**
* recommend to use {@link NacosPropertySourceRepository#collectNacosPropertySource}.
* @param nacosPropertySource nacosPropertySource
*/
@Deprecated
public static void collectNacosPropertySources(
NacosPropertySource nacosPropertySource) {
NACOS_PROPERTY_SOURCE_REPOSITORY.putIfAbsent(nacosPropertySource.getDataId(),
nacosPropertySource);
}
/**
* recommend to use
* {@link NacosPropertySourceRepository#getNacosPropertySource(java.lang.String, java.lang.String)}.
* @param dataId dataId
* @return NacosPropertySource
*/
@Deprecated
public static NacosPropertySource getNacosPropertySource(String dataId) {
return NACOS_PROPERTY_SOURCE_REPOSITORY.get(dataId);
}
public static void collectNacosPropertySource(
NacosPropertySource nacosPropertySource) {
NACOS_PROPERTY_SOURCE_REPOSITORY
.putIfAbsent(getMapKey(nacosPropertySource.getDataId(),
nacosPropertySource.getGroup()), nacosPropertySource);
}
public static NacosPropertySource getNacosPropertySource(String dataId,
String group) {
return NACOS_PROPERTY_SOURCE_REPOSITORY.get(getMapKey(dataId, group));
}
public static String getMapKey(String dataId, String group) {
return String.join(NacosConfigProperties.COMMAS, String.valueOf(dataId),
String.valueOf(group));
}
}
/*
* Copyright (C) 2018 the original author or authors.
* Copyright 2013-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
* https://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,
......@@ -19,6 +19,8 @@ package com.timeloit.cloud.nacos.client;
import java.util.Date;
import java.util.Map;
import com.timeloit.cloud.nacos.NacosConfigProperties;
import org.springframework.core.env.MapPropertySource;
/**
......@@ -28,28 +30,28 @@ import org.springframework.core.env.MapPropertySource;
public class NacosPropertySource extends MapPropertySource {
/**
* Nacos Group
* Nacos Group.
*/
private final String group;
/**
* Nacos dataID
* Nacos dataID.
*/
private final String dataId;
/**
* timestamp the property get
* timestamp the property get.
*/
private final Date timestamp;
/**
* Whether to support dynamic refresh for this Property Source
* Whether to support dynamic refresh for this Property Source.
*/
private final boolean isRefreshable;
NacosPropertySource(String group, String dataId, Map<String, Object> source,
Date timestamp, boolean isRefreshable) {
super(dataId, source);
super(String.join(NacosConfigProperties.COMMAS, dataId, group), source);
this.group = group;
this.dataId = dataId;
this.timestamp = timestamp;
......@@ -71,4 +73,5 @@ public class NacosPropertySource extends MapPropertySource {
public boolean isRefreshable() {
return isRefreshable;
}
}
/*
* Copyright (C) 2018 the original author or authors.
* Copyright 2013-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
* https://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,
......@@ -16,33 +16,32 @@
package com.timeloit.cloud.nacos.client;
import java.io.StringReader;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties;
import com.timeloit.cloud.nacos.NacosPropertySourceRepository;
import com.timeloit.cloud.nacos.parser.NacosDataParserHandler;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
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.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import org.springframework.util.StringUtils;
/**
* @author xiaojing
* @author pbting
*/
public class NacosPropertySourceBuilder {
private static final Logger log = LoggerFactory
.getLogger(NacosPropertySourceBuilder.class);
private static final Properties EMPTY_PROPERTIES = new Properties();
private static final Map<String, Object> EMPTY_MAP = new LinkedHashMap();
private ConfigService configService;
private long timeout;
public NacosPropertySourceBuilder(ConfigService configService, long timeout) {
......@@ -72,35 +71,32 @@ public class NacosPropertySourceBuilder {
*/
NacosPropertySource build(String dataId, String group, String fileExtension,
boolean isRefreshable) {
Properties p = loadNacosData(dataId, group, fileExtension);
Map<String, Object> p = loadNacosData(dataId, group, fileExtension);
NacosPropertySource nacosPropertySource = new NacosPropertySource(group, dataId,
propertiesToMap(p), new Date(), isRefreshable);
NacosPropertySourceRepository.collectNacosPropertySources(nacosPropertySource);
p, new Date(), isRefreshable);
NacosPropertySourceRepository.collectNacosPropertySource(nacosPropertySource);
return nacosPropertySource;
}
private Properties loadNacosData(String dataId, String group, String fileExtension) {
private Map<String, Object> loadNacosData(String dataId, String group,
String fileExtension) {
String data = null;
try {
data = configService.getConfig(dataId, group, timeout);
if (!StringUtils.isEmpty(data)) {
log.info(String.format("Loading nacos data, dataId: '%s', group: '%s'",
dataId, group));
if (fileExtension.equalsIgnoreCase("properties")) {
Properties properties = new Properties();
properties.load(new StringReader(data));
return properties;
if (StringUtils.isEmpty(data)) {
log.warn(
"Ignore the empty nacos configuration and get it based on dataId[{}] & group[{}]",
dataId, group);
return EMPTY_MAP;
}
else if (fileExtension.equalsIgnoreCase("yaml")
|| fileExtension.equalsIgnoreCase("yml")) {
YamlPropertiesFactoryBean yamlFactory = new YamlPropertiesFactoryBean();
yamlFactory.setResources(new ByteArrayResource(data.getBytes()));
return yamlFactory.getObject();
}
if (log.isDebugEnabled()) {
log.debug(String.format(
"Loading nacos data, dataId: '%s', group: '%s', data: %s", dataId,
group, data));
}
Map<String, Object> dataMap = NacosDataParserHandler.getInstance()
.parseNacosData(data, fileExtension);
return dataMap == null ? EMPTY_MAP : dataMap;
}
catch (NacosException e) {
log.error("get data from Nacos error,dataId:{}, ", dataId, e);
......@@ -108,24 +104,7 @@ public class NacosPropertySourceBuilder {
catch (Exception e) {
log.error("parse data from Nacos error,dataId:{},data:{},", dataId, data, e);
}
return EMPTY_PROPERTIES;
}
@SuppressWarnings("unchecked")
private Map<String, Object> propertiesToMap(Properties properties) {
Map<String, Object> result = new HashMap<>(16);
Enumeration<String> keys = (Enumeration<String>) properties.propertyNames();
while (keys.hasMoreElements()) {
String key = keys.nextElement();
Object value = properties.getProperty(key);
if (value != null) {
result.put(key, ((String) value).trim());
}
else {
result.put(key, null);
}
}
return result;
return EMPTY_MAP;
}
}
/*
* Copyright (C) 2018 the original author or authors.
* Copyright 2013-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
* https://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,
......@@ -31,7 +31,10 @@ public class NacosConnectionFailureAnalyzer
@Override
protected FailureAnalysis analyze(Throwable rootFailure,
NacosConnectionFailureException cause) {
return new FailureAnalysis("Application failed to connect to Nacos server",
"check your nacos server config", cause);
return new FailureAnalysis(
"Application failed to connect to Nacos server: \""
+ cause.getServerAddr() + "\"",
"Please check your Nacos server config", cause);
}
}
/*
* Copyright (C) 2018 the original author or authors.
* Copyright 2013-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
* https://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,
......@@ -24,29 +24,21 @@ package com.timeloit.cloud.nacos.diagnostics.analyzer;
*/
public class NacosConnectionFailureException extends RuntimeException {
private final String domain;
private final String serverAddr;
private final String port;
public NacosConnectionFailureException(String domain, String port, String message) {
public NacosConnectionFailureException(String serverAddr, String message) {
super(message);
this.domain = domain;
this.port = port;
this.serverAddr = serverAddr;
}
public NacosConnectionFailureException(String domain, String port, String message,
public NacosConnectionFailureException(String serverAddr, String message,
Throwable cause) {
super(message, cause);
this.domain = domain;
this.port = port;
}
String getDomain() {
return domain;
this.serverAddr = serverAddr;
}
String getPort() {
return port;
public String getServerAddr() {
return serverAddr;
}
}
/*
* Copyright (C) 2018 the original author or authors.
* Copyright 2013-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
* https://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,
......@@ -27,12 +27,13 @@ import com.timeloit.cloud.nacos.NacosConfigProperties;
import com.timeloit.cloud.nacos.NacosPropertySourceRepository;
import com.timeloit.cloud.nacos.client.NacosPropertySource;
import com.timeloit.cloud.nacos.refresh.NacosRefreshHistory;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.actuate.endpoint.annotation.ReadOperation;
/**
* Endpoint for Nacos, contains config data and refresh history
* Endpoint for Nacos, contains config data and refresh history.
*
* @author xiaojing
*/
@Endpoint(id = "nacos-config")
......@@ -42,12 +43,8 @@ public class NacosConfigEndpoint {
private final NacosRefreshHistory refreshHistory;
private ThreadLocal<DateFormat> dateFormat = new ThreadLocal<DateFormat>() {
@Override
protected DateFormat initialValue() {
return 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) {
......@@ -74,4 +71,5 @@ public class NacosConfigEndpoint {
return result;
}
}
/*
* Copyright (C) 2018 the original author or authors.
* Copyright 2013-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
* https://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,
......@@ -16,10 +16,12 @@
package com.timeloit.cloud.nacos.endpoint;
import com.timeloit.cloud.nacos.NacosConfigProperties;
import com.timeloit.cloud.nacos.NacosConfigManager;
import com.timeloit.cloud.nacos.refresh.NacosRefreshHistory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.autoconfigure.endpoint.condition.ConditionalOnEnabledEndpoint;
import org.springframework.boot.actuate.autoconfigure.health.ConditionalOnEnabledHealthIndicator;
import org.springframework.boot.actuate.endpoint.annotation.Endpoint;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
......@@ -27,17 +29,16 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Bean;
/**
* @author xiaojing
*/
@ConditionalOnWebApplication
@ConditionalOnClass(value = Endpoint.class)
@ConditionalOnClass(Endpoint.class)
@ConditionalOnProperty(name = "spring.cloud.nacos.config.enabled", matchIfMissing = true)
public class NacosConfigEndpointAutoConfiguration {
@Autowired
private NacosConfigProperties nacosConfigProperties;
private NacosConfigManager nacosConfigManager;
@Autowired
private NacosRefreshHistory nacosRefreshHistory;
......@@ -46,12 +47,15 @@ public class NacosConfigEndpointAutoConfiguration {
@ConditionalOnEnabledEndpoint
@Bean
public NacosConfigEndpoint nacosConfigEndpoint() {
return new NacosConfigEndpoint(nacosConfigProperties, nacosRefreshHistory);
return new NacosConfigEndpoint(nacosConfigManager.getNacosConfigProperties(),
nacosRefreshHistory);
}
@Bean
@ConditionalOnMissingBean
@ConditionalOnEnabledHealthIndicator("nacos-config")
public NacosConfigHealthIndicator nacosConfigHealthIndicator() {
return new NacosConfigHealthIndicator(nacosConfigProperties,
nacosConfigProperties.configServiceInstance());
return new NacosConfigHealthIndicator(nacosConfigManager.getConfigService());
}
}
/*
* Copyright (C) 2018 the original author or authors.
* Copyright 2013-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
* https://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,
......@@ -16,58 +16,43 @@
package com.timeloit.cloud.nacos.endpoint;
import java.util.ArrayList;
import java.util.List;
import com.alibaba.nacos.api.config.ConfigService;
import com.timeloit.cloud.nacos.NacosConfigProperties;
import com.timeloit.cloud.nacos.NacosPropertySourceRepository;
import com.timeloit.cloud.nacos.client.NacosPropertySource;
import org.springframework.boot.actuate.health.AbstractHealthIndicator;
import org.springframework.boot.actuate.health.Health;
import org.springframework.util.StringUtils;
import com.alibaba.nacos.api.config.ConfigService;
import org.springframework.boot.actuate.health.HealthIndicator;
/**
* The {@link HealthIndicator} for Nacos Config.
*
* @author xiaojing
* @author <a href="mailto:mercyblitz@gmail.com">Mercy</a>
*/
public class NacosConfigHealthIndicator extends AbstractHealthIndicator {
private final NacosConfigProperties nacosConfigProperties;
private final List<String> dataIds;
private final ConfigService configService;
public NacosConfigHealthIndicator(NacosConfigProperties nacosConfigProperties,
ConfigService configService) {
this.nacosConfigProperties = nacosConfigProperties;
public NacosConfigHealthIndicator(ConfigService configService) {
this.configService = configService;
this.dataIds = new ArrayList<>();
for (NacosPropertySource nacosPropertySource : NacosPropertySourceRepository
.getAll()) {
this.dataIds.add(nacosPropertySource.getDataId());
}
}
@Override
protected void doHealthCheck(Health.Builder builder) throws Exception {
for (String dataId : dataIds) {
try {
String config = configService.getConfig(dataId,
nacosConfigProperties.getGroup(),
nacosConfigProperties.getTimeout());
if (StringUtils.isEmpty(config)) {
builder.down().withDetail(String.format("dataId: '%s', group: '%s'",
dataId, nacosConfigProperties.getGroup()), "config is empty");
}
// Just return "UP" or "DOWN"
String status = configService.getServerStatus();
// Set the status to Builder
builder.status(status);
switch (status) {
case "UP":
builder.up();
break;
case "DOWN":
builder.down();
break;
default:
builder.unknown();
break;
}
catch (Exception e) {
builder.down().withDetail(String.format("dataId: '%s', group: '%s'",
dataId, nacosConfigProperties.getGroup()), e.getMessage());
}
}
builder.up().withDetail("dataIds", dataIds);
}
}
/*
* Copyright 2013-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
*
* https://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.timeloit.cloud.nacos.parser;
import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import org.springframework.util.StringUtils;
/**
* @author zkz
*/
public abstract class AbstractNacosDataParser {
protected static final String DOT = ".";
protected static final String VALUE = "value";
protected static final String EMPTY_STRING = "";
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 dataId extensions.
* @param extension file extension. json or xml or yml or yaml or properties
* @return valid or not
*/
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.
* @param data config data from Nacos
* @param extension file extension. json or xml or yml or yaml or properties
* @return result of Properties
* @throws IOException thrown if there is a problem parsing config.
*/
public final Map<String, Object> 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.
* @param data config from Nacos
* @return result of Properties
* @throws IOException thrown if there is a problem parsing config.
*/
protected abstract Map<String, Object> doParse(String data) throws IOException;
protected AbstractNacosDataParser setNextParser(AbstractNacosDataParser nextParser) {
this.nextParser = nextParser;
return this;
}
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);
}
protected void flattenedMap(Map<String, Object> result, Map<String, Object> dataMap,
String parentKey) {
Set<Map.Entry<String, Object>> entries = dataMap.entrySet();
for (Iterator<Map.Entry<String, Object>> iterator = entries.iterator(); iterator
.hasNext();) {
Map.Entry<String, Object> entry = iterator.next();
String key = entry.getKey();
Object value = entry.getValue();
String fullKey = StringUtils.isEmpty(parentKey) ? key : key.startsWith("[")
? parentKey.concat(key) : parentKey.concat(DOT).concat(key);
if (value instanceof Map) {
Map<String, Object> map = (Map<String, Object>) value;
flattenedMap(result, map, fullKey);
continue;
}
else if (value instanceof Collection) {
int count = 0;
Collection<Object> collection = (Collection<Object>) value;
for (Object object : collection) {
flattenedMap(result,
Collections.singletonMap("[" + (count++) + "]", object),
fullKey);
}
continue;
}
result.put(fullKey, value);
}
}
/**
* Reload the key ending in `value` if need.
*/
protected Map<String, Object> reloadMap(Map<String, Object> map) {
if (map == null || map.isEmpty()) {
return null;
}
Map<String, Object> result = new LinkedHashMap<>(map);
for (Map.Entry<String, Object> 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);
}
}
/*
* Copyright 2013-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
*
* https://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.timeloit.cloud.nacos.parser;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
/**
* @author zkz
* @author yuhuangbin
*/
public class NacosDataJsonParser extends AbstractNacosDataParser {
protected NacosDataJsonParser() {
super("json");
}
@Override
protected Map<String, Object> doParse(String data) throws IOException {
if (StringUtils.isEmpty(data)) {
return null;
}
Map<String, Object> map = parseJSON2Map(data);
return this.reloadMap(map);
}
/**
* JSON to Map.
* @param json json data
* @return the map convert by json string
* @throws IOException thrown if there is a problem parsing config.
*/
private Map<String, Object> parseJSON2Map(String json) throws IOException {
Map<String, Object> result = new LinkedHashMap<>(32);
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> nacosDataMap = mapper.readValue(json, LinkedHashMap.class);
if (CollectionUtils.isEmpty(nacosDataMap)) {
return result;
}
flattenedMap(result, nacosDataMap, EMPTY_STRING);
return result;
}
}
/*
* Copyright 2013-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
*
* https://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.timeloit.cloud.nacos.parser;
import java.io.IOException;
import java.util.Map;
/**
* @author zkz
*/
public final class NacosDataParserHandler {
private AbstractNacosDataParser parser;
private NacosDataParserHandler() {
parser = this.createParser();
}
/**
* Parsing nacos configuration content.
* @param data config from Nacos
* @param extension file extension. json or xml or yml or yaml or properties
* @return result of LinkedHashMap
* @throws IOException thrown if there is a problem parsing config.
*/
public Map<String, Object> 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.
* @param dataIdAry array of dataId
* @return dataId handle success or not
*/
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 ParserHandler.HANDLER;
}
private static class ParserHandler {
private static final NacosDataParserHandler HANDLER = new NacosDataParserHandler();
}
}
/*
* Copyright 2013-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
*
* https://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.timeloit.cloud.nacos.parser;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.LinkedHashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
/**
* @author zkz
*/
public class NacosDataPropertiesParser extends AbstractNacosDataParser {
private static final Logger log = LoggerFactory
.getLogger(NacosDataPropertiesParser.class);
public NacosDataPropertiesParser() {
super("properties");
}
@Override
protected Map<String, Object> doParse(String data) throws IOException {
Map<String, Object> result = new LinkedHashMap<>();
try (BufferedReader reader = new BufferedReader(new StringReader(data))) {
for (String line = reader.readLine(); line != null; line = reader
.readLine()) {
String dataLine = line.trim();
if (StringUtils.isEmpty(dataLine) || dataLine.startsWith("#")) {
continue;
}
int index = dataLine.indexOf("=");
if (index == -1) {
log.warn("the config data is invalid {}", dataLine);
continue;
}
result.put(dataLine.substring(0, index), dataLine.substring(index + 1));
}
}
return result;
}
}
/*
* Copyright 2013-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
*
* https://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.timeloit.cloud.nacos.parser;
import java.io.IOException;
import java.io.StringReader;
import java.util.LinkedHashMap;
import java.util.Map;
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 org.springframework.util.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 Map<String, Object> doParse(String data) throws IOException {
if (StringUtils.isEmpty(data)) {
return null;
}
Map<String, Object> map = parseXml2Map(data);
return this.reloadMap(map);
}
private Map<String, Object> parseXml2Map(String xml) throws IOException {
xml = xml.replaceAll("\\r", "").replaceAll("\\n", "").replaceAll("\\t", "");
Map<String, Object> map = new LinkedHashMap<>(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, Object> 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, Object> 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());
}
}
}
}
/*
* Copyright 2013-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
*
* https://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.timeloit.cloud.nacos.parser;
import java.util.LinkedHashMap;
import java.util.Map;
import org.springframework.beans.factory.config.YamlMapFactoryBean;
import org.springframework.core.io.ByteArrayResource;
/**
* @author zkz
*/
public class NacosDataYamlParser extends AbstractNacosDataParser {
public NacosDataYamlParser() {
super(",yml,yaml,");
}
@Override
protected Map<String, Object> doParse(String data) {
YamlMapFactoryBean yamlFactory = new YamlMapFactoryBean();
yamlFactory.setResources(new ByteArrayResource(data.getBytes()));
Map<String, Object> result = new LinkedHashMap<>();
flattenedMap(result, yamlFactory.getObject(), EMPTY_STRING);
return result;
}
}
/*
* Copyright (C) 2018 the original author or authors.
* Copyright 2013-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
* https://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,
......@@ -16,30 +16,27 @@
package com.timeloit.cloud.nacos.refresh;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import com.timeloit.cloud.nacos.NacosConfigManager;
import com.timeloit.cloud.nacos.NacosConfigProperties;
import com.timeloit.cloud.nacos.NacosPropertySourceRepository;
import com.timeloit.cloud.nacos.client.NacosPropertySource;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.AbstractSharedListener;
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.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
......@@ -57,9 +54,11 @@ public class NacosContextRefresher
private static final AtomicLong REFRESH_COUNT = new AtomicLong(0);
private final NacosRefreshProperties refreshProperties;
private NacosConfigProperties nacosConfigProperties;
private final boolean isRefreshEnabled;
private final NacosRefreshHistory refreshHistory;
private final NacosRefreshHistory nacosRefreshHistory;
private final ConfigService configService;
......@@ -69,10 +68,26 @@ public class NacosContextRefresher
private Map<String, Listener> listenerMap = new ConcurrentHashMap<>(16);
public NacosContextRefresher(NacosConfigManager nacosConfigManager,
NacosRefreshHistory refreshHistory) {
this.nacosConfigProperties = nacosConfigManager.getNacosConfigProperties();
this.nacosRefreshHistory = refreshHistory;
this.configService = nacosConfigManager.getConfigService();
this.isRefreshEnabled = this.nacosConfigProperties.isRefreshEnabled();
}
/**
* recommend to use
* {@link NacosContextRefresher#NacosContextRefresher(NacosConfigManager, NacosRefreshHistory)}.
* @param refreshProperties refreshProperties
* @param refreshHistory refreshHistory
* @param configService configService
*/
@Deprecated
public NacosContextRefresher(NacosRefreshProperties refreshProperties,
NacosRefreshHistory refreshHistory, ConfigService configService) {
this.refreshProperties = refreshProperties;
this.refreshHistory = refreshHistory;
this.isRefreshEnabled = refreshProperties.isEnabled();
this.nacosRefreshHistory = refreshHistory;
this.configService = configService;
}
......@@ -89,58 +104,70 @@ public class NacosContextRefresher
this.applicationContext = applicationContext;
}
/**
* register Nacos Listeners.
*/
private void registerNacosListenersForApplications() {
if (refreshProperties.isEnabled()) {
for (NacosPropertySource nacosPropertySource : NacosPropertySourceRepository
if (isRefreshEnabled()) {
for (NacosPropertySource propertySource : NacosPropertySourceRepository
.getAll()) {
if (!nacosPropertySource.isRefreshable()) {
if (!propertySource.isRefreshable()) {
continue;
}
String dataId = nacosPropertySource.getDataId();
registerNacosListener(nacosPropertySource.getGroup(), dataId);
String dataId = propertySource.getDataId();
registerNacosListener(propertySource.getGroup(), dataId);
}
}
}
private void registerNacosListener(final String group, final String dataId) {
Listener listener = listenerMap.computeIfAbsent(dataId, i -> new Listener() {
private void registerNacosListener(final String groupKey, final String dataKey) {
String key = NacosPropertySourceRepository.getMapKey(dataKey, groupKey);
Listener listener = listenerMap.computeIfAbsent(key,
lst -> new AbstractSharedListener() {
@Override
public void receiveConfigInfo(String configInfo) {
public void innerReceive(String dataId, String group,
String configInfo) {
refreshCountIncrement();
String md5 = "";
if (!StringUtils.isEmpty(configInfo)) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md5 = new BigInteger(1, md.digest(configInfo.getBytes("UTF-8")))
.toString(16);
}
catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
log.warn("[Nacos] unable to get md5 for dataId: " + dataId, e);
}
}
refreshHistory.add(dataId, md5);
nacosRefreshHistory.addRefreshRecord(dataId, group, configInfo);
// todo feature: support single refresh for listening
applicationContext.publishEvent(
new RefreshEvent(this, null, "Refresh Nacos config"));
if (log.isDebugEnabled()) {
log.debug("Refresh Nacos config group " + group + ",dataId" + dataId);
}
log.debug(String.format(
"Refresh Nacos config group=%s,dataId=%s,configInfo=%s",
group, dataId, configInfo));
}
@Override
public Executor getExecutor() {
return null;
}
});
try {
configService.addListener(dataId, group, listener);
configService.addListener(dataKey, groupKey, listener);
}
catch (NacosException e) {
e.printStackTrace();
log.warn(String.format(
"register fail for nacos listener ,dataId=[%s],group=[%s]", dataKey,
groupKey), e);
}
}
public NacosConfigProperties getNacosConfigProperties() {
return nacosConfigProperties;
}
public NacosContextRefresher setNacosConfigProperties(
NacosConfigProperties nacosConfigProperties) {
this.nacosConfigProperties = nacosConfigProperties;
return this;
}
public boolean isRefreshEnabled() {
if (null == nacosConfigProperties) {
return isRefreshEnabled;
}
// Compatible with older configurations
if (nacosConfigProperties.isRefreshEnabled() && !isRefreshEnabled) {
return false;
}
return isRefreshEnabled;
}
public static long getRefreshCount() {
......@@ -150,4 +177,5 @@ public class NacosContextRefresher
public static void refreshCountIncrement() {
REFRESH_COUNT.incrementAndGet();
}
}
/*
* Copyright (C) 2018 the original author or authors.
* Copyright 2013-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
* https://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,
......@@ -16,26 +16,61 @@
package com.timeloit.cloud.nacos.refresh;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
public class NacosRefreshHistory {
private final static Logger log = LoggerFactory.getLogger(NacosRefreshHistory.class);
private static final int MAX_SIZE = 20;
private LinkedList<Record> records = new LinkedList<>();
private final LinkedList<Record> records = new LinkedList<>();
private final ThreadLocal<DateFormat> DATE_FORMAT = ThreadLocal
.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
private ThreadLocal<DateFormat> dateFormat = new ThreadLocal<DateFormat>() {
@Override
protected DateFormat initialValue() {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private MessageDigest md;
public NacosRefreshHistory() {
try {
md = MessageDigest.getInstance("MD5");
}
catch (NoSuchAlgorithmException e) {
log.error("failed to initialize MessageDigest : ", e);
}
}
};
/**
* recommend to use
* {@link NacosRefreshHistory#addRefreshRecord(java.lang.String, java.lang.String, java.lang.String)}.
* @param dataId dataId
* @param md5 md5
*/
@Deprecated
public void add(String dataId, String md5) {
records.addFirst(new Record(dateFormat.get().format(new Date()), dataId, md5));
records.addFirst(
new Record(DATE_FORMAT.get().format(new Date()), dataId, "", md5, null));
if (records.size() > MAX_SIZE) {
records.removeLast();
}
}
public void addRefreshRecord(String dataId, String group, String data) {
records.addFirst(new Record(DATE_FORMAT.get().format(new Date()), dataId, group,
md5(data), null));
if (records.size() > MAX_SIZE) {
records.removeLast();
}
......@@ -44,19 +79,38 @@ public class NacosRefreshHistory {
public LinkedList<Record> getRecords() {
return records;
}
}
class Record {
private String md5(String data) {
if (StringUtils.isEmpty(data)) {
return null;
}
if (null == md) {
try {
md = MessageDigest.getInstance("MD5");
}
catch (NoSuchAlgorithmException ignored) {
return "unable to get md5";
}
}
return new BigInteger(1, md.digest(data.getBytes(StandardCharsets.UTF_8)))
.toString(16);
}
static class Record {
private final String timestamp;
private final String dataId;
private final String group;
private final String md5;
public Record(String timestamp, String dataId, String md5) {
Record(String timestamp, String dataId, String group, String md5,
Map<String, Object> last) {
this.timestamp = timestamp;
this.dataId = dataId;
this.group = group;
this.md5 = md5;
}
......@@ -68,7 +122,14 @@ class Record {
return dataId;
}
public String getGroup() {
return group;
}
public String getMd5() {
return md5;
}
}
}
/*
* Copyright (C) 2018 the original author or authors.
* Copyright 2013-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
* https://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,
......@@ -16,15 +16,22 @@
package com.timeloit.cloud.nacos.refresh;
import com.timeloit.cloud.nacos.NacosConfigProperties;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* @author xiaojing
*/
@Deprecated
@Component
public class NacosRefreshProperties {
/**
* recommend to use {@code NacosConfigProperties#refreshEnabled}
* {@link NacosConfigProperties#setRefreshEnabled(boolean)}.
*/
@Value("${spring.cloud.nacos.config.refresh.enabled:true}")
private boolean enabled = true;
......@@ -35,4 +42,5 @@ public class NacosRefreshProperties {
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
}
{
"properties": [
{
"name": "spring.cloud.nacos.server-addr",
"type": "java.lang.String",
"defaultValue": "localhost:8848",
"description": "nacos server address."
},
{
"name": "spring.cloud.nacos.config.server-addr",
"type": "java.lang.String",
"defaultValue": "${spring.cloud.nacos.server-addr}",
"description": "nacos config server address."
},
{
"name": "spring.cloud.nacos.config.encode",
"type": "java.lang.String",
......@@ -23,21 +35,59 @@
"type": "java.lang.String",
"description": "the dataids for configurable multiple shared configurations , multiple separated by commas ."
},
{
"name": "spring.cloud.nacos.config.shared-configs",
"type": "java.util.List",
"description": "a set of shared configurations .e.g: spring.cloud.nacos.config.shared-configs[0]=xxx ."
},
{
"name": "spring.cloud.nacos.config.refreshable-dataids",
"type": "java.lang.String",
"description": "refreshable dataids , multiple separated by commas ."
"description": "refreshable dataids , multiple separated by commas .Not providing support,the need to refresh is specified by the respective refresh configuration."
},
{
"name": "spring.cloud.nacos.config.ext-config",
"type": "java.util.List",
"description": "a set of extended configurations ."
},
{
"name": "spring.cloud.nacos.config.extension-configs",
"type": "java.util.List",
"description": "a set of extensional configurations .e.g: spring.cloud.nacos.config.extension-configs[0]=xxx ."
},
{
"name": "spring.cloud.nacos.config.refresh-enabled",
"type": "java.lang.Boolean",
"defaultValue": true,
"description": "the master switch for refresh configuration, it default opened(true)."
},
{
"name": "spring.cloud.nacos.config.enabled",
"type": "java.lang.Boolean",
"defaultValue": true,
"description": "enable nacos config or not."
},
{
"name": "spring.cloud.nacos.config.username",
"type": "java.lang.String",
"defaultValue": "${spring.cloud.nacos.username}",
"description": "nacos config service's userName to authenticate."
},
{
"name": "spring.cloud.nacos.config.password",
"type": "java.lang.String",
"defaultValue": "${spring.cloud.nacos.password}",
"description": "nacos config service's password to authenticate."
},
{
"name": "spring.cloud.nacos.username",
"type": "java.lang.String",
"description": "nacos userName to authenticate."
},
{
"name": "spring.cloud.nacos.password",
"type": "java.lang.String",
"description": "nacos password to authenticate."
}
]
}
\ No newline at end of file
/*
* 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.timeloit.cloud.nacos;
import static org.junit.Assert.assertNotNull;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import com.timeloit.cloud.nacos.client.NacosPropertySourceLocator;
import com.timeloit.cloud.nacos.endpoint.NacosConfigEndpointAutoConfiguration;
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 com.alibaba.nacos.client.config.NacosConfigService;
/**
* @author xiaojing
*/
@RunWith(PowerMockRunner.class)
@PowerMockIgnore("javax.management.*")
@PowerMockRunnerDelegate(SpringRunner.class)
@PrepareForTest({ NacosConfigService.class })
@SpringBootTest(classes = NacosConfigurationExtConfigTests.TestConfig.class, properties = {
"spring.application.name=myTestService1", "spring.profiles.active=dev,test",
"spring.cloud.nacos.config.server-addr=127.0.0.1:8848",
"spring.cloud.nacos.config.encode=utf-8",
"spring.cloud.nacos.config.timeout=1000",
"spring.cloud.nacos.config.file-extension=properties",
"spring.cloud.nacos.config.ext-config[0].data-id=ext-config-common01.properties",
"spring.cloud.nacos.config.ext-config[1].data-id=ext-config-common02.properties",
"spring.cloud.nacos.config.ext-config[1].group=GLOBAL_GROUP",
"spring.cloud.nacos.config.shared-dataids=common1.properties,common2.properties",
"spring.cloud.nacos.config.accessKey=test-accessKey",
"spring.cloud.nacos.config.secretKey=test-secretKey" }, webEnvironment = NONE)
public class NacosConfigurationExtConfigTests {
static {
try {
// when(any(ConfigService.class).getConfig(eq("test-name.properties"),
// eq("test-group"), any())).thenReturn("user.name=hello");
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 ("test-name.properties".equals(args[0])
&& "DEFAULT_GROUP".equals(args[1])) {
return "user.name=hello\nuser.age=12";
}
if ("test-name-dev.properties".equals(args[0])
&& "DEFAULT_GROUP".equals(args[1])) {
return "user.name=dev";
}
if ("ext-config-common01.properties".equals(args[0])
&& "DEFAULT_GROUP".equals(args[1])) {
return "test-ext-config1=config1\ntest-ext-config2=config1";
}
if ("ext-config-common02.properties".equals(args[0])
&& "GLOBAL_GROUP".equals(args[1])) {
return "test-ext-config2=config2";
}
if ("common1.properties".equals(args[0])
&& "DEFAULT_GROUP".equals(args[1])) {
return "test-common1=common1\ntest-common2=common1";
}
if ("common2.properties".equals(args[0])
&& "DEFAULT_GROUP".equals(args[1])) {
return "test-common2=common2";
}
return "";
}
});
}
catch (Exception ignore) {
ignore.printStackTrace();
}
}
@Autowired
private Environment environment;
@Autowired
private NacosPropertySourceLocator locator;
@Autowired
private NacosConfigProperties properties;
@Test
public void contextLoads() throws Exception {
assertNotNull("NacosPropertySourceLocator was not created", locator);
assertNotNull("NacosConfigProperties was not created", properties);
Assert.assertEquals(environment.getProperty("test-ext-config1"), "config1");
Assert.assertEquals(environment.getProperty("test-ext-config2"), "config2");
Assert.assertEquals(environment.getProperty("test-common1"), "common1");
Assert.assertEquals(environment.getProperty("test-common2"), "common2");
}
@Configuration
@EnableAutoConfiguration
@ImportAutoConfiguration({ NacosConfigEndpointAutoConfiguration.class,
NacosConfigAutoConfiguration.class, NacosConfigBootstrapConfiguration.class })
public static class TestConfig {
}
}
/*
* 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.timeloit.cloud.nacos;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Map;
import com.timeloit.cloud.nacos.client.NacosPropertySourceLocator;
import com.timeloit.cloud.nacos.endpoint.NacosConfigEndpoint;
import com.timeloit.cloud.nacos.endpoint.NacosConfigEndpointAutoConfiguration;
import com.timeloit.cloud.nacos.refresh.NacosRefreshHistory;
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 com.alibaba.nacos.client.config.NacosConfigService;
/**
* @author xiaojing
*/
@RunWith(PowerMockRunner.class)
@PowerMockIgnore("javax.management.*")
@PowerMockRunnerDelegate(SpringRunner.class)
@PrepareForTest({ NacosConfigService.class })
@SpringBootTest(classes = NacosConfigurationTests.TestConfig.class, properties = {
"spring.application.name=myTestService1", "spring.profiles.active=dev,test",
"spring.cloud.nacos.config.server-addr=192.168.66.40: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=properties",
"spring.cloud.nacos.config.contextPath=test-contextpath",
"spring.cloud.nacos.config.ext-config[0].data-id=ext-config-common01.properties",
"spring.cloud.nacos.config.ext-config[1].data-id=ext-config-common02.properties",
"spring.cloud.nacos.config.ext-config[1].group=GLOBAL_GROUP",
"spring.cloud.nacos.config.shared-dataids=common1.properties,common2.properties",
"spring.cloud.nacos.config.accessKey=test-accessKey",
"spring.cloud.nacos.config.secretKey=test-secretKey" }, webEnvironment = NONE)
public class NacosConfigurationTests {
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 ("test-name.properties".equals(args[0])
&& "test-group".equals(args[1])) {
return "user.name=hello\nuser.age=12";
}
if ("test-name-dev.properties".equals(args[0])
&& "test-group".equals(args[1])) {
return "user.name=dev";
}
if ("ext-config-common01.properties".equals(args[0])
&& "DEFAULT_GROUP".equals(args[1])) {
return "test-ext-config1=config1\ntest-ext-config2=config1";
}
if ("ext-config-common02.properties".equals(args[0])
&& "GLOBAL_GROUP".equals(args[1])) {
return "test-ext-config2=config2";
}
if ("common1.properties".equals(args[0])
&& "DEFAULT_GROUP".equals(args[1])) {
return "test-common1=common1\ntest-common2=common1";
}
if ("common2.properties".equals(args[0])
&& "DEFAULT_GROUP".equals(args[1])) {
return "test-common2=common2";
}
return "";
}
});
}
catch (Exception ignore) {
ignore.printStackTrace();
}
}
@Autowired
private Environment environment;
@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();
checkoutDataLoad();
}
private void checkoutNacosConfigServerAddr() {
assertEquals("NacosConfigProperties server address is wrong", "192.168.66.40: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", "properties",
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 checkoutDataLoad() {
Assert.assertEquals("dev", environment.getProperty("user.name"));
Assert.assertEquals("12", environment.getProperty("user.age"));
}
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 {
}
}
/*
* 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.timeloit.cloud.nacos.endpoint;
import static org.junit.Assert.assertEquals;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.timeloit.cloud.nacos.NacosConfigAutoConfiguration;
import com.timeloit.cloud.nacos.NacosConfigBootstrapConfiguration;
import com.timeloit.cloud.nacos.NacosConfigProperties;
import com.timeloit.cloud.nacos.refresh.NacosRefreshHistory;
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.actuate.health.Health.Builder;
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.test.context.junit4.SpringRunner;
import com.alibaba.nacos.client.config.NacosConfigService;
/**
* @author xiaojing
*/
@RunWith(PowerMockRunner.class)
@PowerMockIgnore("javax.management.*")
@PowerMockRunnerDelegate(SpringRunner.class)
@PrepareForTest({ NacosConfigService.class })
@SpringBootTest(classes = NacosConfigEndpointTests.TestConfig.class, properties = {
"spring.application.name=test-name",
"spring.cloud.nacos.config.server-addr=192.168.66.40:8848",
"spring.cloud.nacos.config.file-extension=properties" }, webEnvironment = NONE)
public class NacosConfigEndpointTests {
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 ("test-name.properties".equals(args[0])
&& "DEFAULT_GROUP".equals(args[1])) {
return "user.name=hello\nuser.age=12";
}
return "";
}
});
}
catch (Exception ignore) {
ignore.printStackTrace();
}
}
@Autowired
private NacosConfigProperties properties;
@Autowired
private NacosRefreshHistory refreshHistory;
@Test
public void contextLoads() throws Exception {
checkoutEndpoint();
checkoutAcmHealthIndicator();
}
private void checkoutAcmHealthIndicator() {
try {
Builder builder = new Builder();
NacosConfigHealthIndicator healthIndicator = new NacosConfigHealthIndicator(
properties, properties.configServiceInstance());
healthIndicator.doHealthCheck(builder);
Builder builder1 = new Builder();
List<String> dataIds = new ArrayList<>();
dataIds.add("test-name.properties");
builder1.up().withDetail("dataIds", dataIds);
Assert.assertTrue(builder.build().equals(builder1.build()));
}
catch (Exception ignoreE) {
}
}
private void checkoutEndpoint() throws Exception {
NacosConfigEndpoint endpoint = new NacosConfigEndpoint(properties,
refreshHistory);
Map<String, Object> map = endpoint.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 {
}
}
/*
* Copyright 2013-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
*
* https://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.timeloit.cloud.nacos;
import com.timeloit.cloud.nacos.refresh.NacosContextRefresher;
import com.timeloit.cloud.nacos.refresh.NacosRefreshHistory;
import com.timeloit.cloud.nacos.refresh.NacosRefreshProperties;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author juven.xuxb
*/
@Configuration
@ConditionalOnProperty(name = "spring.cloud.nacos.config.enabled", matchIfMissing = true)
public class NacosConfigAutoConfiguration {
@Bean
public NacosConfigProperties nacosConfigProperties(ApplicationContext context) {
if (context.getParent() != null
&& BeanFactoryUtils.beanNamesForTypeIncludingAncestors(
context.getParent(), NacosConfigProperties.class).length > 0) {
return BeanFactoryUtils.beanOfTypeIncludingAncestors(context.getParent(),
NacosConfigProperties.class);
}
return new NacosConfigProperties();
}
@Bean
public NacosRefreshProperties nacosRefreshProperties() {
return new NacosRefreshProperties();
}
@Bean
public NacosRefreshHistory nacosRefreshHistory() {
return new NacosRefreshHistory();
}
@Bean
public NacosConfigManager nacosConfigManager(
NacosConfigProperties nacosConfigProperties) {
return new NacosConfigManager(nacosConfigProperties);
}
@Bean
public NacosContextRefresher nacosContextRefresher(
NacosConfigManager nacosConfigManager,
NacosRefreshHistory nacosRefreshHistory) {
// Consider that it is not necessary to be compatible with the previous
// configuration
// and use the new configuration if necessary.
return new NacosContextRefresher(nacosConfigManager, nacosRefreshHistory);
}
}
......@@ -14,48 +14,39 @@
* limitations under the License.
*/
package com.timeloit.cloud.seata;
package com.timeloit.cloud.nacos;
import io.seata.spring.annotation.GlobalTransactionScanner;
import com.timeloit.cloud.nacos.client.NacosPropertySourceLocator;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
/**
* @author xiaojing
*/
@Configuration
@EnableConfigurationProperties(SeataProperties.class)
public class GlobalTransactionAutoConfiguration {
private final ApplicationContext applicationContext;
@ConditionalOnProperty(name = "spring.cloud.nacos.config.enabled", matchIfMissing = true)
public class NacosConfigBootstrapConfiguration {
private final SeataProperties seataProperties;
public GlobalTransactionAutoConfiguration(ApplicationContext applicationContext,
SeataProperties seataProperties) {
this.applicationContext = applicationContext;
this.seataProperties = seataProperties;
@Bean
@ConditionalOnMissingBean
public NacosConfigProperties nacosConfigProperties() {
return new NacosConfigProperties();
}
@Bean
public GlobalTransactionScanner globalTransactionScanner() {
String applicationName = applicationContext.getEnvironment()
.getProperty("spring.application.name");
String txServiceGroup = seataProperties.getTxServiceGroup();
if (StringUtils.isEmpty(txServiceGroup)) {
txServiceGroup = applicationName + "-seata-service-group";
seataProperties.setTxServiceGroup(txServiceGroup);
@ConditionalOnMissingBean
public NacosConfigManager nacosConfigManager(
NacosConfigProperties nacosConfigProperties) {
return new NacosConfigManager(nacosConfigProperties);
}
return new GlobalTransactionScanner(applicationName, txServiceGroup);
@Bean
public NacosPropertySourceLocator nacosPropertySourceLocator(
NacosConfigManager nacosConfigManager) {
return new NacosPropertySourceLocator(nacosConfigManager);
}
}
/*
* Copyright 2013-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
*
* https://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.timeloit.cloud.nacos;
import java.util.Objects;
import com.timeloit.cloud.nacos.diagnostics.analyzer.NacosConnectionFailureException;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author zkzlx
*/
public class NacosConfigManager {
private static final Logger log = LoggerFactory.getLogger(NacosConfigManager.class);
private static ConfigService service = null;
private NacosConfigProperties nacosConfigProperties;
public NacosConfigManager(NacosConfigProperties nacosConfigProperties) {
this.nacosConfigProperties = nacosConfigProperties;
// Compatible with older code in NacosConfigProperties,It will be deleted in the
// future.
createConfigService(nacosConfigProperties);
}
/**
* Compatible with old design,It will be perfected in the future.
*/
static ConfigService createConfigService(
NacosConfigProperties nacosConfigProperties) {
if (Objects.isNull(service)) {
synchronized (NacosConfigManager.class) {
try {
if (Objects.isNull(service)) {
service = NacosFactory.createConfigService(
nacosConfigProperties.assembleConfigServiceProperties());
}
}
catch (NacosException e) {
log.error(e.getMessage());
throw new NacosConnectionFailureException(
nacosConfigProperties.getServerAddr(), e.getMessage(), e);
}
}
}
return service;
}
public ConfigService getConfigService() {
if (Objects.isNull(service)) {
createConfigService(this.nacosConfigProperties);
}
return service;
}
public NacosConfigProperties getNacosConfigProperties() {
return nacosConfigProperties;
}
}
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论