Merge pull request #124 from alibaba/0.2.2

0.2.2
This commit is contained in:
小马哥 2018-10-15 17:10:57 +08:00 committed by GitHub
commit e05bc7a682
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
141 changed files with 3750 additions and 4479 deletions

View File

@ -12,30 +12,46 @@
limitations under the License. limitations under the License.
--> -->
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent> <parent>
<groupId>com.alibaba.nacos</groupId> <groupId>com.alibaba.nacos</groupId>
<artifactId>nacos-all</artifactId> <artifactId>nacos-all</artifactId>
<version>0.2.1</version> <version>0.2.2-SNAPSHOT</version>
</parent> <relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>nacos-api</artifactId> <artifactId>nacos-api</artifactId>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>nacos-api ${project.version}</name> <name>nacos-api ${project.version}</name>
<url>http://maven.apache.org</url> <url>http://maven.apache.org</url>
<properties> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties> </properties>
<dependencies> <dependencies>
<dependency>
<groupId>com.alibaba</groupId> <dependency>
<artifactId>fastjson</artifactId> <groupId>com.alibaba</groupId>
</dependency> <artifactId>fastjson</artifactId>
</dependencies> </dependency>
<!-- Test -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project> </project>

View File

@ -1,53 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.client;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class AppTest
extends TestCase
{
/**
* Create the test case
*
* @param testName name of the test case
*/
public AppTest( String testName )
{
super( testName );
}
/**
* @return the suite of tests being tested
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
}
/**
* Rigourous Test :-)
*/
public void testApp()
{
assertTrue( true );
}
}

View File

@ -12,113 +12,101 @@
limitations under the License. limitations under the License.
--> -->
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent> <parent>
<groupId>com.alibaba.nacos</groupId> <groupId>com.alibaba.nacos</groupId>
<artifactId>nacos-all</artifactId> <artifactId>nacos-all</artifactId>
<version>0.2.1</version> <version>0.2.2-SNAPSHOT</version>
</parent> <relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>nacos-client</artifactId> <artifactId>nacos-client</artifactId>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>nacos-client ${project.version}</name> <name>nacos-client ${project.version}</name>
<url>http://maven.apache.org</url> <url>http://maven.apache.org</url>
<properties> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties> </properties>
<dependencies> <dependencies>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.8.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>nacos-common</artifactId>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>nacos-api</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
</dependency>
<dependency> <dependency>
<groupId>ch.qos.logback</groupId> <groupId>org.slf4j</groupId>
<artifactId>logback-classic</artifactId> <artifactId>slf4j-api</artifactId>
</dependency> <optional>true</optional>
<dependency> </dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
</dependency>
<dependency> <dependency>
<groupId>com.google.guava</groupId> <groupId>org.apache.logging.log4j</groupId>
<artifactId>guava</artifactId> <artifactId>log4j-core</artifactId>
</dependency> <version>2.8.2</version>
<optional>true</optional>
</dependency>
<dependency> <dependency>
<artifactId>commons-codec</artifactId> <groupId>org.apache.logging.log4j</groupId>
<groupId>commons-codec</groupId> <artifactId>log4j-slf4j-impl</artifactId>
</dependency> <optional>true</optional>
</dependency>
<dependency> <dependency>
<groupId>org.codehaus.jackson</groupId> <groupId>${project.groupId}</groupId>
<artifactId>jackson-mapper-lgpl</artifactId> <artifactId>nacos-common</artifactId>
</dependency> </dependency>
<dependency>
<groupId>net.jcip</groupId> <dependency>
<artifactId>jcip-annotations</artifactId> <groupId>${project.groupId}</groupId>
<optional>true</optional> <artifactId>nacos-api</artifactId>
</dependency> </dependency>
<dependency>
<groupId>com.github.spotbugs</groupId> <dependency>
<artifactId>spotbugs-annotations</artifactId> <groupId>ch.qos.logback</groupId>
<optional>true</optional> <artifactId>logback-classic</artifactId>
</dependency> <optional>true</optional>
</dependencies> </dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
<dependency>
<artifactId>commons-codec</artifactId>
<groupId>commons-codec</groupId>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-lgpl</artifactId>
</dependency>
<dependency>
<groupId>net.jcip</groupId>
<artifactId>jcip-annotations</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.github.spotbugs</groupId>
<artifactId>spotbugs-annotations</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project> </project>

View File

@ -15,16 +15,15 @@
*/ */
package com.alibaba.nacos.client.logger; package com.alibaba.nacos.client.logger;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import com.alibaba.nacos.client.logger.log4j.Log4jLoggerFactory;
import com.alibaba.nacos.client.logger.log4j2.Log4j2LoggerFactory; import com.alibaba.nacos.client.logger.log4j2.Log4j2LoggerFactory;
import com.alibaba.nacos.client.logger.nop.NopLoggerFactory; import com.alibaba.nacos.client.logger.nop.NopLoggerFactory;
import com.alibaba.nacos.client.logger.slf4j.Slf4jLoggerFactory; import com.alibaba.nacos.client.logger.slf4j.Slf4jLoggerFactory;
import com.alibaba.nacos.client.logger.support.ILoggerFactory; import com.alibaba.nacos.client.logger.support.ILoggerFactory;
import com.alibaba.nacos.client.logger.support.LogLog; import com.alibaba.nacos.client.logger.support.LogLog;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/** /**
* <pre> * <pre>
* 阿里中间件LoggerFactory获取具体日志实现 * 阿里中间件LoggerFactory获取具体日志实现
@ -57,17 +56,12 @@ public class LoggerFactory {
LogLog.info("Init JM logger with Slf4jLoggerFactory success, " + LoggerFactory.class.getClassLoader()); LogLog.info("Init JM logger with Slf4jLoggerFactory success, " + LoggerFactory.class.getClassLoader());
} catch (Throwable e1) { } catch (Throwable e1) {
try { try {
setLoggerFactory(new Log4jLoggerFactory()); setLoggerFactory(new Log4j2LoggerFactory());
LogLog.info("Init JM logger with Log4jLoggerFactory, " + LoggerFactory.class.getClassLoader()); LogLog.info("Init JM logger with Log4j2LoggerFactory, " + LoggerFactory.class.getClassLoader());
} catch (Throwable e2) { } catch (Throwable e2) {
try { setLoggerFactory(new NopLoggerFactory());
setLoggerFactory(new Log4j2LoggerFactory()); LogLog.warn("Init JM logger with NopLoggerFactory, pay attention. "
LogLog.info("Init JM logger with Log4j2LoggerFactory, " + LoggerFactory.class.getClassLoader()); + LoggerFactory.class.getClassLoader(), e2);
} catch (Throwable e3) {
setLoggerFactory(new NopLoggerFactory());
LogLog.warn("Init JM logger with NopLoggerFactory, pay attention. "
+ LoggerFactory.class.getClassLoader(), e2);
}
} }
} }

View File

@ -1,146 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.client.logger.log4j;
import org.apache.log4j.Level;
import com.alibaba.nacos.client.logger.Logger;
import com.alibaba.nacos.client.logger.option.Log4jActivateOption;
import com.alibaba.nacos.client.logger.support.LoggerHelper;
import com.alibaba.nacos.client.logger.support.LoggerSupport;
import com.alibaba.nacos.client.logger.util.MessageUtil;
/**
* Log4jLogger
* @author Nacos
*
*/
public class Log4jLogger extends LoggerSupport implements Logger {
private org.apache.log4j.Logger delegate;
public Log4jLogger(org.apache.log4j.Logger delegate) {
super(delegate);
if (delegate == null) {
throw new IllegalArgumentException("delegate Logger is null");
}
this.delegate = delegate;
this.activateOption = new Log4jActivateOption(delegate);
}
@Override
public void debug(String context, String message) {
if (isDebugEnabled()) {
message = LoggerHelper.getResourceBundleString(getProductName(), message);
delegate.debug(MessageUtil.getMessage(context, message));
}
}
@Override
public void debug(String context, String format, Object... args) {
if (isDebugEnabled()) {
format = LoggerHelper.getResourceBundleString(getProductName(), format);
delegate.debug(MessageUtil.getMessage(context, MessageUtil.formatMessage(format, args)));
}
}
@Override
public void info(String context, String message) {
if (isInfoEnabled()) {
message = LoggerHelper.getResourceBundleString(getProductName(), message);
delegate.info(MessageUtil.getMessage(context, message));
}
}
@Override
public void info(String context, String format, Object... args) {
if (isInfoEnabled()) {
format = LoggerHelper.getResourceBundleString(getProductName(), format);
delegate.info(MessageUtil.getMessage(context, MessageUtil.formatMessage(format, args)));
}
}
@Override
public void warn(String message, Throwable t) {
if (isWarnEnabled()) {
message = LoggerHelper.getResourceBundleString(getProductName(), message);
delegate.warn(MessageUtil.getMessage(null, message), t);
}
}
@Override
public void warn(String context, String message) {
if (isWarnEnabled()) {
message = LoggerHelper.getResourceBundleString(getProductName(), message);
delegate.warn(MessageUtil.getMessage(context, message));
}
}
@Override
public void warn(String context, String format, Object... args) {
if (isWarnEnabled()) {
format = LoggerHelper.getResourceBundleString(getProductName(), format);
delegate.warn(MessageUtil.getMessage(context, MessageUtil.formatMessage(format, args)));
}
}
@Override
public void error(String context, String errorCode, String message) {
if (isErrorEnabled()) {
message = LoggerHelper.getResourceBundleString(getProductName(), message);
delegate.error(MessageUtil.getMessage(context, errorCode, message));
}
}
@Override
public void error(String context, String errorCode, String message, Throwable t) {
if (isErrorEnabled()) {
message = LoggerHelper.getResourceBundleString(getProductName(), message);
delegate.error(MessageUtil.getMessage(context, errorCode, message), t);
}
}
@Override
public void error(String context, String errorCode, String format, Object... args) {
if (isErrorEnabled()) {
format = LoggerHelper.getResourceBundleString(getProductName(), format);
delegate.error(MessageUtil.getMessage(context, errorCode, MessageUtil.formatMessage(format, args)));
}
}
@Override
public boolean isDebugEnabled() {
return delegate.isDebugEnabled();
}
@Override
public boolean isInfoEnabled() {
return delegate.isInfoEnabled();
}
@Override
public boolean isWarnEnabled() {
return delegate.isEnabledFor(Level.WARN);
}
@Override
public boolean isErrorEnabled() {
return delegate.isEnabledFor(Level.ERROR);
}
}

View File

@ -1,53 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.client.logger.log4j;
import org.apache.log4j.LogManager;
import com.alibaba.nacos.client.logger.Logger;
import com.alibaba.nacos.client.logger.nop.NopLogger;
import com.alibaba.nacos.client.logger.support.ILoggerFactory;
import com.alibaba.nacos.client.logger.support.LogLog;
/**
* Log4jLogger Factory
* @author Nacos
*
*/
public class Log4jLoggerFactory implements ILoggerFactory {
public Log4jLoggerFactory() throws ClassNotFoundException {
Class.forName("org.apache.log4j.Level");
}
public Logger getLogger(Class<?> clazz) {
try {
return new Log4jLogger(LogManager.getLogger(clazz));
} catch (Throwable t) {
LogLog.error("Failed to get Log4jLogger", t);
return new NopLogger();
}
}
public Logger getLogger(String name) {
try {
return new Log4jLogger(LogManager.getLogger(name));
} catch (Throwable t) {
LogLog.error("Failed to get Log4jLogger", t);
return new NopLogger();
}
}
}

View File

@ -15,8 +15,6 @@
*/ */
package com.alibaba.nacos.client.logger.option; package com.alibaba.nacos.client.logger.option;
import org.apache.log4j.AsyncAppender;
import com.alibaba.nacos.client.logger.Level; import com.alibaba.nacos.client.logger.Level;
import com.alibaba.nacos.client.logger.support.LogLog; import com.alibaba.nacos.client.logger.support.LogLog;

View File

@ -1,212 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.client.logger.option;
import org.apache.log4j.*;
import com.alibaba.nacos.client.logger.Logger;
import com.alibaba.nacos.client.logger.support.LoggerHelper;
import java.io.File;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* ActivateOption的Log4j实现
*
* @author zhuyong 2014年3月20日 上午10:24:36
*/
public class Log4jActivateOption extends AbstractActiveOption {
protected org.apache.log4j.Logger logger;
public Log4jActivateOption(org.apache.log4j.Logger logger) {
this.logger = logger;
}
@Override
public void activateConsoleAppender(String target, String encoding) {
org.apache.log4j.ConsoleAppender appender = new org.apache.log4j.ConsoleAppender();
appender.setLayout(new PatternLayout(LoggerHelper.getPattern()));
appender.setTarget(target);
appender.setEncoding(encoding);
appender.activateOptions();
logger.removeAllAppenders();
logger.addAppender(appender);
}
@Override
public void activateAppender(String productName, String file, String encoding) {
org.apache.log4j.Appender appender = getLog4jDailyRollingFileAppender(productName, file, encoding);
logger.removeAllAppenders();
logger.addAppender(appender);
setProductName(productName);
}
@Override
public void activateAsyncAppender(String productName, String file, String encoding) {
activateAsyncAppender(productName, file, encoding, Integer.MIN_VALUE, Integer.MIN_VALUE);
}
@Override
public void activateAsyncAppender(String productName, String file, String encoding, int queueSize,
int discardingThreshold) {
activateAppender(productName, file, encoding);
activateAsync(queueSize, discardingThreshold);
}
@Override
public void activateAppenderWithTimeAndSizeRolling(String productName, String file, String encoding, String size) {
activateAppender(productName, file, encoding);
}
@Override
public void setLevel(com.alibaba.nacos.client.logger.Level level) {
this.level = level;
logger.setLevel(org.apache.log4j.Level.toLevel(level.getName()));
}
@Override
public void setAdditivity(boolean additivity) {
logger.setAdditivity(additivity);
}
protected org.apache.log4j.Appender getLog4jDailyRollingFileAppender(String productName, String file,
String encoding) {
DailyRollingFileAppender appender = new DailyRollingFileAppender();
appender.setName(productName + "." + file.replace(File.separatorChar, '.') + ".Appender");
appender.setLayout(new PatternLayout(LoggerHelper.getPattern(productName)));
appender.setAppend(true);
appender.setFile(LoggerHelper.getLogFileP(productName, file));
appender.setEncoding(encoding);
appender.activateOptions();
return appender;
}
@Override
public void activateAppender(Logger logger) {
if (!(logger.getDelegate() instanceof org.apache.log4j.Logger)) {
throw new IllegalArgumentException(
"logger must be org.apache.log4j.Logger, but it's " + logger.getDelegate().getClass());
}
activateAppender((org.apache.log4j.Logger) logger.getDelegate());
setProductName(logger.getProductName());
}
protected void activateAppender(org.apache.log4j.Logger logger) {
this.logger.removeAllAppenders();
Enumeration<?> enums = logger.getAllAppenders();
while (enums != null && enums.hasMoreElements()) {
this.logger.addAppender((Appender) enums.nextElement());
}
}
@Override
public void activateAppenderWithTimeAndSizeRolling(String productName, String file, String encoding, String size,
String datePattern) {
Appender appender = getLog4jRollingFileAppender(productName, file, encoding, size, datePattern, -1);
logger.removeAllAppenders();
logger.addAppender(appender);
setProductName(productName);
}
@Override
public void activateAppenderWithTimeAndSizeRolling(String productName, String file, String encoding, String size,
String datePattern, int maxBackupIndex) {
Appender appender = getLog4jRollingFileAppender(productName, file, encoding, size, datePattern, maxBackupIndex);
logger.removeAllAppenders();
logger.addAppender(appender);
setProductName(productName);
}
protected org.apache.log4j.Appender getLog4jRollingFileAppender(String productName, String file, String encoding,
String size, String datePattern,
int maxBackupIndex) {
RollingFileAppender appender = new RollingFileAppender();
appender.setName(productName + "." + file.replace(File.separatorChar, '.') + ".Appender");
appender.setLayout(new PatternLayout(LoggerHelper.getPattern(productName)));
appender.setAppend(true);
appender.setFile(LoggerHelper.getLogFileP(productName, file));
appender.setEncoding(encoding);
appender.setMaxFileSize(size);
if (maxBackupIndex >= 0) {
// 等于0表示直接truck
appender.setMaxBackupIndex(maxBackupIndex);
}
appender.activateOptions();
return appender;
}
@Override
public void activateAppenderWithSizeRolling(String productName, String file, String encoding, String size,
int maxBackupIndex) {
Appender appender = getLog4jRollingFileAppender(productName, file, encoding, size, null, maxBackupIndex);
logger.removeAllAppenders();
logger.addAppender(appender);
setProductName(productName);
}
@Override
public void activateAsync(int queueSize, int discardingThreshold) {
// discardingThreshold is unused for log4j
List<Object[]> args = new ArrayList<Object[]>();
if (queueSize != Integer.MIN_VALUE) {
args.add(new Object[] { "setBufferSize", new Class<?>[] { int.class }, queueSize });
}
activateAsync(args);
}
@Override
public void activateAsync(List<Object[]> args) {
AsyncAppender asyncAppender = new AsyncAppender();
invokeMethod(asyncAppender, args);
asyncAppender.setName(productName + "." + logger.getName() + ".AsyncAppender");
Enumeration<Appender> appenders = logger.getAllAppenders();
if (appenders == null) {
throw new IllegalStateException("Activate async appender failed, no appender exist.");
}
while (appenders.hasMoreElements()) {
asyncAppender.addAppender(appenders.nextElement());
}
appenders = logger.getAllAppenders();
while (appenders.hasMoreElements()) {
logger.removeAppender(appenders.nextElement());
}
logger.addAppender(asyncAppender);
setProductName(productName);
}
}

View File

@ -1,71 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.client.logger.option;
import java.lang.reflect.Field;
import com.alibaba.nacos.client.logger.Logger;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
/**
* Slf4j-log4j12架构下的ActivateOption实现
*
* @author zhuyong 2014年3月20日 上午10:26:04
*/
public class Slf4jLog4jAdapterActivateOption extends Log4jActivateOption {
private static Field loggerField = null;
static {
try {
loggerField = org.slf4j.impl.Log4jLoggerAdapter.class.getDeclaredField("logger");
loggerField.setAccessible(true);
} catch (Exception e) {
throw new RuntimeException("logger must be instanceof org.slf4j.impl.Log4jLoggerAdapter", e);
}
}
public Slf4jLog4jAdapterActivateOption(Object logger) {
super(null);
try {
org.apache.log4j.Logger log4jLogger = (org.apache.log4j.Logger) loggerField.get(logger);
super.logger = log4jLogger;
} catch (Exception e) {
throw new RuntimeException("logger must be instanceof org.slf4j.impl.Log4jLoggerAdapter", e);
}
}
@Override
@SuppressFBWarnings("NM_WRONG_PACKAGE")
public void activateAppender(Logger logger) {
if (!(logger.getDelegate() instanceof org.slf4j.impl.Log4jLoggerAdapter)) {
throw new IllegalArgumentException(
"logger must be org.slf4j.impl.Log4jLoggerAdapter, but it's "
+ logger.getDelegate().getClass());
}
try {
org.apache.log4j.Logger log4jLogger =
(org.apache.log4j.Logger) loggerField.get(logger.getDelegate());
super.activateAppender(log4jLogger);
setProductName(logger.getProductName());
} catch (Exception e) {
throw new RuntimeException("activateAppender error, ", e);
}
}
}

View File

@ -15,24 +15,25 @@
*/ */
package com.alibaba.nacos.client.logger.slf4j; package com.alibaba.nacos.client.logger.slf4j;
import java.lang.reflect.Constructor;
import com.alibaba.nacos.client.logger.Logger; import com.alibaba.nacos.client.logger.Logger;
import com.alibaba.nacos.client.logger.option.ActivateOption; import com.alibaba.nacos.client.logger.option.ActivateOption;
import com.alibaba.nacos.client.logger.support.LoggerHelper; import com.alibaba.nacos.client.logger.support.LoggerHelper;
import com.alibaba.nacos.client.logger.support.LoggerSupport; import com.alibaba.nacos.client.logger.support.LoggerSupport;
import com.alibaba.nacos.client.logger.util.MessageUtil; import com.alibaba.nacos.client.logger.util.MessageUtil;
import java.lang.reflect.Constructor;
/** /**
* slf4j logger * slf4j logger
* @author Nacos
* *
* @author Nacos
*/ */
public class Slf4jLogger extends LoggerSupport implements Logger { public class Slf4jLogger extends LoggerSupport implements Logger {
private static boolean CanUseEncoder = false; private static boolean CanUseEncoder = false;
private static final String LOGBACK_CLASSNAME = "ch.qos.logback.classic.Logger"; private static final String LOGBACK_CLASSNAME = "ch.qos.logback.classic.Logger";
private static final String SLF4J_CLASSNAME = "org.slf4j.impl.Log4jLoggerAdapter";
private static final String SLF4JLOG4J_CLASSNAME = "org.apache.logging.slf4j.Log4jLogger"; private static final String SLF4JLOG4J_CLASSNAME = "org.apache.logging.slf4j.Log4jLogger";
static { static {
try { try {
// logback从0.9.19开始采用encoder@see http://logback.qos.ch/manual/encoders.html // logback从0.9.19开始采用encoder@see http://logback.qos.ch/manual/encoders.html
@ -46,8 +47,7 @@ public class Slf4jLogger extends LoggerSupport implements Logger {
private org.slf4j.Logger delegate; private org.slf4j.Logger delegate;
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public public Slf4jLogger(org.slf4j.Logger delegate) {
Slf4jLogger(org.slf4j.Logger delegate){
super(delegate); super(delegate);
if (delegate == null) { if (delegate == null) {
throw new IllegalArgumentException("delegate Logger is null"); throw new IllegalArgumentException("delegate Logger is null");
@ -61,8 +61,6 @@ public class Slf4jLogger extends LoggerSupport implements Logger {
} else { } else {
activateOptionClass = "com.alibaba.nacos.client.logger.option.Logback918ActivateOption"; activateOptionClass = "com.alibaba.nacos.client.logger.option.Logback918ActivateOption";
} }
} else if (SLF4J_CLASSNAME.equals(delegate.getClass().getName())) {
activateOptionClass = "com.alibaba.nacos.client.logger.option.Slf4jLog4jAdapterActivateOption";
} else if (SLF4JLOG4J_CLASSNAME.equals(delegate.getClass().getName())) { } else if (SLF4JLOG4J_CLASSNAME.equals(delegate.getClass().getName())) {
activateOptionClass = "com.alibaba.nacos.client.logger.option.Slf4jLog4j2AdapterActivateOption"; activateOptionClass = "com.alibaba.nacos.client.logger.option.Slf4jLog4j2AdapterActivateOption";
} }

View File

@ -1,90 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Copyright 2014 Alibaba.com All right reserved. This software is the
* confidential and proprietary information of Alibaba.com ("Confidential
* Information"). You shall not disclose such Confidential Information and shall
* use it only in accordance with the terms of the license agreement you entered
* into with Alibaba.com.
*/
package com.alibaba.nacos.client.logger.support;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.io.LineNumberReader;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import org.apache.log4j.spi.ThrowableRenderer;
/**
* 针对 Log4j 1.2.16 及以上版本提供对异常栈的深度控制
*
* @author zhuyong 2014年9月19日 上午10:31:48
*/
public final class DepthThrowableRenderer implements ThrowableRenderer {
private int depth = -1;
public DepthThrowableRenderer(int depth) {
this.depth = depth;
}
public void setDepth(int depth) {
this.depth = depth;
}
public String[] doRender(final Throwable throwable) {
return render(throwable, depth);
}
/**
* Render throwable using Throwable.printStackTrace.
*
* @param throwable throwable, may not be null.
* @param depth stack depth
* @return string representation.
*/
public static String[] render(final Throwable throwable, final int depth) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
try {
throwable.printStackTrace(pw);
} catch (RuntimeException ex) {
}
pw.flush();
LineNumberReader reader = new LineNumberReader(new StringReader(sw.toString()));
ArrayList<String> lines = new ArrayList<String>();
try {
String line = reader.readLine();
int count = 0;
while (line != null && (depth == -1 || count++ <= depth)) {
lines.add(line);
line = reader.readLine();
}
} catch (IOException ex) {
if (ex instanceof InterruptedIOException) {
Thread.currentThread().interrupt();
}
lines.add(ex.toString());
}
String[] tempRep = new String[lines.size()];
lines.toArray(tempRep);
return tempRep;
}
}

View File

@ -1,201 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.client.logger.support;
import org.apache.log4j.Appender;
import org.apache.log4j.AsyncAppender;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.log4j.spi.LoggerRepository;
import org.apache.log4j.spi.ThrowableRenderer;
import org.apache.log4j.spi.ThrowableRendererSupport;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author zhuyong on 2017/6/28.
*/
@SuppressWarnings("PMD.AbstractClassShouldStartWithAbstractNamingRule")
public class Log4jHelper {
private static boolean Log4j = false, Log4jGT1216 = false;
static {
try {
Class<?> loggerClass = Class.forName("org.apache.log4j.Logger");
// 这里可能会加载到应用中依赖的log4j因此需要判断classloader
if (loggerClass.getClassLoader().equals(Log4jHelper.class.getClassLoader())) {
LogManager.getLoggerRepository();
try {
Class<?> throwableRendererClass = Class.forName("org.apache.log4j.spi.ThrowableRenderer");
// 这里可能会加载到应用中依赖的log4j 1.2.16版本的类因此需要额外判断
if (loggerClass.getClassLoader().equals(throwableRendererClass.getClassLoader())
&& throwableRendererClass.getClassLoader().equals(Log4jHelper.class.getClassLoader())) {
Log4jGT1216 = true;
}
} catch (Throwable t) {
LogLog.warn("log4j must >= 1.2.16 for change throwable depth");
}
Log4j = true;
}
} catch (Throwable t) {
}
}
@SuppressFBWarnings("NP_BOOLEAN_RETURN_NULL")
public static Boolean setDepth(int depth) {
if (Log4j && Log4jGT1216) {
try {
LoggerRepository repo = LogManager.getLoggerRepository();
doSetDepth(repo, depth);
return Boolean.TRUE;
} catch (Throwable t) {
// ignore
LogLog.error("failed to set depth for log4j", t);
return Boolean.FALSE;
}
}
return null;
}
@SuppressFBWarnings("NP_BOOLEAN_RETURN_NULL")
public static Boolean changeLevel(String name, String level) {
if (Log4j) {
Level l = Level.toLevel(level, Level.ERROR);
Logger logger = LogManager.getLoggerRepository().exists(name);
if (logger != null) {
logger.setLevel(l);
LogLog.info("set log4j log level success, " + name + ": " + l);
return true;
} else {
Logger root = LogManager.getLoggerRepository().getRootLogger();
if (root.getName().equals(name)) {
root.setLevel(l);
LogLog.info("set log4j log level success, " + name + ": " + l);
return true;
}
}
LogLog.info("set log4j log level fail, no logger name exists: " + name);
return false;
}
return null;
}
public static Map<String, LoggerInfo> getLoggers(String name) {
Map<String, LoggerInfo> appenders = new HashMap<String, LoggerInfo>(10);
if (!Log4j) {
return appenders;
}
if (name != null && !"".equals(name.trim())) {
Logger logger = LogManager.getLoggerRepository().exists(name);
if (logger != null) {
appenders.put(name, doGetLoggerInfo(logger));
}
} else {
// 获取所有logger时如果没有appender则忽略
Enumeration<Logger> loggers = LogManager.getLoggerRepository().getCurrentLoggers();
if (loggers != null) {
while (loggers.hasMoreElements()) {
Logger logger = loggers.nextElement();
LoggerInfo info = doGetLoggerInfo(logger);
if (info.getAppenders() == null || !info.getAppenders().isEmpty()) {
appenders.put(logger.getName(), info);
}
}
}
Logger root = LogManager.getLoggerRepository().getRootLogger();
if (root != null) {
LoggerInfo info = doGetLoggerInfo(root);
if (info.getAppenders() == null || !info.getAppenders().isEmpty()) {
appenders.put(root.getName(), info);
}
}
}
return appenders;
}
private static LoggerInfo doGetLoggerInfo(Logger logger) {
LoggerInfo info = new LoggerInfo(logger.getName(), logger.getAdditivity());
Level level = logger.getLevel(), effectiveLevel = logger.getEffectiveLevel();
if (level != null) {
info.setLevel(level.toString());
}
if (effectiveLevel != null) {
info.setEffectiveLevel(effectiveLevel.toString());
}
List<AppenderInfo> result = doGetLoggerAppenders(logger.getAllAppenders());
info.setAppenders(result);
return info;
}
private static List<AppenderInfo> doGetLoggerAppenders(Enumeration<Appender> appenders) {
List<AppenderInfo> result = new ArrayList<AppenderInfo>();
while (appenders.hasMoreElements()) {
AppenderInfo info = new AppenderInfo();
Appender appender = appenders.nextElement();
info.setName(appender.getName());
info.setType(appender.getClass().getName());
result.add(info);
if (appender instanceof FileAppender) {
info.setFile(((FileAppender) appender).getFile());
} else if (appender instanceof ConsoleAppender) {
info.withDetail("target", ((ConsoleAppender) appender).getTarget());
} else if (appender instanceof AsyncAppender) {
List<AppenderInfo> asyncs = doGetLoggerAppenders(((AsyncAppender) appender).getAllAppenders());
// 标明异步appender
List<String> nestedNames = new ArrayList<String>();
for (AppenderInfo a : asyncs) {
nestedNames.add(a.getName());
result.add(a);
}
info.withDetail("nestedNames", nestedNames);
}
}
return result;
}
private static void doSetDepth(LoggerRepository repo, int depth) {
if (repo instanceof ThrowableRendererSupport) {
Object tr = ((ThrowableRendererSupport) repo).getThrowableRenderer();
if (tr == null || !(tr instanceof DepthThrowableRenderer)) {
Object ctr = new DepthThrowableRenderer(depth);
// 自定义ThrowableRender栈深度设置
((ThrowableRendererSupport) repo).setThrowableRenderer((ThrowableRenderer) ctr);
LogLog.info("set log4j log depth success, depth: " + depth);
} else {
((DepthThrowableRenderer) tr).setDepth(depth);
LogLog.info("set log4j log depth success, depth: " + depth);
}
}
}
}

View File

@ -229,9 +229,6 @@ public class ConcurrentDiskUtil {
} }
} }
public static void main(String[] args) {
}
static final public Logger log = LogUtils.LOG; static final public Logger log = LogUtils.LOG;
static final int RETRY_COUNT = 10; static final int RETRY_COUNT = 10;
static final int SLEEP_BASETIME = 10; static final int SLEEP_BASETIME = 10;

View File

@ -175,12 +175,6 @@ public class HttpClient {
return sb.toString(); return sb.toString();
} }
public static void main(String[] args) throws UnsupportedEncodingException {
Map<String, String> params = new HashMap<String, String>(2);
params.put("s", "Wms+rkGG8jlaBBbpl8FIDxxNQGA=");
System.out.println(encodingParams(params, "utf-8"));
}
public static class HttpResult { public static class HttpResult {
final public int code; final public int code;
final public String content; final public String content;

View File

@ -12,40 +12,50 @@
limitations under the License. limitations under the License.
--> -->
<project xmlns="http://maven.apache.org/POM/4.0.0" <project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent> <parent>
<groupId>com.alibaba.nacos</groupId> <groupId>com.alibaba.nacos</groupId>
<artifactId>nacos-all</artifactId> <artifactId>nacos-all</artifactId>
<version>0.2.1</version> <version>0.2.2-SNAPSHOT</version>
</parent> <relativePath>../pom.xml</relativePath>
<modelVersion>4.0.0</modelVersion> </parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>nacos-common</artifactId> <artifactId>nacos-common</artifactId>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>nacos-common ${project.version}</name> <name>nacos-common ${project.version}</name>
<url>http://maven.apache.org</url> <url>http://maven.apache.org</url>
<properties> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties> </properties>
<dependencies> <dependencies>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>org.apache.commons</groupId> <groupId>org.slf4j</groupId>
<artifactId>commons-lang3</artifactId> <artifactId>slf4j-api</artifactId>
</dependency> </dependency>
</dependencies>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<!-- Test -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project> </project>

View File

@ -1,85 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.common;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import org.apache.commons.io.IOUtils;
/**
*
* 遍历目标文件夹下的所有文件在文件头上加上license协议
* 注意读取/写入文件默认用utf-8进行
* @author en.xuze@alipay.com
* @version $Id: AppendLicense.java, v 0.1 2018年7月4日 下午2:31:16 en.xuze@alipay.com Exp $
*/
public class AppendLicense {
private static List<File> targetFiles = new LinkedList<File>();
private static String licenseFile = "/Users/en.xuze/git/nacos/common/license";
private static String targetDirOrFile = "/Users/en.xuze/git/nacos";
public static void main(String[] args) throws Exception {
List<String> licenseContents = IOUtils.readLines(new FileInputStream(new File(licenseFile)), "utf-8");
readFiles(targetDirOrFile);
for (Iterator<File> iterator = targetFiles.iterator(); iterator.hasNext();) {
File file = (File) iterator.next();
List<String> srcFileContents = IOUtils.readLines(new FileInputStream(file), "utf-8");
List<String> writeContents = new ArrayList<String>();
writeContents.addAll(licenseContents);
writeContents.addAll(srcFileContents);
IOUtils.writeLines(writeContents, "\n", new FileOutputStream(file));
System.out.println("append license to file:" + file.getAbsolutePath());
}
}
private static void readFiles(String filePath) {
if (filePath == null) {
return;
}
File temp = new File(filePath);
File[] files = null;
if (temp.isFile()) {
if (needAppend(temp.getName())) {
targetFiles.add(temp);
}
} else {
files = temp.listFiles();
}
if (files == null) {
return;
}
for (File f : files) {
if (f.isFile()) {
if (needAppend(f.getName())) {
targetFiles.add(f);
}
} else if (f.isDirectory()) {
readFiles(f.getPath());
}
}
}
private static boolean needAppend(String fileName) {
return (fileName.endsWith(".java"));
}
}

View File

@ -0,0 +1,31 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.common.util;
/**
* Nacos common constants
*
* @author <a href="mailto:mercyblitz@gmail.com">Mercy</a>
* @since 0.2.2
*/
public interface Constants {
/**
* Spring Profile : "standalone"
*/
String STANDALONE_SPRING_PROFILE = "standalone";
}

View File

@ -15,11 +15,9 @@
*/ */
package com.alibaba.nacos.common.util; package com.alibaba.nacos.common.util;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.io.IOUtils;
import java.io.*; import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.GZIPInputStream; import java.util.zip.GZIPInputStream;
/** /**
@ -29,120 +27,6 @@ import java.util.zip.GZIPInputStream;
*/ */
public class IoUtils { public class IoUtils {
static public String toString(InputStream input, String encoding) throws IOException {
return (null == encoding) ? toString(new InputStreamReader(input, "UTF-8"))
: toString(new InputStreamReader(input, encoding));
}
static public String toString(Reader reader) throws IOException {
CharArrayWriter sw = new CharArrayWriter();
copy(reader, sw);
return sw.toString();
}
static public long copy(Reader input, Writer output) throws IOException {
char[] buffer = new char[1 << 12];
long count = 0;
for (int n = 0; (n = input.read(buffer)) >= 0; ) {
output.write(buffer, 0, n);
count += n;
}
return count;
}
static public long copy(InputStream input, OutputStream output) throws IOException {
byte[] buffer = new byte[1024];
int bytesRead;
int totalBytes = 0;
while ((bytesRead = input.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
totalBytes += bytesRead;
}
return totalBytes;
}
static public List<String> readLines(Reader input) throws IOException {
BufferedReader reader = toBufferedReader(input);
List<String> list = new ArrayList<String>();
String line = null;
for (; ; ) {
line = reader.readLine();
if (null != line) {
if (StringUtils.isNotEmpty(line)) {
list.add(line.trim());
}
} else {
break;
}
}
return list;
}
static private BufferedReader toBufferedReader(Reader reader) {
return reader instanceof BufferedReader ? (BufferedReader) reader : new BufferedReader(
reader);
}
public static boolean delete(File fileOrDir) throws IOException {
if (fileOrDir == null) {
return false;
}
if (fileOrDir.isDirectory()) {
cleanDirectory(fileOrDir);
}
return fileOrDir.delete();
}
public static void cleanDirectory(File directory) throws IOException {
if (!directory.exists()) {
String message = directory + " does not exist";
throw new IllegalArgumentException(message);
}
if (!directory.isDirectory()) {
String message = directory + " is not a directory";
throw new IllegalArgumentException(message);
}
File[] files = directory.listFiles();
if (files == null) {
throw new IOException("Failed to list contents of " + directory);
}
IOException exception = null;
for (File file : files) {
try {
delete(file);
} catch (IOException ioe) {
exception = ioe;
}
}
if (null != exception) {
throw exception;
}
}
public static void writeStringToFile(File file, String data, String encoding)
throws IOException {
OutputStream os = null;
try {
os = new FileOutputStream(file);
os.write(data.getBytes(encoding));
os.flush();
} finally {
if (null != os) {
os.close();
}
}
}
public static byte[] tryDecompress(InputStream raw) throws Exception { public static byte[] tryDecompress(InputStream raw) throws Exception {
try { try {
@ -151,8 +35,7 @@ public class IoUtils {
ByteArrayOutputStream out ByteArrayOutputStream out
= new ByteArrayOutputStream(); = new ByteArrayOutputStream();
IOUtils.copy(gis, out);
IoUtils.copy(gis, out);
return out.toByteArray(); return out.toByteArray();
} catch (Exception e) { } catch (Exception e) {
@ -162,12 +45,5 @@ public class IoUtils {
return null; return null;
} }
public static void main(String[] args) throws IOException {
// String path = "/Users/zhupengfei/test_write.txt";
// writeStringToFile(new File(path), "hello2222", "utf-8");
}
} }

View File

@ -16,18 +16,28 @@
package com.alibaba.nacos.common.util; package com.alibaba.nacos.common.util;
import com.sun.management.OperatingSystemMXBean;
import org.apache.commons.lang3.StringUtils;
import java.lang.management.ManagementFactory; import java.lang.management.ManagementFactory;
import java.sql.SQLException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
import org.apache.commons.lang3.StringUtils;
import com.sun.management.OperatingSystemMXBean;
/** /**
* @author nacos * @author nacos
*/ */
public class SystemUtil { public class SystemUtils {
/**
* The System property name of Standalone mode
*/
public static final String STANDALONE_MODE_PROPERTY_NAME = "nacos.standalone";
/**
* Standalone mode or not
*/
public static final boolean STANDALONE_MODE = Boolean.getBoolean(STANDALONE_MODE_PROPERTY_NAME);
private static OperatingSystemMXBean operatingSystemMXBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean(); private static OperatingSystemMXBean operatingSystemMXBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
@ -45,10 +55,6 @@ public class SystemUtil {
return env; return env;
} }
public static void main(String[] args) throws SQLException {
System.out.println(Boolean.parseBoolean("Tfue"));
}
public static float getLoad() { public static float getLoad() {
return (float) operatingSystemMXBean.getSystemLoadAverage(); return (float) operatingSystemMXBean.getSystemLoadAverage();
} }

View File

@ -0,0 +1,57 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.common;
import com.alibaba.nacos.common.util.SystemUtils;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import java.util.Random;
/**
* {@link SystemUtils} Test
*
* @author <a href="mailto:mercyblitz@gmail.com">Mercy</a>
* @since 0.2.2
*/
public class SystemUtilsTest {
private static final Random random = new Random();
private static boolean standaloneMode = random.nextBoolean();
@BeforeClass
public static void init() {
System.setProperty("nacos.standalone", String.valueOf(standaloneMode));
}
@Test
public void testStandaloneModeConstants() {
System.out.printf("System property \"%s\" = %s \n", "nacos.standalone", standaloneMode);
if ("true".equalsIgnoreCase(System.getProperty("nacos.standalone"))) {
Assert.assertTrue(SystemUtils.STANDALONE_MODE);
} else {
Assert.assertFalse(SystemUtils.STANDALONE_MODE);
}
Assert.assertEquals(standaloneMode, SystemUtils.STANDALONE_MODE);
}
}

View File

@ -12,169 +12,176 @@
limitations under the License. limitations under the License.
--> -->
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent> <parent>
<groupId>com.alibaba.nacos</groupId> <groupId>com.alibaba.nacos</groupId>
<artifactId>nacos-all</artifactId> <artifactId>nacos-all</artifactId>
<version>0.2.1</version> <version>0.2.2-SNAPSHOT</version>
</parent> <relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<artifactId>nacos-config</artifactId> <artifactId>nacos-config</artifactId>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>nacos-config ${project.version}</name> <name>nacos-config ${project.version}</name>
<url>http://maven.apache.org</url> <url>http://maven.apache.org</url>
<properties> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties> </properties>
<dependencies> <dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>nacos-core</artifactId>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
</dependency>
<dependency>
<groupId>org.apache.derby</groupId>
<artifactId>derby</artifactId>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
</dependency>
<!-- for aop --> <dependency>
<dependency> <groupId>org.springframework.boot</groupId>
<groupId>org.aspectj</groupId> <artifactId>spring-boot-starter-web</artifactId>
<artifactId>aspectjrt</artifactId> </dependency>
</dependency>
<dependency> <dependency>
<groupId>cglib</groupId> <groupId>${project.groupId}</groupId>
<artifactId>cglib-nodep</artifactId> <artifactId>nacos-core</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId> <dependency>
<artifactId>httpasyncclient</artifactId> <groupId>com.google.guava</groupId>
</dependency> <artifactId>guava</artifactId>
</dependency>
<!-- Provided -->
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId> <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId> <dependency>
<artifactId>jackson-mapper-lgpl</artifactId> <groupId>mysql</groupId>
</dependency> <artifactId>mysql-connector-java</artifactId>
<dependency> </dependency>
<groupId>net.jcip</groupId> <dependency>
<artifactId>jcip-annotations</artifactId> <groupId>commons-dbcp</groupId>
<optional>true</optional> <artifactId>commons-dbcp</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.github.spotbugs</groupId> <groupId>org.apache.derby</groupId>
<artifactId>spotbugs-annotations</artifactId> <artifactId>derby</artifactId>
</dependency> </dependency>
</dependencies> <dependency>
<build> <groupId>ch.qos.logback</groupId>
<plugins> <artifactId>logback-classic</artifactId>
<plugin> </dependency>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId> <!-- for aop -->
<configuration> <dependency>
<skipTests>true</skipTests> <groupId>org.aspectj</groupId>
<argLine>-Dnacos.standalone=true</argLine> <artifactId>aspectjrt</artifactId>
</configuration> </dependency>
</plugin> <dependency>
<plugin> <groupId>cglib</groupId>
<groupId>org.apache.maven.plugins</groupId> <artifactId>cglib-nodep</artifactId>
<artifactId>maven-assembly-plugin</artifactId> </dependency>
<configuration> <dependency>
<archive> <groupId>org.apache.httpcomponents</groupId>
<manifest> <artifactId>httpasyncclient</artifactId>
<mainClass>com.alibaba.nacos.config.server.Config</mainClass> </dependency>
</manifest>
</archive> <!-- Provided -->
<descriptorRefs> <dependency>
<descriptorRef>jar-with-dependencies</descriptorRef> <groupId>org.codehaus.jackson</groupId>
</descriptorRefs> <artifactId>jackson-mapper-lgpl</artifactId>
</configuration> </dependency>
</plugin> <dependency>
</plugins> <groupId>net.jcip</groupId>
<resources> <artifactId>jcip-annotations</artifactId>
<resource> <optional>true</optional>
<filtering>true</filtering> </dependency>
<directory>src/main/resources</directory> <dependency>
<excludes> <groupId>com.github.spotbugs</groupId>
<exclude>application.properties</exclude> <artifactId>spotbugs-annotations</artifactId>
<exclude>banner.txt</exclude> </dependency>
<exclude>schema.sql</exclude>
<exclude>nacos-db.sql</exclude> <dependency>
</excludes> <groupId>junit</groupId>
</resource> <artifactId>junit</artifactId>
</resources> <scope>test</scope>
</build> </dependency>
<profiles>
<profile> <dependency>
<id>springboot</id> <groupId>org.mockito</groupId>
<dependencies> <artifactId>mockito-core</artifactId>
<dependency> <scope>test</scope>
<groupId>com.alibaba.nacos</groupId> </dependency>
<artifactId>nacos-core</artifactId>
</dependency> <dependency>
</dependencies> <groupId>org.springframework</groupId>
<build> <artifactId>spring-test</artifactId>
<plugins> <scope>test</scope>
<plugin> </dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId> <dependency>
<configuration> <groupId>org.springframework.boot</groupId>
<mainClass>com.alibaba.nacos.config.server.Config</mainClass> <artifactId>spring-boot-test</artifactId>
</configuration> <scope>test</scope>
</plugin> </dependency>
</plugins>
<finalName>nacos-config</finalName> </dependencies>
</build>
</profile> <build>
</profiles> <plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<skipTests>true</skipTests>
<argLine>-Dnacos.standalone=true</argLine>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<archive>
<manifest>
<mainClass>com.alibaba.nacos.config.server.Config</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
</plugins>
<resources>
<resource>
<directory>src/main/resources</directory>
<excludes>
<exclude>application.properties</exclude>
</excludes>
</resource>
</resources>
</build>
<profiles>
<profile>
<id>springboot</id>
<dependencies>
<dependency>
<groupId>com.alibaba.nacos</groupId>
<artifactId>nacos-core</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass>com.alibaba.nacos.config.server.Config</mainClass>
</configuration>
</plugin>
</plugins>
<finalName>nacos-config</finalName>
</build>
</profile>
</profiles>
</project> </project>

View File

@ -1,68 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.nacos.config.server.utils.AppNameUtils;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
/**
* logback test
* @author Nacos
*
*/
public class LogbackInitTest {
private static final Logger logger = LoggerFactory.getLogger(LogbackInitTest.class);
public static void main(String[] args) throws Exception {
AppNameUtils.class.getClassLoader();
String classpath = AppNameUtils.class.getResource("/").getPath();
System.out.println("The classpath is " + classpath);
LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
lc.reset();
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(lc);
configurator.doConfigure(LogbackInitTest.class.getResource("logback-jiuren.xml"));
for (;;) {
logger.info("hello");
System.out.println(getLevel(logger));
Thread.sleep(1000L);
}
}
static String getLevel(Logger logger) {
if (logger.isDebugEnabled()) {
return "debug";
} else if (logger.isInfoEnabled()) {
return "info";
} else if (logger.isWarnEnabled()) {
return "warn";
} else if (logger.isErrorEnabled()) {
return "error";
} else {
return "unknown";
}
}
}

View File

@ -15,26 +15,20 @@
*/ */
package com.alibaba.nacos.config.server; package com.alibaba.nacos.config.server;
import java.net.UnknownHostException;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.web.servlet.ServletComponentScan; import java.net.UnknownHostException;
/** /**
* Config main * Config main
*
* @author Nacos
* *
* @author Nacos
*/ */
@SpringBootApplication(scanBasePackages = "com.alibaba.nacos.config.server") @SpringBootApplication
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
@ServletComponentScan
public class Config { public class Config {
public static void main(String[] args) throws UnknownHostException {
SpringApplication.run(Config.class, args); public static void main(String[] args) throws UnknownHostException {
} SpringApplication.run(Config.class, args);
}
} }

View File

@ -15,19 +15,6 @@
*/ */
package com.alibaba.nacos.config.server.aspect; package com.alibaba.nacos.config.server.aspect;
import java.nio.charset.Charset;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.alibaba.nacos.config.server.constant.Constants; import com.alibaba.nacos.config.server.constant.Constants;
import com.alibaba.nacos.config.server.constant.CounterMode; import com.alibaba.nacos.config.server.constant.CounterMode;
import com.alibaba.nacos.config.server.model.ConfigInfo; import com.alibaba.nacos.config.server.model.ConfigInfo;
@ -35,6 +22,17 @@ import com.alibaba.nacos.config.server.model.capacity.Capacity;
import com.alibaba.nacos.config.server.service.PersistService; import com.alibaba.nacos.config.server.service.PersistService;
import com.alibaba.nacos.config.server.service.capacity.CapacityService; import com.alibaba.nacos.config.server.service.capacity.CapacityService;
import com.alibaba.nacos.config.server.utils.PropertyUtil; import com.alibaba.nacos.config.server.utils.PropertyUtil;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.Charset;
/** /**
* 容量管理切面批量写入更新暂不处理 * 容量管理切面批量写入更新暂不处理

View File

@ -15,18 +15,17 @@
*/ */
package com.alibaba.nacos.config.server.aspect; package com.alibaba.nacos.config.server.aspect;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import com.alibaba.nacos.config.server.service.ConfigService; import com.alibaba.nacos.config.server.service.ConfigService;
import com.alibaba.nacos.config.server.utils.GroupKey2; import com.alibaba.nacos.config.server.utils.GroupKey2;
import com.alibaba.nacos.config.server.utils.LogUtil; import com.alibaba.nacos.config.server.utils.LogUtil;
import com.alibaba.nacos.config.server.utils.MD5; import com.alibaba.nacos.config.server.utils.MD5;
import com.alibaba.nacos.config.server.utils.RequestUtil; import com.alibaba.nacos.config.server.utils.RequestUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/** /**
* * Created with IntelliJ IDEA. User: dingjoey Date: 13-12-12 Time: 21:12 * * Created with IntelliJ IDEA. User: dingjoey Date: 13-12-12 Time: 21:12

View File

@ -0,0 +1,198 @@
///*
// * Licensed to the Apache Software Foundation (ASF) under one or more
// * contributor license agreements. See the NOTICE file distributed with
// * this work for additional information regarding copyright ownership.
// * The ASF licenses this file to You under the Apache License, Version 2.0
// * (the "License"); you may not use this file except in compliance with
// * the License. You may obtain a copy of the License at
// *
// * http://www.apache.org/licenses/LICENSE-2.0
// *
// * Unless required by applicable law or agreed to in writing, software
// * distributed under the License is distributed on an "AS IS" BASIS,
// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// * See the License for the specific language governing permissions and
// * limitations under the License.
// */
//package com.alibaba.nacos.config.server.configuration;
//
//import com.alibaba.nacos.config.server.service.BasicDataSourceServiceImpl;
//import com.alibaba.nacos.config.server.service.TimerTaskService;
//import com.alibaba.nacos.config.server.utils.PropertyUtil;
//import org.apache.commons.dbcp.BasicDataSource;
//import org.apache.commons.lang.math.NumberUtils;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.context.annotation.Profile;
//import org.springframework.jdbc.core.JdbcTemplate;
//import org.springframework.jdbc.datasource.DataSourceTransactionManager;
//import org.springframework.transaction.support.TransactionTemplate;
//
//import javax.annotation.PostConstruct;
//import javax.sql.DataSource;
//import java.io.IOException;
//import java.util.ArrayList;
//import java.util.List;
//import java.util.concurrent.TimeUnit;
//import java.util.regex.Pattern;
//
//import static com.alibaba.nacos.config.server.utils.LogUtil.fatalLog;
//
///**
// * Cluster {@link DataSource} {@link Configuration}
// *
// * @author <a href="mailto:mercyblitz@gmail.com">Mercy</a>
// * @since 0.2.2
// */
//@Profile("!standalone")
//@Configuration
//public class ClusterDataSourceConfiguration {
//
// private static final String JDBC_DRIVER_NAME = "com.mysql.jdbc.Driver";
//
// /**
// * JDBC执行超时时间, 单位秒
// */
// private int queryTimeout = 3;
//
// private static final int TRANSACTION_QUERY_TIMEOUT = 5;
//
// private static final String DB_LOAD_ERROR_MSG = "[db-load-error]load jdbc.properties error";
//
// private List<BasicDataSource> dataSourceList = new ArrayList<BasicDataSource>();
// private JdbcTemplate jt;
// private DataSourceTransactionManager tm;
// private TransactionTemplate tjt;
//
// private JdbcTemplate testMasterJT;
// private JdbcTemplate testMasterWritableJT;
//
// volatile private List<JdbcTemplate> testJTList;
// volatile private List<Boolean> isHealthList;
// private volatile int masterIndex;
// private static Pattern ipPattern = Pattern.compile("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}");
//
//
//
// @PostConstruct
// public void init() {
// queryTimeout = NumberUtils
// .toInt(System.getProperty("QUERYTIMEOUT"), 3);
// jt = new JdbcTemplate();
// /**
// * 设置最大记录数防止内存膨胀
// */
// jt.setMaxRows(50000);
// jt.setQueryTimeout(queryTimeout);
//
// testMasterJT = new JdbcTemplate();
// testMasterJT.setQueryTimeout(queryTimeout);
//
// testMasterWritableJT = new JdbcTemplate();
// /**
// * 防止login接口因为主库不可用而rt太长
// */
// testMasterWritableJT.setQueryTimeout(1);
// /**
// * 数据库健康检测
// */
// testJTList = new ArrayList<JdbcTemplate>();
// isHealthList = new ArrayList<Boolean>();
//
// tm = new DataSourceTransactionManager();
// tjt = new TransactionTemplate(tm);
// /**
// * 事务的超时时间需要与普通操作区分开
// */
// tjt.setTimeout(TRANSACTION_QUERY_TIMEOUT);
// if (!STANDALONE_MODE) {
// try {
// reload();
// } catch (IOException e) {
// e.printStackTrace();
// throw new RuntimeException(DB_LOAD_ERROR_MSG);
// }
//
// TimerTaskService.scheduleWithFixedDelay(new BasicDataSourceServiceImpl.SelectMasterTask(), 10, 10,
// TimeUnit.SECONDS);
// TimerTaskService.scheduleWithFixedDelay(new BasicDataSourceServiceImpl.CheckDBHealthTask(), 10, 10,
// TimeUnit.SECONDS);
// }
// }
//
// public synchronized void reload() throws IOException {
// List<BasicDataSource> dblist = new ArrayList<BasicDataSource>();
// try {
// String val = null;
// val = env.getProperty("db.num");
// if (null == val) {
// throw new IllegalArgumentException("db.num is null");
// }
// int dbNum = Integer.parseInt(val.trim());
//
// for (int i = 0; i < dbNum; i++) {
// BasicDataSource ds = new BasicDataSource();
// ds.setDriverClassName(JDBC_DRIVER_NAME);
//
// val = env.getProperty("db.url." + i);
// if (null == val) {
// fatalLog.error("db.url." + i + " is null");
// throw new IllegalArgumentException();
// }
// ds.setUrl(val.trim());
//
// val = env.getProperty("db.user");
// if (null == val) {
// fatalLog.error("db.user is null");
// throw new IllegalArgumentException();
// }
// ds.setUsername(val.trim());
//
// val = env.getProperty("db.password");
// if (null == val) {
// fatalLog.error("db.password is null");
// throw new IllegalArgumentException();
// }
// ds.setPassword(val.trim());
//
// val = env.getProperty("db.initialSize");
// ds.setInitialSize(Integer.parseInt(defaultIfNull(val, "10")));
//
// val = env.getProperty("db.maxActive");
// ds.setMaxActive(Integer.parseInt(defaultIfNull(val, "20")));
//
// val = env.getProperty("db.maxIdle");
// ds.setMaxIdle(Integer.parseInt(defaultIfNull(val, "50")));
//
// ds.setMaxWait(3000L);
// ds.setPoolPreparedStatements(true);
//
// // 每10分钟检查一遍连接池
// ds.setTimeBetweenEvictionRunsMillis(TimeUnit.MINUTES
// .toMillis(10L));
// ds.setTestWhileIdle(true);
// ds.setValidationQuery("SELECT 1 FROM dual");
//
// dblist.add(ds);
//
// JdbcTemplate jdbcTemplate = new JdbcTemplate();
// jdbcTemplate.setQueryTimeout(queryTimeout);
// jdbcTemplate.setDataSource(ds);
//
// testJTList.add(jdbcTemplate);
// isHealthList.add(Boolean.TRUE);
// }
//
// if (dblist == null || dblist.size() == 0) {
// throw new RuntimeException("no datasource available");
// }
//
// dataSourceList = dblist;
// new BasicDataSourceServiceImpl.SelectMasterTask().run();
// new BasicDataSourceServiceImpl.CheckDBHealthTask().run();
// } catch (RuntimeException e) {
// fatalLog.error(DB_LOAD_ERROR_MSG, e);
// throw new IOException(e);
// } finally {
// }
// }
//}

View File

@ -0,0 +1,63 @@
///*
// * Licensed to the Apache Software Foundation (ASF) under one or more
// * contributor license agreements. See the NOTICE file distributed with
// * this work for additional information regarding copyright ownership.
// * The ASF licenses this file to You under the Apache License, Version 2.0
// * (the "License"); you may not use this file except in compliance with
// * the License. You may obtain a copy of the License at
// *
// * http://www.apache.org/licenses/LICENSE-2.0
// *
// * Unless required by applicable law or agreed to in writing, software
// * distributed under the License is distributed on an "AS IS" BASIS,
// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// * See the License for the specific language governing permissions and
// * limitations under the License.
// */
//package com.alibaba.nacos.config.server.configuration;
//
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.Qualifier;
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.core.env.Environment;
//import org.springframework.jdbc.core.JdbcTemplate;
//import org.springframework.jdbc.datasource.DataSourceTransactionManager;
//import org.springframework.transaction.PlatformTransactionManager;
//
//import javax.sql.DataSource;
//
///**
// * DataBase {@link Configuration}
// *
// * @author <a href="mailto:mercyblitz@gmail.com">Mercy</a>
// * @since 0.2.2
// */
//@Configuration
//public class DataBaseConfiguration {
//
// /**
// * The bean name of {@link DataSource} for Nacos Config
// */
// public static final String DATA_SOURCE_BEAN_NAME = "nacosConfigDataSource";
//
// @Bean
// @Autowired
// public JdbcTemplate jdbcTemplate(@Qualifier(DATA_SOURCE_BEAN_NAME) DataSource dataSource, Environment environment) {
// JdbcTemplate jdbcTemplate = new JdbcTemplate();
// jdbcTemplate = new JdbcTemplate();
// jdbcTemplate.setMaxRows(50000);
// jdbcTemplate.setQueryTimeout(5000);
// jdbcTemplate.setDataSource(dataSource);
// return jdbcTemplate;
// }
//
// @Bean
// @Autowired
// public PlatformTransactionManager transactionManager(@Qualifier(DATA_SOURCE_BEAN_NAME) DataSource dataSource) {
// DataSourceTransactionManager manager = new DataSourceTransactionManager();
// manager.setDataSource(dataSource);
// return manager;
// }
//
//}

View File

@ -0,0 +1,75 @@
///*
// * Licensed to the Apache Software Foundation (ASF) under one or more
// * contributor license agreements. See the NOTICE file distributed with
// * this work for additional information regarding copyright ownership.
// * The ASF licenses this file to You under the Apache License, Version 2.0
// * (the "License"); you may not use this file except in compliance with
// * the License. You may obtain a copy of the License at
// *
// * http://www.apache.org/licenses/LICENSE-2.0
// *
// * Unless required by applicable law or agreed to in writing, software
// * distributed under the License is distributed on an "AS IS" BASIS,
// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// * See the License for the specific language governing permissions and
// * limitations under the License.
// */
//package com.alibaba.nacos.config.server.configuration;
//
//import org.apache.commons.dbcp.BasicDataSource;
//import org.springframework.context.annotation.Bean;
//import org.springframework.context.annotation.Configuration;
//import org.springframework.context.annotation.Profile;
//import org.springframework.core.env.Environment;
//
//import javax.sql.DataSource;
//import java.io.File;
//import java.util.concurrent.TimeUnit;
//
//import static com.alibaba.nacos.config.server.configuration.DataBaseConfiguration.DATA_SOURCE_BEAN_NAME;
//
///**
// * Local {@link DataSource} {@link Configuration}
// *
// * @author <a href="mailto:mercyblitz@gmail.com">Mercy</a>
// * @since 0.2.2
// */
//@Profile("standalone")
//@Configuration
//public class LocalDataSourceConfiguration {
//
// private static final String JDBC_DRIVER_NAME = "org.apache.derby.jdbc.EmbeddedDriver";
//
// private static final String DERBY_BASE_DIR = "data" + File.separator + "derby-data";
//
// private static final String NACOS_HOME_PROPERTY_NAME = "nacos.home";
//
// private static final String DEFAULT_APP_NAME = System.getProperty("user.home") + File.separator + "nacos";
//
// private static final String APP_HOME = System.getProperty(NACOS_HOME_PROPERTY_NAME, DEFAULT_APP_NAME);
//
// private static final String DATA_SOURCE_URL = "jdbc:derby:" + APP_HOME + File.separator + DERBY_BASE_DIR +
// ";create=true";
//
// private static final String USER_NAME = "nacos";
//
// private static final String PASSWORD = "nacos";
//
// @Bean(name = DATA_SOURCE_BEAN_NAME,destroyMethod = "close")
// public DataSource nacosConfigDataSource(Environment environment) {
// BasicDataSource ds = new BasicDataSource();
// ds.setDriverClassName(JDBC_DRIVER_NAME);
// ds.setUrl(DATA_SOURCE_URL);
// ds.setUsername(USER_NAME);
// ds.setPassword(PASSWORD);
// ds.setInitialSize(environment.getProperty("db.initialSize", int.class, 20));
// ds.setMaxActive(environment.getProperty("db.maxActive", int.class, 30));
// ds.setMaxIdle(environment.getProperty("db.maxIdle", int.class, 50));
// ds.setMaxWait(environment.getProperty("db.maxWait", long.class, 10000L));
// ds.setPoolPreparedStatements(true);
// ds.setTimeBetweenEvictionRunsMillis(TimeUnit.MINUTES.toMillis(10L));
// ds.setTestWhileIdle(true);
// return ds;
// }
//
//}

View File

@ -0,0 +1,29 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.configuration;
import org.springframework.context.annotation.Configuration;
/**
* Nacos Config {@link Configuration} includes required Spring components.
*
* @author <a href="mailto:mercyblitz@gmail.com">Mercy</a>
* @since 0.2.2
*/
@Configuration
public class NacosConfigConfiguration {
}

View File

@ -17,8 +17,8 @@ package com.alibaba.nacos.config.server.constant;
/** /**
* Server Constants * Server Constants
* @author Nacos
* *
* @author Nacos
*/ */
public class Constants { public class Constants {
@ -27,21 +27,21 @@ public class Constants {
public static final String CLIENT_VERSION = "3.0.0"; public static final String CLIENT_VERSION = "3.0.0";
public static int DATA_IN_BODY_VERSION = 204; public static int DATA_IN_BODY_VERSION = 204;
public static final String DEFAULT_GROUP = "DEFAULT_GROUP"; public static final String DEFAULT_GROUP = "DEFAULT_GROUP";
/** /**
* server端配置文件基目录 * server端配置文件基目录
*/ */
public static final String BASE_DIR = "config-data"; public static final String BASE_DIR = "config-data";
/** /**
* server端配置文件备份目录 * server端配置文件备份目录
*/ */
public static final String CONFIG_BAK_DIR = System.getProperty("user.home", "/home/admin") + "/nacos/bak_data"; public static final String CONFIG_BAK_DIR = System.getProperty("user.home", "/home/admin") + "/nacos/bak_data";
public static final String APPNAME = "AppName"; public static final String APPNAME = "AppName";
public static final String UNKNOWN_APP = "UnknownApp"; public static final String UNKNOWN_APP = "UnknownApp";
public static final String DEFAULT_DOMAINNAME = "commonconfig.config-host.taobao.com"; public static final String DEFAULT_DOMAINNAME = "commonconfig.config-host.taobao.com";
@ -79,7 +79,7 @@ public class Constants {
/** /**
* *
*/ */
public static final int ASYNC_UPDATE_ADDRESS_INTERVAL = 300; public static final int ASYNC_UPDATE_ADDRESS_INTERVAL = 300;
/** /**
* *
*/ */
@ -101,24 +101,44 @@ public class Constants {
*/ */
public static final int RECV_WAIT_TIMEOUT = ONCE_TIMEOUT * 5; public static final int RECV_WAIT_TIMEOUT = ONCE_TIMEOUT * 5;
public static final String BASE_PATH = "/v1/cs"; public static final String BASE_PATH = "/nacos/v1/cs";
public static final String OPS_CONTROLLER_PATH = BASE_PATH + "/ops";
public static final String CAPACITY_CONTROLLER_PATH = BASE_PATH + "/capacity"; public static final String DEFAULT_OPS_CONTROLLER_PATH = BASE_PATH + "/ops";
public static final String COMMUNICATION_CONTROLLER_PATH = BASE_PATH + "/communication";
public static final String CONFIG_CONTROLLER_PATH = BASE_PATH + "/configs";
public static final String HEALTH_CONTROLLER_PATH = BASE_PATH + "/health";
public static final String HISTORY_CONTROLLER_PATH = BASE_PATH + "/history"; public static final String OPS_CONTROLLER_PATH = "${nacos.config.ops.path" + ":" + DEFAULT_OPS_CONTROLLER_PATH + "}";
public static final String DEFAULT_CAPACITY_CONTROLLER_PATH = BASE_PATH + "/capacity";
public static final String CAPACITY_CONTROLLER_PATH = "${nacos.config.capacity.path" + ":" + DEFAULT_CAPACITY_CONTROLLER_PATH + "}";
public static final String DEFAULT_COMMUNICATION_CONTROLLER_PATH = BASE_PATH + "/communication";
// public static final String COMMUNICATION_CONTROLLER_PATH = "${nacos.config.communication.path" + ":" + DEFAULT_COMMUNICATION_CONTROLLER_PATH + "}";
public static final String COMMUNICATION_CONTROLLER_PATH = DEFAULT_COMMUNICATION_CONTROLLER_PATH;
public static final String DEFAULT_CONFIG_CONTROLLER_PATH = BASE_PATH + "/configs";
public static final String CONFIG_CONTROLLER_PATH = "${nacos.config.path" + ":" + DEFAULT_CONFIG_CONTROLLER_PATH + "}";
public static final String DEFAULT_HEALTH_CONTROLLER_PATH = BASE_PATH + "/health";
// public static final String HEALTH_CONTROLLER_PATH = "${nacos.config.health.path" + ":" + DEFAULT_HEALTH_CONTROLLER_PATH + "}";
public static final String HEALTH_CONTROLLER_PATH = DEFAULT_HEALTH_CONTROLLER_PATH;
public static final String DEFAULT_HISTORY_CONTROLLER_PATH = BASE_PATH + "/history";
public static final String HISTORY_CONTROLLER_PATH = "${nacos.config.history.path" + ":" + DEFAULT_HISTORY_CONTROLLER_PATH + "}";
public static final String DEFAULT_LISTENER_CONTROLLER_PATH = BASE_PATH + "/listener";
public static final String LISTENER_CONTROLLER_PATH = "${nacos.config.listener.path" + ":" + DEFAULT_LISTENER_CONTROLLER_PATH + "}";
public static final String DEFAULT_NAMESPACE_CONTROLLER_PATH = BASE_PATH + "/namespaces";
public static final String NAMESPACE_CONTROLLER_PATH = "${nacos.config.namespaces.path" + ":" + DEFAULT_NAMESPACE_CONTROLLER_PATH + "}";
public static final String LISTENER_CONTROLLER_PATH = BASE_PATH + "/listener";
public static final String NAMESPACE_CONTROLLER_PATH = BASE_PATH + "/namespaces";
public static final String ENCODE = "UTF-8"; public static final String ENCODE = "UTF-8";
public static final String MAP_FILE = "map-file.js"; public static final String MAP_FILE = "map-file.js";
@ -136,36 +156,36 @@ public class Constants {
public static final String NACOS_LINE_SEPARATOR = "\r\n"; public static final String NACOS_LINE_SEPARATOR = "\r\n";
/** /**
* 从网络获取数据的总时间, 当超过此时间, 不再从网络获取数据, 单位ms * 从网络获取数据的总时间, 当超过此时间, 不再从网络获取数据, 单位ms
*/ */
public static final long TOTALTIME_FROM_SERVER = 10000; public static final long TOTALTIME_FROM_SERVER = 10000;
/** /**
* 从网络获取数据的总时间的失效时间, 单位ms * 从网络获取数据的总时间的失效时间, 单位ms
*/ */
public static final long TOTALTIME_INVALID_THRESHOLD = 60000; public static final long TOTALTIME_INVALID_THRESHOLD = 60000;
/** /**
* 发生异常 * 发生异常
*/ */
public static final int BATCH_OP_ERROR = -1; public static final int BATCH_OP_ERROR = -1;
public static final String BATCH_OP_ERROR_IO_MSG = "get config dump error"; public static final String BATCH_OP_ERROR_IO_MSG = "get config dump error";
public static final String BATCH_OP_ERROR_CONFLICT_MSG = "config get conflicts"; public static final String BATCH_OP_ERROR_CONFLICT_MSG = "config get conflicts";
/** /**
* 查询成功, 数据存在 * 查询成功, 数据存在
*/ */
public static final int BATCH_QUERY_EXISTS = 1; public static final int BATCH_QUERY_EXISTS = 1;
public static final String BATCH_QUERY_EXISTS_MSG = "config exits"; public static final String BATCH_QUERY_EXISTS_MSG = "config exits";
/** /**
* 查询成功, 数据不存在 * 查询成功, 数据不存在
*/ */
public static final int BATCH_QUERY_NONEXISTS = 2; public static final int BATCH_QUERY_NONEXISTS = 2;
public static final String BATCH_QUERY_NONEEXISTS_MSG = "config not exits"; public static final String BATCH_QUERY_NONEEXISTS_MSG = "config not exits";
/** /**
* 新增成功 * 新增成功
*/ */
public static final int BATCH_ADD_SUCCESS = 3; public static final int BATCH_ADD_SUCCESS = 3;
/** /**
* 更新成功 * 更新成功
*/ */
public static final int BATCH_UPDATE_SUCCESS = 4; public static final int BATCH_UPDATE_SUCCESS = 4;
@ -177,20 +197,20 @@ public class Constants {
public static final int MAX_ADDACK_COUNT = 5; public static final int MAX_ADDACK_COUNT = 5;
/** /**
* 数据的初始版本号 * 数据的初始版本号
*/ */
public static final int FIRST_VERSION = 1; public static final int FIRST_VERSION = 1;
/** /**
* 数据被删除的标识版本号 * 数据被删除的标识版本号
*/ */
public static final int POISON_VERSION = -1; public static final int POISON_VERSION = -1;
/** /**
* 写磁盘文件时, 临时版本号 * 写磁盘文件时, 临时版本号
*/ */
public static final int TEMP_VERSION = 0; public static final int TEMP_VERSION = 0;
/** /**
* 获取数据的顺序容灾文件-> 服务器 -> 本地缓存 * 获取数据的顺序容灾文件-> 服务器 -> 本地缓存
*/ */
public static final int GETCONFIG_LOCAL_SERVER_SNAPSHOT = 1; public static final int GETCONFIG_LOCAL_SERVER_SNAPSHOT = 1;
/** /**
* 获取数据的顺序容灾文件-> 本地缓存 -> 服务器 * 获取数据的顺序容灾文件-> 本地缓存 -> 服务器
@ -201,13 +221,13 @@ public class Constants {
public static final String CLIENT_REQUEST_TS_HEADER = "Client-RequestTS"; public static final String CLIENT_REQUEST_TS_HEADER = "Client-RequestTS";
public static final String CLIENT_REQUEST_TOKEN_HEADER = "Client-RequestToken"; public static final String CLIENT_REQUEST_TOKEN_HEADER = "Client-RequestToken";
/** /**
* client, sdk请求server服务的身份 * client, sdk请求server服务的身份
*/ */
public static final String REQUEST_IDENTITY = "Request-Identity"; public static final String REQUEST_IDENTITY = "Request-Identity";
/** /**
* 鉴权结果信息 * 鉴权结果信息
*/ */
public static final String ACL_RESPONSE = "ACL-Response"; public static final String ACL_RESPONSE = "ACL-Response";
public static final int ATOMIC_MAX_SIZE = 1000; public static final int ATOMIC_MAX_SIZE = 1000;
} }

View File

@ -15,9 +15,11 @@
*/ */
package com.alibaba.nacos.config.server.controller; package com.alibaba.nacos.config.server.controller;
import javax.servlet.http.HttpServletResponse; import com.alibaba.nacos.config.server.constant.Constants;
import com.alibaba.nacos.config.server.model.RestResult;
import org.apache.commons.lang.StringUtils; import com.alibaba.nacos.config.server.model.capacity.Capacity;
import com.alibaba.nacos.config.server.service.capacity.CapacityService;
import org.apache.commons.lang3.StringUtils;
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;
@ -27,10 +29,7 @@ import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.nacos.config.server.constant.Constants; import javax.servlet.http.HttpServletResponse;
import com.alibaba.nacos.config.server.model.RestResult;
import com.alibaba.nacos.config.server.model.capacity.Capacity;
import com.alibaba.nacos.config.server.service.capacity.CapacityService;
/** /**
* capcity manage * capcity manage

View File

@ -15,13 +15,12 @@
*/ */
package com.alibaba.nacos.config.server.controller; package com.alibaba.nacos.config.server.controller;
import java.io.IOException; import com.alibaba.nacos.config.server.constant.Constants;
import com.alibaba.nacos.config.server.model.SampleResult;
import javax.servlet.ServletException; import com.alibaba.nacos.config.server.service.LongPollingService;
import javax.servlet.http.HttpServletRequest; import com.alibaba.nacos.config.server.service.dump.DumpService;
import javax.servlet.http.HttpServletResponse; import com.alibaba.nacos.config.server.service.notify.NotifyService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap; import org.springframework.ui.ModelMap;
@ -30,11 +29,10 @@ import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.nacos.config.server.constant.Constants; import javax.servlet.ServletException;
import com.alibaba.nacos.config.server.model.SampleResult; import javax.servlet.http.HttpServletRequest;
import com.alibaba.nacos.config.server.service.LongPullingService; import javax.servlet.http.HttpServletResponse;
import com.alibaba.nacos.config.server.service.dump.DumpService; import java.io.IOException;
import com.alibaba.nacos.config.server.service.notify.NotifyService;
/** /**
@ -51,7 +49,7 @@ public class CommunicationController {
private DumpService dumpService; private DumpService dumpService;
@Autowired @Autowired
protected LongPullingService longPullingService; protected LongPollingService longPollingService;
private String trueStr = "true"; private String trueStr = "true";
@ -92,7 +90,7 @@ public class CommunicationController {
ModelMap modelMap) ModelMap modelMap)
throws IOException, ServletException, Exception { throws IOException, ServletException, Exception {
group = StringUtils.isBlank(group) ? Constants.DEFAULT_GROUP : group; group = StringUtils.isBlank(group) ? Constants.DEFAULT_GROUP : group;
SampleResult sampleResult = longPullingService.getCollectSubscribleInfo(dataId, group, tenant); SampleResult sampleResult = longPollingService.getCollectSubscribleInfo(dataId, group, tenant);
return sampleResult; return sampleResult;
} }
@ -106,7 +104,7 @@ public class CommunicationController {
@RequestParam("ip") String ip, @RequestParam("ip") String ip,
ModelMap modelMap) ModelMap modelMap)
throws IOException, ServletException, Exception { throws IOException, ServletException, Exception {
SampleResult sampleResult = longPullingService.getCollectSubscribleInfoByIp(ip); SampleResult sampleResult = longPollingService.getCollectSubscribleInfoByIp(ip);
return sampleResult; return sampleResult;
} }
} }

View File

@ -15,6 +15,7 @@
*/ */
package com.alibaba.nacos.config.server.controller; package com.alibaba.nacos.config.server.controller;
import java.io.IOException; import java.io.IOException;
import java.net.URLDecoder; import java.net.URLDecoder;
import java.sql.Timestamp; import java.sql.Timestamp;
@ -34,26 +35,35 @@ import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.nacos.config.server.constant.Constants; import com.alibaba.nacos.config.server.constant.Constants;
import com.alibaba.nacos.config.server.exception.NacosException; import com.alibaba.nacos.config.server.exception.NacosException;
import com.alibaba.nacos.config.server.model.ConfigAdvanceInfo; import com.alibaba.nacos.config.server.model.*;
import com.alibaba.nacos.config.server.model.ConfigAllInfo;
import com.alibaba.nacos.config.server.model.ConfigInfo;
import com.alibaba.nacos.config.server.model.ConfigInfo4Beta;
import com.alibaba.nacos.config.server.model.GroupkeyListenserStatus;
import com.alibaba.nacos.config.server.model.Page;
import com.alibaba.nacos.config.server.model.RestResult;
import com.alibaba.nacos.config.server.model.SampleResult;
import com.alibaba.nacos.config.server.service.AggrWhitelist; import com.alibaba.nacos.config.server.service.AggrWhitelist;
import com.alibaba.nacos.config.server.service.ConfigDataChangeEvent; import com.alibaba.nacos.config.server.service.ConfigDataChangeEvent;
import com.alibaba.nacos.config.server.service.ConfigSubService; import com.alibaba.nacos.config.server.service.ConfigSubService;
import com.alibaba.nacos.config.server.service.PersistService; import com.alibaba.nacos.config.server.service.PersistService;
import com.alibaba.nacos.config.server.service.merge.MergeDatumService; import com.alibaba.nacos.config.server.service.merge.MergeDatumService;
import com.alibaba.nacos.config.server.service.trace.ConfigTraceService; import com.alibaba.nacos.config.server.service.trace.ConfigTraceService;
import com.alibaba.nacos.config.server.utils.MD5Util; import com.alibaba.nacos.config.server.utils.*;
import com.alibaba.nacos.config.server.utils.ParamUtils;
import com.alibaba.nacos.config.server.utils.RequestUtil;
import com.alibaba.nacos.config.server.utils.SystemConfig;
import com.alibaba.nacos.config.server.utils.TimeUtils;
import com.alibaba.nacos.config.server.utils.event.EventDispatcher; import com.alibaba.nacos.config.server.utils.event.EventDispatcher;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.Map;
/** /**
* 软负载客户端发布数据专用控制器 * 软负载客户端发布数据专用控制器

View File

@ -15,8 +15,22 @@
*/ */
package com.alibaba.nacos.config.server.controller; package com.alibaba.nacos.config.server.controller;
import static com.alibaba.nacos.config.server.utils.LogUtil.pullLog; import com.alibaba.nacos.config.server.constant.Constants;
import com.alibaba.nacos.config.server.model.CacheItem;
import com.alibaba.nacos.config.server.model.ConfigInfoBase;
import com.alibaba.nacos.config.server.service.ConfigService;
import com.alibaba.nacos.config.server.service.DiskUtil;
import com.alibaba.nacos.config.server.service.LongPollingService;
import com.alibaba.nacos.config.server.service.PersistService;
import com.alibaba.nacos.config.server.service.trace.ConfigTraceService;
import com.alibaba.nacos.config.server.utils.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
@ -27,29 +41,8 @@ import java.nio.charset.StandardCharsets;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import javax.servlet.ServletException; import static com.alibaba.nacos.common.util.SystemUtils.STANDALONE_MODE;
import javax.servlet.http.HttpServletRequest; import static com.alibaba.nacos.config.server.utils.LogUtil.pullLog;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.nacos.config.server.constant.Constants;
import com.alibaba.nacos.config.server.model.CacheItem;
import com.alibaba.nacos.config.server.model.ConfigInfoBase;
import com.alibaba.nacos.config.server.service.ConfigService;
import com.alibaba.nacos.config.server.service.DiskUtil;
import com.alibaba.nacos.config.server.service.LongPullingService;
import com.alibaba.nacos.config.server.service.PersistService;
import com.alibaba.nacos.config.server.service.trace.ConfigTraceService;
import com.alibaba.nacos.config.server.utils.GroupKey2;
import com.alibaba.nacos.config.server.utils.LogUtil;
import com.alibaba.nacos.config.server.utils.MD5Util;
import com.alibaba.nacos.config.server.utils.PropertyUtil;
import com.alibaba.nacos.config.server.utils.Protocol;
import com.alibaba.nacos.config.server.utils.RequestUtil;
import com.alibaba.nacos.config.server.utils.TimeUtils;
/** /**
* ConfigServlet inner for aop * ConfigServlet inner for aop
@ -60,7 +53,7 @@ import com.alibaba.nacos.config.server.utils.TimeUtils;
public class ConfigServletInner { public class ConfigServletInner {
@Autowired @Autowired
private LongPullingService longPullingService; private LongPollingService longPollingService;
@Autowired @Autowired
private PersistService persistService; private PersistService persistService;
@ -74,8 +67,8 @@ public class ConfigServletInner {
public String doPollingConfig(HttpServletRequest request, HttpServletResponse response, Map<String, String> clientMd5Map, int probeRequestSize) throws IOException, ServletException { public String doPollingConfig(HttpServletRequest request, HttpServletResponse response, Map<String, String> clientMd5Map, int probeRequestSize) throws IOException, ServletException {
// 长轮询 // 长轮询
if (LongPullingService.isSupportLongPulling(request)) { if (LongPollingService.isSupportLongPulling(request)) {
longPullingService.addLongPullingClient(request, response, clientMd5Map, probeRequestSize); longPollingService.addLongPullingClient(request, response, clientMd5Map, probeRequestSize);
return HttpServletResponse.SC_OK + ""; return HttpServletResponse.SC_OK + "";
} }
@ -141,7 +134,7 @@ public class ConfigServletInner {
if (isBeta) { if (isBeta) {
md5 = cacheItem.getMd54Beta(); md5 = cacheItem.getMd54Beta();
lastModified = cacheItem.getLastModifiedTs4Beta(); lastModified = cacheItem.getLastModifiedTs4Beta();
if (PropertyUtil.isStandaloneMode()) { if (STANDALONE_MODE) {
configInfoBase = persistService.findConfigInfo4Beta(dataId, group,tenant); configInfoBase = persistService.findConfigInfo4Beta(dataId, group,tenant);
} else { } else {
file = DiskUtil.targetBetaFile(dataId, group, tenant); file = DiskUtil.targetBetaFile(dataId, group, tenant);
@ -158,7 +151,7 @@ public class ConfigServletInner {
lastModified = cacheItem.tagLastModifiedTs.get(autoTag); lastModified = cacheItem.tagLastModifiedTs.get(autoTag);
} }
} }
if (PropertyUtil.isStandaloneMode()) { if (STANDALONE_MODE) {
configInfoBase = persistService.findConfigInfo4Tag(dataId, group, tenant, autoTag); configInfoBase = persistService.findConfigInfo4Tag(dataId, group, tenant, autoTag);
} else { } else {
file = DiskUtil.targetTagFile(dataId, group, tenant, autoTag); file = DiskUtil.targetTagFile(dataId, group, tenant, autoTag);
@ -169,7 +162,7 @@ public class ConfigServletInner {
} else { } else {
md5 = cacheItem.getMd5(); md5 = cacheItem.getMd5();
lastModified = cacheItem.getLastModifiedTs(); lastModified = cacheItem.getLastModifiedTs();
if (PropertyUtil.isStandaloneMode()) { if (STANDALONE_MODE) {
configInfoBase = persistService.findConfigInfo(dataId, group, tenant); configInfoBase = persistService.findConfigInfo(dataId, group, tenant);
} else { } else {
file = DiskUtil.targetFile(dataId, group, tenant); file = DiskUtil.targetFile(dataId, group, tenant);
@ -201,7 +194,7 @@ public class ConfigServletInner {
} }
} }
} }
if (PropertyUtil.isStandaloneMode()) { if (STANDALONE_MODE) {
configInfoBase = persistService.findConfigInfo4Tag(dataId, group, tenant, tag); configInfoBase = persistService.findConfigInfo4Tag(dataId, group, tenant, tag);
} else { } else {
file = DiskUtil.targetTagFile(dataId, group, tenant, tag); file = DiskUtil.targetTagFile(dataId, group, tenant, tag);
@ -230,7 +223,7 @@ public class ConfigServletInner {
response.setHeader("Pragma", "no-cache"); response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0); response.setDateHeader("Expires", 0);
response.setHeader("Cache-Control", "no-cache,no-store"); response.setHeader("Cache-Control", "no-cache,no-store");
if (PropertyUtil.isStandaloneMode()) { if (STANDALONE_MODE) {
response.setDateHeader("Last-Modified", lastModified); response.setDateHeader("Last-Modified", lastModified);
} else { } else {
fis = new FileInputStream(file); fis = new FileInputStream(file);
@ -238,7 +231,7 @@ public class ConfigServletInner {
} }
if (PropertyUtil.isStandaloneMode()) { if (STANDALONE_MODE) {
out = response.getWriter(); out = response.getWriter();
out.print(configInfoBase.getContent()); out.print(configInfoBase.getContent());
out.flush(); out.flush();

View File

@ -15,17 +15,18 @@
*/ */
package com.alibaba.nacos.config.server.controller; package com.alibaba.nacos.config.server.controller;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.nacos.config.server.constant.Constants; import com.alibaba.nacos.config.server.constant.Constants;
import com.alibaba.nacos.config.server.service.DataSourceService; import com.alibaba.nacos.config.server.service.DataSourceService;
import com.alibaba.nacos.config.server.service.DynamicDataSource; import com.alibaba.nacos.config.server.service.DynamicDataSource;
import com.alibaba.nacos.config.server.service.ServerListService; import com.alibaba.nacos.config.server.service.ServerListService;
import com.alibaba.nacos.config.server.utils.SystemConfig; import com.alibaba.nacos.config.server.utils.SystemConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.PostConstruct;
/** /**
* health service * health service

View File

@ -15,10 +15,11 @@
*/ */
package com.alibaba.nacos.config.server.controller; package com.alibaba.nacos.config.server.controller;
import javax.servlet.http.HttpServletRequest; import com.alibaba.nacos.config.server.constant.Constants;
import javax.servlet.http.HttpServletResponse; import com.alibaba.nacos.config.server.model.ConfigHistoryInfo;
import com.alibaba.nacos.config.server.model.Page;
import org.apache.commons.lang.StringUtils; import com.alibaba.nacos.config.server.service.PersistService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap; import org.springframework.ui.ModelMap;
@ -27,10 +28,8 @@ import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.nacos.config.server.constant.Constants; import javax.servlet.http.HttpServletRequest;
import com.alibaba.nacos.config.server.model.ConfigHistoryInfo; import javax.servlet.http.HttpServletResponse;
import com.alibaba.nacos.config.server.model.Page;
import com.alibaba.nacos.config.server.service.PersistService;
/** /**
* 管理控制器 * 管理控制器

View File

@ -15,15 +15,12 @@
*/ */
package com.alibaba.nacos.config.server.controller; package com.alibaba.nacos.config.server.controller;
import java.io.IOException; import com.alibaba.nacos.config.server.constant.Constants;
import java.util.HashMap; import com.alibaba.nacos.config.server.model.GroupkeyListenserStatus;
import java.util.Map; import com.alibaba.nacos.config.server.model.SampleResult;
import com.alibaba.nacos.config.server.service.ConfigSubService;
import javax.servlet.ServletException; import com.alibaba.nacos.config.server.utils.GroupKey2;
import javax.servlet.http.HttpServletRequest; import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap; import org.springframework.ui.ModelMap;
@ -32,11 +29,12 @@ import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.nacos.config.server.constant.Constants; import javax.servlet.ServletException;
import com.alibaba.nacos.config.server.model.GroupkeyListenserStatus; import javax.servlet.http.HttpServletRequest;
import com.alibaba.nacos.config.server.model.SampleResult; import javax.servlet.http.HttpServletResponse;
import com.alibaba.nacos.config.server.service.ConfigSubService; import java.io.IOException;
import com.alibaba.nacos.config.server.utils.GroupKey2; import java.util.HashMap;
import java.util.Map;
/** /**
* Config longpulling * Config longpulling

View File

@ -15,9 +15,9 @@
*/ */
package com.alibaba.nacos.config.server.controller; package com.alibaba.nacos.config.server.controller;
import javax.servlet.http.HttpServletRequest; import com.alibaba.nacos.config.server.constant.Constants;
import javax.servlet.http.HttpServletResponse; import com.alibaba.nacos.config.server.service.PersistService;
import com.alibaba.nacos.config.server.service.dump.DumpService;
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;
@ -26,9 +26,8 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.nacos.config.server.constant.Constants; import javax.servlet.http.HttpServletRequest;
import com.alibaba.nacos.config.server.service.PersistService; import javax.servlet.http.HttpServletResponse;
import com.alibaba.nacos.config.server.service.dump.DumpService;
/** /**
* 管理控制器 * 管理控制器

View File

@ -15,13 +15,12 @@
*/ */
package com.alibaba.nacos.config.server.exception; package com.alibaba.nacos.config.server.exception;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ExceptionHandler;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/** /**
* global exception handler * global exception handler
* *

View File

@ -15,19 +15,14 @@
*/ */
package com.alibaba.nacos.config.server.filter; package com.alibaba.nacos.config.server.filter;
import static com.alibaba.nacos.config.server.utils.LogUtil.defaultLog; import com.alibaba.nacos.config.server.constant.Constants;
import org.springframework.core.annotation.Order;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException; import java.io.IOException;
import javax.servlet.Filter; import static com.alibaba.nacos.config.server.utils.LogUtil.defaultLog;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.springframework.core.annotation.Order;
import com.alibaba.nacos.config.server.constant.Constants;
/** /**
* encode filter * encode filter
@ -36,8 +31,8 @@ import com.alibaba.nacos.config.server.constant.Constants;
* *
*/ */
@Order(1) @Order(1)
@javax.servlet.annotation.WebFilter(filterName = "webFilter", urlPatterns = "/*") @WebFilter(filterName = "webFilter", urlPatterns = "/*")
public class WebFilter implements Filter { public class NacosWebFilter implements Filter {
static private String webRootPath; static private String webRootPath;

View File

@ -15,6 +15,11 @@
*/ */
package com.alibaba.nacos.config.server.manager; package com.alibaba.nacos.config.server.manager;
import com.alibaba.nacos.config.server.constant.Constants;
import com.alibaba.nacos.config.server.utils.LogUtil;
import org.slf4j.Logger;
import javax.management.ObjectName;
import java.lang.management.ManagementFactory; import java.lang.management.ManagementFactory;
import java.util.Date; import java.util.Date;
import java.util.Map; import java.util.Map;
@ -23,11 +28,6 @@ import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantLock;
import javax.management.ObjectName;
import org.slf4j.Logger;
import com.alibaba.nacos.config.server.constant.Constants;
import com.alibaba.nacos.config.server.utils.LogUtil;
/** /**

View File

@ -15,12 +15,12 @@
*/ */
package com.alibaba.nacos.config.server.model; package com.alibaba.nacos.config.server.model;
import java.util.List;
import java.util.Map;
import com.alibaba.nacos.config.server.constant.Constants; import com.alibaba.nacos.config.server.constant.Constants;
import com.alibaba.nacos.config.server.utils.SimpleReadWriteLock; import com.alibaba.nacos.config.server.utils.SimpleReadWriteLock;
import com.alibaba.nacos.config.server.utils.SingletonRepository.DataIdGroupIdCache; import com.alibaba.nacos.config.server.utils.SingletonRepository.DataIdGroupIdCache;
import java.util.List;
import java.util.Map;
/** /**
* cache item * cache item
* @author Nacos * @author Nacos

View File

@ -15,11 +15,11 @@
*/ */
package com.alibaba.nacos.config.server.model; package com.alibaba.nacos.config.server.model;
import com.alibaba.nacos.config.server.utils.MD5;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.io.Serializable; import java.io.Serializable;
import com.alibaba.nacos.config.server.utils.MD5;
/** /**
* 不能增加字段为了兼容老前台接口老接口增加一个字段会出现不兼容问题设置的model * 不能增加字段为了兼容老前台接口老接口增加一个字段会出现不兼容问题设置的model
* *

View File

@ -15,15 +15,17 @@
*/ */
package com.alibaba.nacos.config.server.monitor; package com.alibaba.nacos.config.server.monitor;
import static com.alibaba.nacos.config.server.utils.LogUtil.memoryLog;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.nacos.config.server.service.ClientTrackService; import com.alibaba.nacos.config.server.service.ClientTrackService;
import com.alibaba.nacos.config.server.service.ConfigService; import com.alibaba.nacos.config.server.service.ConfigService;
import com.alibaba.nacos.config.server.service.TimerTaskService; import com.alibaba.nacos.config.server.service.TimerTaskService;
import com.alibaba.nacos.config.server.service.notify.AsyncNotifyService; import com.alibaba.nacos.config.server.service.notify.AsyncNotifyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import static com.alibaba.nacos.config.server.utils.LogUtil.memoryLog;
/** /**
* Memory monitor * Memory monitor

View File

@ -20,78 +20,61 @@ import java.util.concurrent.atomic.AtomicLong;
/** /**
* Response Monitory * Response Monitory
*
* @author Nacos
* *
* @author Nacos
*/ */
public class ResponseMonitor { public class ResponseMonitor {
static AtomicLong[] getConfigCountDetail = new AtomicLong[8]; static AtomicLong[] getConfigCountDetail = new AtomicLong[8];
static AtomicLong getConfigCount = new AtomicLong(); static AtomicLong getConfigCount = new AtomicLong();
private static final int MS_50 = 50; private static final int MS_50 = 50;
private static final int MS_100 = 100; private static final int MS_100 = 100;
private static final int MS_200 = 200; private static final int MS_200 = 200;
private static final int MS_500 = 500; private static final int MS_500 = 500;
private static final int MS_1000 = 1000; private static final int MS_1000 = 1000;
private static final int MS_2000 = 2000; private static final int MS_2000 = 2000;
private static final int MS_3000 = 3000; private static final int MS_3000 = 3000;
static{ static {
refresh(); refresh();
} }
public static void refresh(){ public static void refresh() {
for(int i = 0; i< getConfigCountDetail.length;i++){ for (int i = 0; i < getConfigCountDetail.length; i++) {
getConfigCountDetail[i] = new AtomicLong(); getConfigCountDetail[i] = new AtomicLong();
} }
} }
public static void addConfigTime(long time){ public static void addConfigTime(long time) {
getConfigCount.incrementAndGet(); getConfigCount.incrementAndGet();
if(time < MS_50){ if (time < MS_50) {
getConfigCountDetail[0].incrementAndGet(); getConfigCountDetail[0].incrementAndGet();
} else if(time < MS_100) { } else if (time < MS_100) {
getConfigCountDetail[1].incrementAndGet(); getConfigCountDetail[1].incrementAndGet();
} else if (time < MS_200){ } else if (time < MS_200) {
getConfigCountDetail[2].incrementAndGet(); getConfigCountDetail[2].incrementAndGet();
} else if(time < MS_500){ } else if (time < MS_500) {
getConfigCountDetail[3].incrementAndGet(); getConfigCountDetail[3].incrementAndGet();
} else if(time < MS_1000){ } else if (time < MS_1000) {
getConfigCountDetail[4].incrementAndGet(); getConfigCountDetail[4].incrementAndGet();
} else if(time < MS_2000){ } else if (time < MS_2000) {
getConfigCountDetail[5].incrementAndGet(); getConfigCountDetail[5].incrementAndGet();
} else if(time < MS_3000){ } else if (time < MS_3000) {
getConfigCountDetail[6].incrementAndGet(); getConfigCountDetail[6].incrementAndGet();
} else { } else {
getConfigCountDetail[7].incrementAndGet(); getConfigCountDetail[7].incrementAndGet();
} }
} }
public static String getStringForPrint(){ public static String getStringForPrint() {
DecimalFormat df = new DecimalFormat("##.0"); DecimalFormat df = new DecimalFormat("##.0");
StringBuilder s = new StringBuilder("getConfig monitor:\r\n"); StringBuilder s = new StringBuilder("getConfig monitor:\r\n");
s.append("0-50ms:" + df.format(getConfigCountDetail[0].getAndSet(0)*100/ getConfigCount.get())).append("%\r\n"); s.append("0-50ms:" + df.format(getConfigCountDetail[0].getAndSet(0) * 100 / getConfigCount.get())).append("%\r\n");
s.append("100-200ms:" + df.format(getConfigCountDetail[2].getAndSet(0)*100/ getConfigCount.get())).append("%\r\n"); s.append("100-200ms:" + df.format(getConfigCountDetail[2].getAndSet(0) * 100 / getConfigCount.get())).append("%\r\n");
s.append("200-500ms:" + df.format(getConfigCountDetail[3].getAndSet(0)*100/ getConfigCount.get())).append("%\r\n"); s.append("200-500ms:" + df.format(getConfigCountDetail[3].getAndSet(0) * 100 / getConfigCount.get())).append("%\r\n");
s.append("500-1000ms:" + df.format(getConfigCountDetail[4].getAndSet(0)*100/ getConfigCount.get())).append("%\r\n"); s.append("500-1000ms:" + df.format(getConfigCountDetail[4].getAndSet(0) * 100 / getConfigCount.get())).append("%\r\n");
s.append("1000-2000ms:" + df.format(getConfigCountDetail[5].getAndSet(0)*100/ getConfigCount.get())).append("%\r\n"); s.append("1000-2000ms:" + df.format(getConfigCountDetail[5].getAndSet(0) * 100 / getConfigCount.get())).append("%\r\n");
s.append("2000-3000ms:" + df.format(getConfigCountDetail[6].getAndSet(0)*100/ getConfigCount.get())).append("%\r\n"); s.append("2000-3000ms:" + df.format(getConfigCountDetail[6].getAndSet(0) * 100 / getConfigCount.get())).append("%\r\n");
s.append("3000以上ms:" + df.format(getConfigCountDetail[7].getAndSet(0)*100/ getConfigCount.getAndSet(0))).append("%\r\n"); s.append("3000以上ms:" + df.format(getConfigCountDetail[7].getAndSet(0) * 100 / getConfigCount.getAndSet(0))).append("%\r\n");
return s.toString(); return s.toString();
} }
public static void main(String[] args) {
ResponseMonitor.addConfigTime(10);
ResponseMonitor.addConfigTime(10);
ResponseMonitor.addConfigTime(10);
ResponseMonitor.addConfigTime(10);
ResponseMonitor.addConfigTime(100);
ResponseMonitor.addConfigTime(150);
ResponseMonitor.addConfigTime(250);
ResponseMonitor.addConfigTime(350);
ResponseMonitor.addConfigTime(750);
ResponseMonitor.addConfigTime(15000);
System.out.println(ResponseMonitor.getStringForPrint());
System.out.println(ResponseMonitor.getStringForPrint());
}
} }

View File

@ -15,8 +15,10 @@
*/ */
package com.alibaba.nacos.config.server.service; package com.alibaba.nacos.config.server.service;
import static com.alibaba.nacos.config.server.utils.LogUtil.defaultLog; import com.alibaba.nacos.config.server.utils.RegexParser;
import static com.alibaba.nacos.config.server.utils.LogUtil.fatalLog; import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import java.io.StringReader; import java.io.StringReader;
import java.util.ArrayList; import java.util.ArrayList;
@ -24,11 +26,8 @@ import java.util.List;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import org.apache.commons.io.IOUtils; import static com.alibaba.nacos.config.server.utils.LogUtil.defaultLog;
import org.apache.commons.lang.StringUtils; import static com.alibaba.nacos.config.server.utils.LogUtil.fatalLog;
import org.springframework.stereotype.Service;
import com.alibaba.nacos.config.server.utils.RegexParser;
/** /**

View File

@ -15,23 +15,9 @@
*/ */
package com.alibaba.nacos.config.server.service; package com.alibaba.nacos.config.server.service;
import static com.alibaba.nacos.config.server.service.PersistService.CONFIG_INFO4BETA_ROW_MAPPER;
import static com.alibaba.nacos.config.server.utils.LogUtil.defaultLog;
import static com.alibaba.nacos.config.server.utils.LogUtil.fatalLog;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSource; import org.apache.commons.dbcp.BasicDataSource;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang.math.NumberUtils; import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment; import org.springframework.core.env.Environment;
import org.springframework.dao.DataAccessException; import org.springframework.dao.DataAccessException;
@ -41,291 +27,302 @@ import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate; import org.springframework.transaction.support.TransactionTemplate;
import com.alibaba.nacos.config.server.utils.PropertyUtil; import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.alibaba.nacos.common.util.SystemUtils.STANDALONE_MODE;
import static com.alibaba.nacos.config.server.service.PersistService.CONFIG_INFO4BETA_ROW_MAPPER;
import static com.alibaba.nacos.config.server.utils.LogUtil.defaultLog;
import static com.alibaba.nacos.config.server.utils.LogUtil.fatalLog;
/** /**
* Base data source * Base data source
* @author Nacos
* *
* @author Nacos
*/ */
@Service("basicDataSourceService") @Service("basicDataSourceService")
public class BasicDataSourceServiceImpl implements DataSourceService { public class BasicDataSourceServiceImpl implements DataSourceService {
private static final String JDBC_DRIVER_NAME = "com.mysql.jdbc.Driver"; private static final String JDBC_DRIVER_NAME = "com.mysql.jdbc.Driver";
/** /**
* JDBC执行超时时间, 单位秒 * JDBC执行超时时间, 单位秒
*/ */
private int queryTimeout = 3; private int queryTimeout = 3;
private static final int TRANSACTION_QUERY_TIMEOUT = 5; private static final int TRANSACTION_QUERY_TIMEOUT = 5;
private static final String DB_LOAD_ERROR_MSG = "[db-load-error]load jdbc.properties error"; private static final String DB_LOAD_ERROR_MSG = "[db-load-error]load jdbc.properties error";
private List<BasicDataSource> dataSourceList = new ArrayList<BasicDataSource>(); private List<BasicDataSource> dataSourceList = new ArrayList<BasicDataSource>();
private JdbcTemplate jt; private JdbcTemplate jt;
private DataSourceTransactionManager tm; private DataSourceTransactionManager tm;
private TransactionTemplate tjt; private TransactionTemplate tjt;
private JdbcTemplate testMasterJT; private JdbcTemplate testMasterJT;
private JdbcTemplate testMasterWritableJT; private JdbcTemplate testMasterWritableJT;
volatile private List<JdbcTemplate> testJTList; volatile private List<JdbcTemplate> testJTList;
volatile private List<Boolean> isHealthList; volatile private List<Boolean> isHealthList;
private volatile int masterIndex; private volatile int masterIndex;
private static Pattern ipPattern = Pattern.compile("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}"); private static Pattern ipPattern = Pattern.compile("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}");
@Autowired @Autowired
private Environment env; private Environment env;
@PostConstruct @PostConstruct
public void init() { public void init() {
queryTimeout = NumberUtils queryTimeout = NumberUtils.toInt(System.getProperty("QUERYTIMEOUT"), 3);
.toInt(System.getProperty("QUERYTIMEOUT"), 3); jt = new JdbcTemplate();
jt = new JdbcTemplate(); /**
/** * 设置最大记录数防止内存膨胀
* 设置最大记录数防止内存膨胀 */
*/ jt.setMaxRows(50000);
jt.setMaxRows(50000); jt.setQueryTimeout(queryTimeout);
jt.setQueryTimeout(queryTimeout);
testMasterJT = new JdbcTemplate(); testMasterJT = new JdbcTemplate();
testMasterJT.setQueryTimeout(queryTimeout); testMasterJT.setQueryTimeout(queryTimeout);
testMasterWritableJT = new JdbcTemplate(); testMasterWritableJT = new JdbcTemplate();
/** /**
* 防止login接口因为主库不可用而rt太长 * 防止login接口因为主库不可用而rt太长
*/ */
testMasterWritableJT.setQueryTimeout(1); testMasterWritableJT.setQueryTimeout(1);
/** /**
* 数据库健康检测 * 数据库健康检测
*/ */
testJTList = new ArrayList<JdbcTemplate>(); testJTList = new ArrayList<JdbcTemplate>();
isHealthList = new ArrayList<Boolean>(); isHealthList = new ArrayList<Boolean>();
tm = new DataSourceTransactionManager(); tm = new DataSourceTransactionManager();
tjt = new TransactionTemplate(tm); tjt = new TransactionTemplate(tm);
/** /**
* 事务的超时时间需要与普通操作区分开 * 事务的超时时间需要与普通操作区分开
*/ */
tjt.setTimeout(TRANSACTION_QUERY_TIMEOUT); tjt.setTimeout(TRANSACTION_QUERY_TIMEOUT);
if (!PropertyUtil.isStandaloneMode()) { if (!STANDALONE_MODE) {
try { try {
reload(); reload();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
throw new RuntimeException(DB_LOAD_ERROR_MSG); throw new RuntimeException(DB_LOAD_ERROR_MSG);
} }
TimerTaskService.scheduleWithFixedDelay(new SelectMasterTask(), 10, 10, TimerTaskService.scheduleWithFixedDelay(new SelectMasterTask(), 10, 10,
TimeUnit.SECONDS); TimeUnit.SECONDS);
TimerTaskService.scheduleWithFixedDelay(new CheckDBHealthTask(), 10, 10, TimerTaskService.scheduleWithFixedDelay(new CheckDBHealthTask(), 10, 10,
TimeUnit.SECONDS); TimeUnit.SECONDS);
} }
} }
public synchronized void reload() throws IOException { public synchronized void reload() throws IOException {
List<BasicDataSource> dblist = new ArrayList<BasicDataSource>(); List<BasicDataSource> dblist = new ArrayList<BasicDataSource>();
try { try {
String val = null; String val = null;
val = env.getProperty("db.num"); val = env.getProperty("db.num");
if (null == val) { if (null == val) {
throw new IllegalArgumentException("db.num is null"); throw new IllegalArgumentException("db.num is null");
} }
int dbNum = Integer.parseInt(val.trim()); int dbNum = Integer.parseInt(val.trim());
for (int i = 0; i < dbNum; i++) { for (int i = 0; i < dbNum; i++) {
BasicDataSource ds = new BasicDataSource(); BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName(JDBC_DRIVER_NAME); ds.setDriverClassName(JDBC_DRIVER_NAME);
val = env.getProperty("db.url." + i); val = env.getProperty("db.url." + i);
if (null == val) { if (null == val) {
fatalLog.error("db.url." + i + " is null"); fatalLog.error("db.url." + i + " is null");
throw new IllegalArgumentException(); throw new IllegalArgumentException();
} }
ds.setUrl(val.trim()); ds.setUrl(val.trim());
val = env.getProperty("db.user"); val = env.getProperty("db.user");
if (null == val) { if (null == val) {
fatalLog.error("db.user is null"); fatalLog.error("db.user is null");
throw new IllegalArgumentException(); throw new IllegalArgumentException();
} }
ds.setUsername(val.trim()); ds.setUsername(val.trim());
val = env.getProperty("db.password"); val = env.getProperty("db.password");
if (null == val) { if (null == val) {
fatalLog.error("db.password is null"); fatalLog.error("db.password is null");
throw new IllegalArgumentException(); throw new IllegalArgumentException();
} }
ds.setPassword(val.trim()); ds.setPassword(val.trim());
val = env.getProperty("db.initialSize"); val = env.getProperty("db.initialSize");
ds.setInitialSize(Integer.parseInt(defaultIfNull(val, "10"))); ds.setInitialSize(Integer.parseInt(defaultIfNull(val, "10")));
val = env.getProperty("db.maxActive"); val = env.getProperty("db.maxActive");
ds.setMaxActive(Integer.parseInt(defaultIfNull(val, "20"))); ds.setMaxActive(Integer.parseInt(defaultIfNull(val, "20")));
val = env.getProperty("db.maxIdle"); val = env.getProperty("db.maxIdle");
ds.setMaxIdle(Integer.parseInt(defaultIfNull(val, "50"))); ds.setMaxIdle(Integer.parseInt(defaultIfNull(val, "50")));
ds.setMaxWait(3000L); ds.setMaxWait(3000L);
ds.setPoolPreparedStatements(true); ds.setPoolPreparedStatements(true);
// 每10分钟检查一遍连接池 // 每10分钟检查一遍连接池
ds.setTimeBetweenEvictionRunsMillis(TimeUnit.MINUTES ds.setTimeBetweenEvictionRunsMillis(TimeUnit.MINUTES
.toMillis(10L)); .toMillis(10L));
ds.setTestWhileIdle(true); ds.setTestWhileIdle(true);
ds.setValidationQuery("SELECT 1 FROM dual"); ds.setValidationQuery("SELECT 1 FROM dual");
dblist.add(ds); dblist.add(ds);
JdbcTemplate jdbcTemplate = new JdbcTemplate(); JdbcTemplate jdbcTemplate = new JdbcTemplate();
jdbcTemplate.setQueryTimeout(queryTimeout); jdbcTemplate.setQueryTimeout(queryTimeout);
jdbcTemplate.setDataSource(ds); jdbcTemplate.setDataSource(ds);
testJTList.add(jdbcTemplate); testJTList.add(jdbcTemplate);
isHealthList.add(Boolean.TRUE); isHealthList.add(Boolean.TRUE);
} }
if (dblist == null || dblist.size() == 0) { if (dblist == null || dblist.size() == 0) {
throw new RuntimeException("no datasource available"); throw new RuntimeException("no datasource available");
} }
dataSourceList = dblist; dataSourceList = dblist;
new SelectMasterTask().run(); new SelectMasterTask().run();
new CheckDBHealthTask().run(); new CheckDBHealthTask().run();
} catch (RuntimeException e) { } catch (RuntimeException e) {
fatalLog.error(DB_LOAD_ERROR_MSG, e); fatalLog.error(DB_LOAD_ERROR_MSG, e);
throw new IOException(e); throw new IOException(e);
} finally { } finally {
} }
} }
public boolean checkMasterWritable() { public boolean checkMasterWritable() {
testMasterWritableJT.setDataSource(jt.getDataSource()); testMasterWritableJT.setDataSource(jt.getDataSource());
/** /**
* 防止login接口因为主库不可用而rt太长 * 防止login接口因为主库不可用而rt太长
*/ */
testMasterWritableJT.setQueryTimeout(1); testMasterWritableJT.setQueryTimeout(1);
String sql = " select @@read_only "; String sql = " select @@read_only ";
try { try {
Integer result = testMasterWritableJT.queryForObject(sql, Integer.class); Integer result = testMasterWritableJT.queryForObject(sql, Integer.class);
if (result == null) { if (result == null) {
return false; return false;
} else { } else {
return result.intValue() == 0 ? true : false; return result.intValue() == 0 ? true : false;
} }
} catch (CannotGetJdbcConnectionException e) { } catch (CannotGetJdbcConnectionException e) {
fatalLog.error("[db-error] " + e.toString(), e); fatalLog.error("[db-error] " + e.toString(), e);
return false; return false;
} }
} }
public JdbcTemplate getJdbcTemplate() { public JdbcTemplate getJdbcTemplate() {
return this.jt; return this.jt;
} }
public TransactionTemplate getTransactionTemplate() { public TransactionTemplate getTransactionTemplate() {
return this.tjt; return this.tjt;
} }
public String getCurrentDBUrl() { public String getCurrentDBUrl() {
DataSource ds = this.jt.getDataSource(); DataSource ds = this.jt.getDataSource();
if (ds == null) { if (ds == null) {
return StringUtils.EMPTY; return StringUtils.EMPTY;
} }
BasicDataSource bds = (BasicDataSource) ds; BasicDataSource bds = (BasicDataSource) ds;
return bds.getUrl(); return bds.getUrl();
} }
public String getHealth() { public String getHealth() {
for (int i = 0 ; i < isHealthList.size(); i++) { for (int i = 0; i < isHealthList.size(); i++) {
if (!isHealthList.get(i)) { if (!isHealthList.get(i)) {
if (i == masterIndex) { if (i == masterIndex) {
/** /**
* 主库不健康 * 主库不健康
*/ */
return "DOWN:" + getIpFromUrl(dataSourceList.get(i).getUrl()); return "DOWN:" + getIpFromUrl(dataSourceList.get(i).getUrl());
} else { } else {
/** /**
* 从库不健康 * 从库不健康
*/ */
return "WARN:" + getIpFromUrl(dataSourceList.get(i).getUrl()); return "WARN:" + getIpFromUrl(dataSourceList.get(i).getUrl());
} }
} }
} }
return "UP"; return "UP";
} }
private String getIpFromUrl(String url) { private String getIpFromUrl(String url) {
Matcher m = ipPattern.matcher(url);
if (m.find()) {
return m.group();
}
return ""; Matcher m = ipPattern.matcher(url);
} if (m.find()) {
return m.group();
}
static String defaultIfNull(String value, String defaultValue) { return "";
return null == value ? defaultValue : value; }
}
class SelectMasterTask implements Runnable { static String defaultIfNull(String value, String defaultValue) {
public void run() { return null == value ? defaultValue : value;
defaultLog.info("check master db."); }
boolean isFound = false;
int index = -1; class SelectMasterTask implements Runnable {
for (BasicDataSource ds : dataSourceList) { public void run() {
index++; defaultLog.info("check master db.");
testMasterJT.setDataSource(ds); boolean isFound = false;
testMasterJT.setQueryTimeout(queryTimeout);
try {
testMasterJT
.update("delete from config_info where data_id='com.alibaba.nacos.testMasterDB'");
if (jt.getDataSource() != ds) {
fatalLog.warn("[master-db] {}", ds.getUrl());
}
jt.setDataSource(ds);
tm.setDataSource(ds);
isFound = true;
masterIndex = index;
break;
} catch (DataAccessException e) { // read only
e.printStackTrace(); // TODO remove
}
}
if (!isFound) { int index = -1;
fatalLog.error("[master-db] master db not found."); for (BasicDataSource ds : dataSourceList) {
} index++;
} testMasterJT.setDataSource(ds);
} testMasterJT.setQueryTimeout(queryTimeout);
try {
testMasterJT
.update("delete from config_info where data_id='com.alibaba.nacos.testMasterDB'");
if (jt.getDataSource() != ds) {
fatalLog.warn("[master-db] {}", ds.getUrl());
}
jt.setDataSource(ds);
tm.setDataSource(ds);
isFound = true;
masterIndex = index;
break;
} catch (DataAccessException e) { // read only
e.printStackTrace(); // TODO remove
}
}
@SuppressWarnings("PMD.ClassNamingShouldBeCamelRule") if (!isFound) {
class CheckDBHealthTask implements Runnable { fatalLog.error("[master-db] master db not found.");
public void run() { }
defaultLog.info("check db health."); }
String sql = "SELECT * FROM config_info_beta WHERE id = 1"; }
for (int i = 0; i < testJTList.size(); i++) { @SuppressWarnings("PMD.ClassNamingShouldBeCamelRule")
JdbcTemplate jdbcTemplate = testJTList.get(i); class CheckDBHealthTask implements Runnable {
try { public void run() {
jdbcTemplate.query(sql, CONFIG_INFO4BETA_ROW_MAPPER); defaultLog.info("check db health.");
isHealthList.set(i, Boolean.TRUE); String sql = "SELECT * FROM config_info_beta WHERE id = 1";
} catch (DataAccessException e) {
if (i == masterIndex) { for (int i = 0; i < testJTList.size(); i++) {
fatalLog.error("[db-error] master db {} down.", getIpFromUrl(dataSourceList.get(i).getUrl())); JdbcTemplate jdbcTemplate = testJTList.get(i);
} else { try {
fatalLog.error("[db-error] slave db {} down.", getIpFromUrl(dataSourceList.get(i).getUrl())); jdbcTemplate.query(sql, CONFIG_INFO4BETA_ROW_MAPPER);
} isHealthList.set(i, Boolean.TRUE);
isHealthList.set(i, Boolean.FALSE); } catch (DataAccessException e) {
} if (i == masterIndex) {
} fatalLog.error("[db-error] master db {} down.", getIpFromUrl(dataSourceList.get(i).getUrl()));
} } else {
} fatalLog.error("[db-error] slave db {} down.", getIpFromUrl(dataSourceList.get(i).getUrl()));
}
isHealthList.set(i, Boolean.FALSE);
}
}
}
}
} }

View File

@ -15,17 +15,16 @@
*/ */
package com.alibaba.nacos.config.server.service; package com.alibaba.nacos.config.server.service;
import static com.alibaba.nacos.config.server.utils.LogUtil.defaultLog; import com.alibaba.nacos.config.server.model.ACLInfo;
import com.alibaba.nacos.config.server.utils.JSONUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
import org.apache.commons.lang.StringUtils; import static com.alibaba.nacos.config.server.utils.LogUtil.defaultLog;
import org.springframework.stereotype.Service;
import com.alibaba.nacos.config.server.model.ACLInfo;
import com.alibaba.nacos.config.server.utils.JSONUtils;
/** /**
* Client ip whitelist * Client ip whitelist
* @author Nacos * @author Nacos

View File

@ -15,13 +15,13 @@
*/ */
package com.alibaba.nacos.config.server.service; package com.alibaba.nacos.config.server.service;
import com.alibaba.nacos.config.server.model.SubscriberStatus;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentMap;
import com.alibaba.nacos.config.server.model.SubscriberStatus;
/** /**
* 跟踪客户端md5的服务 一段时间没有比较md5后就删除IP对应的记录 * 跟踪客户端md5的服务 一段时间没有比较md5后就删除IP对应的记录

View File

@ -15,9 +15,8 @@
*/ */
package com.alibaba.nacos.config.server.service; package com.alibaba.nacos.config.server.service;
import org.apache.commons.lang.StringUtils;
import com.alibaba.nacos.config.server.utils.event.EventDispatcher.Event; import com.alibaba.nacos.config.server.utils.event.EventDispatcher.Event;
import org.apache.commons.lang3.StringUtils;
/** /**

View File

@ -15,34 +15,26 @@
*/ */
package com.alibaba.nacos.config.server.service; package com.alibaba.nacos.config.server.service;
import static com.alibaba.nacos.config.server.utils.LogUtil.defaultLog;
import static com.alibaba.nacos.config.server.utils.LogUtil.dumpLog;
import static com.alibaba.nacos.config.server.utils.LogUtil.fatalLog;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import com.alibaba.nacos.config.server.model.ConfigInfoBase;
import com.alibaba.nacos.config.server.utils.PropertyUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.nacos.config.server.constant.Constants; import com.alibaba.nacos.config.server.constant.Constants;
import com.alibaba.nacos.config.server.model.CacheItem; import com.alibaba.nacos.config.server.model.CacheItem;
import com.alibaba.nacos.config.server.model.ConfigInfoBase;
import com.alibaba.nacos.config.server.utils.GroupKey; import com.alibaba.nacos.config.server.utils.GroupKey;
import com.alibaba.nacos.config.server.utils.GroupKey2; import com.alibaba.nacos.config.server.utils.GroupKey2;
import com.alibaba.nacos.config.server.utils.MD5; import com.alibaba.nacos.config.server.utils.MD5;
import com.alibaba.nacos.config.server.utils.event.EventDispatcher; import com.alibaba.nacos.config.server.utils.event.EventDispatcher;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import java.io.IOException;
import java.util.*;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import static com.alibaba.nacos.common.util.SystemUtils.STANDALONE_MODE;
import static com.alibaba.nacos.config.server.utils.LogUtil.*;
/** /**
* config service * config service
* @author Nacos * @author Nacos
@ -82,7 +74,7 @@ public class ConfigService {
"[dump-ignore] ignore to save cache file. groupKey={}, md5={}, lastModifiedOld={}, " "[dump-ignore] ignore to save cache file. groupKey={}, md5={}, lastModifiedOld={}, "
+ "lastModifiedNew={}", + "lastModifiedNew={}",
groupKey, md5, ConfigService.getLastModifiedTs(groupKey), lastModifiedTs); groupKey, md5, ConfigService.getLastModifiedTs(groupKey), lastModifiedTs);
} else if (!PropertyUtil.isStandaloneMode()) { } else if (!STANDALONE_MODE) {
DiskUtil.saveToDisk(dataId, group, tenant, content); DiskUtil.saveToDisk(dataId, group, tenant, content);
} }
updateMd5(groupKey, md5, lastModifiedTs); updateMd5(groupKey, md5, lastModifiedTs);
@ -126,7 +118,7 @@ public class ConfigService {
"[dump-beta-ignore] ignore to save cache file. groupKey={}, md5={}, lastModifiedOld={}, " "[dump-beta-ignore] ignore to save cache file. groupKey={}, md5={}, lastModifiedOld={}, "
+ "lastModifiedNew={}", + "lastModifiedNew={}",
groupKey, md5, ConfigService.getLastModifiedTs(groupKey), lastModifiedTs); groupKey, md5, ConfigService.getLastModifiedTs(groupKey), lastModifiedTs);
} else if (!PropertyUtil.isStandaloneMode()) { } else if (!STANDALONE_MODE) {
DiskUtil.saveBetaToDisk(dataId, group, tenant, content); DiskUtil.saveBetaToDisk(dataId, group, tenant, content);
} }
String[] betaIpsArr = betaIps.split(","); String[] betaIpsArr = betaIps.split(",");
@ -164,7 +156,7 @@ public class ConfigService {
"[dump-tag-ignore] ignore to save cache file. groupKey={}, md5={}, lastModifiedOld={}, " "[dump-tag-ignore] ignore to save cache file. groupKey={}, md5={}, lastModifiedOld={}, "
+ "lastModifiedNew={}", + "lastModifiedNew={}",
groupKey, md5, ConfigService.getLastModifiedTs(groupKey), lastModifiedTs); groupKey, md5, ConfigService.getLastModifiedTs(groupKey), lastModifiedTs);
} else if (!PropertyUtil.isStandaloneMode()) { } else if (!STANDALONE_MODE) {
DiskUtil.saveTagToDisk(dataId, group, tenant, tag, content); DiskUtil.saveTagToDisk(dataId, group, tenant, tag, content);
} }
@ -196,7 +188,7 @@ public class ConfigService {
try { try {
final String md5 = MD5.getInstance().getMD5String(content); final String md5 = MD5.getInstance().getMD5String(content);
if (!PropertyUtil.isStandaloneMode()) { if (!STANDALONE_MODE) {
String loacalMd5 = DiskUtil.getLocalConfigMd5(dataId, group, tenant); String loacalMd5 = DiskUtil.getLocalConfigMd5(dataId, group, tenant);
if(md5.equals(loacalMd5)) { if(md5.equals(loacalMd5)) {
dumpLog.warn( dumpLog.warn(
@ -222,7 +214,7 @@ public class ConfigService {
{ {
String aggreds = null; String aggreds = null;
try { try {
if (PropertyUtil.isStandaloneMode()) { if (STANDALONE_MODE) {
ConfigInfoBase config = persistService.findConfigInfoBase(AggrWhitelist.AGGRIDS_METADATA, "DEFAULT_GROUP"); ConfigInfoBase config = persistService.findConfigInfoBase(AggrWhitelist.AGGRIDS_METADATA, "DEFAULT_GROUP");
if (config != null) { if (config != null) {
aggreds = config.getContent(); aggreds = config.getContent();
@ -240,7 +232,7 @@ public class ConfigService {
String clientIpWhitelist = null; String clientIpWhitelist = null;
try { try {
if (PropertyUtil.isStandaloneMode()) { if (STANDALONE_MODE) {
ConfigInfoBase config = persistService.findConfigInfoBase(ClientIpWhiteList.CLIENT_IP_WHITELIST_METADATA, "DEFAULT_GROUP"); ConfigInfoBase config = persistService.findConfigInfoBase(ClientIpWhiteList.CLIENT_IP_WHITELIST_METADATA, "DEFAULT_GROUP");
if (config != null) { if (config != null) {
clientIpWhitelist = config.getContent(); clientIpWhitelist = config.getContent();
@ -259,7 +251,7 @@ public class ConfigService {
String switchContent= null; String switchContent= null;
try { try {
if (PropertyUtil.isStandaloneMode()) { if (STANDALONE_MODE) {
ConfigInfoBase config = persistService.findConfigInfoBase(SwitchService.SWITCH_META_DATAID, "DEFAULT_GROUP"); ConfigInfoBase config = persistService.findConfigInfoBase(SwitchService.SWITCH_META_DATAID, "DEFAULT_GROUP");
if (config != null) { if (config != null) {
switchContent = config.getContent(); switchContent = config.getContent();
@ -326,7 +318,7 @@ public class ConfigService {
} }
try { try {
if (!PropertyUtil.isStandaloneMode()) { if (!STANDALONE_MODE) {
DiskUtil.removeConfigInfo(dataId, group, tenant); DiskUtil.removeConfigInfo(dataId, group, tenant);
} }
CACHE.remove(groupKey); CACHE.remove(groupKey);
@ -359,7 +351,7 @@ public class ConfigService {
} }
try { try {
if (!PropertyUtil.isStandaloneMode()) { if (!STANDALONE_MODE) {
DiskUtil.removeConfigInfo4Beta(dataId, group, tenant); DiskUtil.removeConfigInfo4Beta(dataId, group, tenant);
} }
EventDispatcher.fireEvent(new LocalDataChangeEvent(groupKey, true, CACHE.get(groupKey).getIps4Beta())); EventDispatcher.fireEvent(new LocalDataChangeEvent(groupKey, true, CACHE.get(groupKey).getIps4Beta()));
@ -394,7 +386,7 @@ public class ConfigService {
} }
try { try {
if (!PropertyUtil.isStandaloneMode()) { if (!STANDALONE_MODE) {
DiskUtil.removeConfigInfo4Tag(dataId, group, tenant, tag); DiskUtil.removeConfigInfo4Tag(dataId, group, tenant, tag);
} }

View File

@ -15,30 +15,6 @@
*/ */
package com.alibaba.nacos.config.server.service; package com.alibaba.nacos.config.server.service;
import java.net.HttpURLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.apache.commons.lang.StringUtils;
import org.codehaus.jackson.type.TypeReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.nacos.config.server.constant.Constants; import com.alibaba.nacos.config.server.constant.Constants;
import com.alibaba.nacos.config.server.model.SampleResult; import com.alibaba.nacos.config.server.model.SampleResult;
import com.alibaba.nacos.config.server.service.notify.NotifyService; import com.alibaba.nacos.config.server.service.notify.NotifyService;
@ -46,6 +22,18 @@ import com.alibaba.nacos.config.server.utils.JSONUtils;
import com.alibaba.nacos.config.server.utils.LogUtil; import com.alibaba.nacos.config.server.utils.LogUtil;
import com.alibaba.nacos.config.server.utils.RunningConfigUtils; import com.alibaba.nacos.config.server.utils.RunningConfigUtils;
import com.alibaba.nacos.config.server.utils.ThreadUtil; import com.alibaba.nacos.config.server.utils.ThreadUtil;
import org.apache.commons.lang3.StringUtils;
import org.codehaus.jackson.type.TypeReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.net.HttpURLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;
/** /**
* config sub service * config sub service
* @author Nacos * @author Nacos

View File

@ -15,21 +15,20 @@
*/ */
package com.alibaba.nacos.config.server.service; package com.alibaba.nacos.config.server.service;
import com.alibaba.nacos.config.server.constant.Constants;
import com.alibaba.nacos.config.server.utils.LogUtil;
import com.alibaba.nacos.config.server.utils.MD5;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.nacos.config.server.constant.Constants;
import com.alibaba.nacos.config.server.utils.LogUtil;
import com.alibaba.nacos.config.server.utils.MD5;
/** /**
* 磁盘操作工具类 * 磁盘操作工具类

View File

@ -15,11 +15,12 @@
*/ */
package com.alibaba.nacos.config.server.service; package com.alibaba.nacos.config.server.service;
import com.alibaba.nacos.config.server.utils.PropertyUtil;
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware; import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import static com.alibaba.nacos.common.util.SystemUtils.STANDALONE_MODE;
/** /**
* datasource adapter * datasource adapter
* @author Nacos * @author Nacos
@ -40,7 +41,7 @@ public class DynamicDataSource implements ApplicationContextAware {
public DataSourceService getDataSource() { public DataSourceService getDataSource() {
DataSourceService dataSourceService = null; DataSourceService dataSourceService = null;
if (PropertyUtil.isStandaloneMode()) { if (STANDALONE_MODE) {
dataSourceService = (DataSourceService)applicationContext.getBean("localDataSourceService"); dataSourceService = (DataSourceService)applicationContext.getBean("localDataSourceService");
} else { } else {
dataSourceService = (DataSourceService)applicationContext.getBean("basicDataSourceService"); dataSourceService = (DataSourceService)applicationContext.getBean("basicDataSourceService");

View File

@ -15,10 +15,10 @@
*/ */
package com.alibaba.nacos.config.server.service; package com.alibaba.nacos.config.server.service;
import java.util.List;
import com.alibaba.nacos.config.server.utils.event.EventDispatcher.Event; import com.alibaba.nacos.config.server.utils.event.EventDispatcher.Event;
import java.util.List;
/** /**
* 本地数据发生变更的事件 * 本地数据发生变更的事件
* @author Nacos * @author Nacos

View File

@ -15,6 +15,19 @@
*/ */
package com.alibaba.nacos.config.server.service; package com.alibaba.nacos.config.server.service;
import com.alibaba.nacos.config.server.constant.Constants;
import com.alibaba.nacos.config.server.utils.LogUtil;
import com.alibaba.nacos.config.server.utils.StringUtils;
import org.apache.commons.dbcp.BasicDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;
import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.InputStream; import java.io.InputStream;
@ -25,44 +38,34 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import javax.annotation.PostConstruct; import static com.alibaba.nacos.common.util.SystemUtils.STANDALONE_MODE;
import javax.sql.DataSource;
import com.alibaba.nacos.config.server.utils.PropertyUtil;
import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;
import com.alibaba.nacos.config.server.constant.Constants;
import com.alibaba.nacos.config.server.utils.LogUtil;
import com.alibaba.nacos.config.server.utils.StringUtils;
/** /**
* local data source * local data source
*
* @author Nacos
* *
* @author Nacos
*/ */
@Service("localDataSourceService") @Service("localDataSourceService")
public class LocalDataSourceServiceImpl implements DataSourceService { public class LocalDataSourceServiceImpl implements DataSourceService {
private static final String JDBC_DRIVER_NAME = "org.apache.derby.jdbc.EmbeddedDriver";
private static final String DERBY_BASE_DIR = "data" + File.separator + "derby-data"; private static final Logger logger = LoggerFactory.getLogger(LocalDataSourceServiceImpl.class);
private static String appHome = System.getProperty("user.home") + File.separator + "nacos";
private static final String NACOS_HOME_KEY = "nacos.home"; private static final String JDBC_DRIVER_NAME = "org.apache.derby.jdbc.EmbeddedDriver";
private static final String USER_NAME = "nacos"; private static final String DERBY_BASE_DIR = "data" + File.separator + "derby-data";
private static final String PASSWORD = "nacos"; private static String appHome = System.getProperty("user.home") + File.separator + "nacos";
private static final String NACOS_HOME_KEY = "nacos.home";
private static final String USER_NAME = "nacos";
private static final String PASSWORD = "nacos";
private JdbcTemplate jt; private JdbcTemplate jt;
private TransactionTemplate tjt; private TransactionTemplate tjt;
@PostConstruct @PostConstruct
public void init() { public void init() {
String nacosBaseDir = System.getProperty(NACOS_HOME_KEY); String nacosBaseDir = System.getProperty(NACOS_HOME_KEY);
if (!StringUtils.isBlank(nacosBaseDir)) { if (!StringUtils.isBlank(nacosBaseDir)) {
setAppHome(nacosBaseDir); setAppHome(nacosBaseDir);
} }
BasicDataSource ds = new BasicDataSource(); BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName(JDBC_DRIVER_NAME); ds.setDriverClassName(JDBC_DRIVER_NAME);
ds.setUrl("jdbc:derby:" + appHome + File.separator + DERBY_BASE_DIR + ";create=true"); ds.setUrl("jdbc:derby:" + appHome + File.separator + DERBY_BASE_DIR + ";create=true");
@ -86,23 +89,26 @@ public class LocalDataSourceServiceImpl implements DataSourceService {
tm.setDataSource(ds); tm.setDataSource(ds);
tjt.setTimeout(5000); tjt.setTimeout(5000);
if (PropertyUtil.isStandaloneMode()) { if (STANDALONE_MODE) {
reload(); reload();
} }
} }
@Override @Override
public void reload() { public void reload() {
DataSource ds = jt.getDataSource(); DataSource ds = jt.getDataSource();
if (ds == null) { if (ds == null) {
throw new RuntimeException("datasource is null"); throw new RuntimeException("datasource is null");
} }
try { try {
execute(ds.getConnection(), "schema.sql"); execute(ds.getConnection(), "META-INF/schema.sql");
} catch (Exception e) { } catch (Exception e) {
throw new RuntimeException("load schema.sql error." + e); if (logger.isErrorEnabled()) {
} logger.error(e.getMessage(), e);
} }
throw new RuntimeException("load schema.sql error." + e);
}
}
@Override @Override
public boolean checkMasterWritable() { public boolean checkMasterWritable() {
@ -131,6 +137,7 @@ public class LocalDataSourceServiceImpl implements DataSourceService {
/** /**
* 读取SQL文件 * 读取SQL文件
*
* @param sqlFile sql * @param sqlFile sql
* @return sqls * @return sqls
* @throws Exception Exception * @throws Exception Exception
@ -139,21 +146,21 @@ public class LocalDataSourceServiceImpl implements DataSourceService {
List<String> sqlList = new ArrayList<String>(); List<String> sqlList = new ArrayList<String>();
InputStream sqlFileIn = null; InputStream sqlFileIn = null;
try { try {
if (StringUtils.isBlank(System.getProperty(NACOS_HOME_KEY))) { if (StringUtils.isBlank(System.getProperty(NACOS_HOME_KEY))) {
ClassLoader classLoader = getClass().getClassLoader(); ClassLoader classLoader = getClass().getClassLoader();
URL url = classLoader.getResource(sqlFile); URL url = classLoader.getResource(sqlFile);
sqlFileIn = url.openStream(); sqlFileIn = url.openStream();
} else { } else {
File file = new File(System.getProperty(NACOS_HOME_KEY) + File.separator + "conf" + File.separator + sqlFile); File file = new File(System.getProperty(NACOS_HOME_KEY) + "/conf/schema.sql");
sqlFileIn = new FileInputStream(file); sqlFileIn = new FileInputStream(file);
} }
StringBuffer sqlSb = new StringBuffer(); StringBuffer sqlSb = new StringBuffer();
byte[] buff = new byte[1024]; byte[] buff = new byte[1024];
int byteRead = 0; int byteRead = 0;
while ((byteRead = sqlFileIn.read(buff)) != -1) { while ((byteRead = sqlFileIn.read(buff)) != -1) {
sqlSb.append(new String(buff, 0, byteRead, Constants.ENCODE)); sqlSb.append(new String(buff, 0, byteRead, Constants.ENCODE));
} }
String[] sqlArr = sqlSb.toString().split(";"); String[] sqlArr = sqlSb.toString().split(";");
for (int i = 0; i < sqlArr.length; i++) { for (int i = 0; i < sqlArr.length; i++) {
@ -163,18 +170,19 @@ public class LocalDataSourceServiceImpl implements DataSourceService {
} }
} }
return sqlList; return sqlList;
} catch (Exception ex) { } catch (Exception ex) {
throw new Exception(ex.getMessage()); throw new Exception(ex.getMessage());
} finally { } finally {
if (sqlFileIn != null) { if (sqlFileIn != null) {
sqlFileIn.close(); sqlFileIn.close();
} }
} }
} }
/** /**
* 执行SQL语句 * 执行SQL语句
* @param conn connect *
* @param conn connect
* @param sqlFile sql * @param sqlFile sql
* @throws Exception Exception * @throws Exception Exception
*/ */
@ -197,13 +205,13 @@ public class LocalDataSourceServiceImpl implements DataSourceService {
} }
} }
public static String getAppHome() { public static String getAppHome() {
return appHome; return appHome;
} }
public static void setAppHome(String appHome) {
LocalDataSourceServiceImpl.appHome = appHome;
}
public static void setAppHome(String appHome) {
LocalDataSourceServiceImpl.appHome = appHome;
}
} }

View File

@ -15,35 +15,6 @@
*/ */
package com.alibaba.nacos.config.server.service; package com.alibaba.nacos.config.server.service;
import static com.alibaba.nacos.config.server.utils.LogUtil.memoryLog;
import static com.alibaba.nacos.config.server.utils.LogUtil.pullLog;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import javax.servlet.AsyncContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import com.alibaba.nacos.config.server.model.SampleResult; import com.alibaba.nacos.config.server.model.SampleResult;
import com.alibaba.nacos.config.server.utils.GroupKey; import com.alibaba.nacos.config.server.utils.GroupKey;
import com.alibaba.nacos.config.server.utils.LogUtil; import com.alibaba.nacos.config.server.utils.LogUtil;
@ -51,13 +22,24 @@ import com.alibaba.nacos.config.server.utils.MD5Util;
import com.alibaba.nacos.config.server.utils.RequestUtil; import com.alibaba.nacos.config.server.utils.RequestUtil;
import com.alibaba.nacos.config.server.utils.event.EventDispatcher.AbstractEventListener; import com.alibaba.nacos.config.server.utils.event.EventDispatcher.AbstractEventListener;
import com.alibaba.nacos.config.server.utils.event.EventDispatcher.Event; import com.alibaba.nacos.config.server.utils.event.EventDispatcher.Event;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import javax.servlet.AsyncContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.concurrent.*;
import static com.alibaba.nacos.config.server.utils.LogUtil.memoryLog;
import static com.alibaba.nacos.config.server.utils.LogUtil.pullLog;
/** /**
* 长轮询服务负责处理 * 长轮询服务负责处理
* @author Nacos * @author Nacos
*/ */
@Service @Service
public class LongPullingService extends AbstractEventListener { public class LongPollingService extends AbstractEventListener {
private static final int FIXED_POLLING_INTERVAL_MS = 10000; private static final int FIXED_POLLING_INTERVAL_MS = 10000;
@ -222,8 +204,8 @@ public class LongPullingService extends AbstractEventListener {
public void addLongPullingClient(HttpServletRequest req, HttpServletResponse rsp, Map<String, String> clientMd5Map, int probeRequestSize) { public void addLongPullingClient(HttpServletRequest req, HttpServletResponse rsp, Map<String, String> clientMd5Map, int probeRequestSize) {
String str = req.getHeader(LongPullingService.LONG_PULLING_HEADER); String str = req.getHeader(LongPollingService.LONG_PULLING_HEADER);
String noHangUpFlag = req.getHeader(LongPullingService.LONG_PULLING_NO_HANG_UP_HEADER); String noHangUpFlag = req.getHeader(LongPollingService.LONG_PULLING_NO_HANG_UP_HEADER);
String appName = req.getHeader(RequestUtil.CLIENT_APPNAME_HEADER); String appName = req.getHeader(RequestUtil.CLIENT_APPNAME_HEADER);
String tag = req.getHeader("Vipserver-Tag"); String tag = req.getHeader("Vipserver-Tag");
int delayTime=SwitchService.getSwitchInteger(SwitchService.FIXED_DELAY_TIME, 500); int delayTime=SwitchService.getSwitchInteger(SwitchService.FIXED_DELAY_TIME, 500);
@ -285,7 +267,7 @@ public class LongPullingService extends AbstractEventListener {
} }
@SuppressWarnings("PMD.ThreadPoolCreationRule") @SuppressWarnings("PMD.ThreadPoolCreationRule")
public LongPullingService() { public LongPollingService() {
allSubs = new ConcurrentLinkedQueue<ClientLongPulling>(); allSubs = new ConcurrentLinkedQueue<ClientLongPulling>();
scheduler = Executors.newScheduledThreadPool(1, new ThreadFactory() { scheduler = Executors.newScheduledThreadPool(1, new ThreadFactory() {

View File

@ -15,25 +15,14 @@
*/ */
package com.alibaba.nacos.config.server.service; package com.alibaba.nacos.config.server.service;
import static com.alibaba.nacos.config.server.utils.LogUtil.defaultLog; import com.alibaba.nacos.config.server.model.*;
import static com.alibaba.nacos.config.server.utils.LogUtil.fatalLog; import com.alibaba.nacos.config.server.utils.LogUtil;
import com.alibaba.nacos.config.server.utils.MD5;
import java.io.IOException; import com.alibaba.nacos.config.server.utils.PaginationHelper;
import java.sql.Connection; import com.alibaba.nacos.config.server.utils.event.EventDispatcher;
import java.sql.PreparedStatement; import com.google.common.collect.Lists;
import java.sql.ResultSet; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.sql.SQLException; import org.apache.commons.lang3.StringUtils;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.annotation.PostConstruct;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException; import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataIntegrityViolationException; import org.springframework.dao.DataIntegrityViolationException;
@ -54,25 +43,17 @@ import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate; import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.CollectionUtils; import org.springframework.util.CollectionUtils;
import com.alibaba.nacos.config.server.model.ConfigAdvanceInfo; import javax.annotation.PostConstruct;
import com.alibaba.nacos.config.server.model.ConfigAllInfo; import java.io.IOException;
import com.alibaba.nacos.config.server.model.ConfigHistoryInfo; import java.sql.*;
import com.alibaba.nacos.config.server.model.ConfigInfo; import java.util.ArrayList;
import com.alibaba.nacos.config.server.model.ConfigInfo4Beta; import java.util.Collections;
import com.alibaba.nacos.config.server.model.ConfigInfo4Tag; import java.util.List;
import com.alibaba.nacos.config.server.model.ConfigInfoAggr; import java.util.Map;
import com.alibaba.nacos.config.server.model.ConfigInfoBase; import java.util.Map.Entry;
import com.alibaba.nacos.config.server.model.ConfigInfoChanged;
import com.alibaba.nacos.config.server.model.ConfigKey;
import com.alibaba.nacos.config.server.model.Page;
import com.alibaba.nacos.config.server.model.SubInfo;
import com.alibaba.nacos.config.server.utils.LogUtil;
import com.alibaba.nacos.config.server.utils.MD5;
import com.alibaba.nacos.config.server.utils.PaginationHelper;
import com.alibaba.nacos.config.server.utils.event.EventDispatcher;
import com.google.common.collect.Lists;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import static com.alibaba.nacos.config.server.utils.LogUtil.defaultLog;
import static com.alibaba.nacos.config.server.utils.LogUtil.fatalLog;
/** /**
* 数据库服务提供ConfigInfo在数据库的存取<br> * 数据库服务提供ConfigInfo在数据库的存取<br>

View File

@ -15,39 +15,6 @@
*/ */
package com.alibaba.nacos.config.server.service; package com.alibaba.nacos.config.server.service;
import static com.alibaba.nacos.config.server.utils.LogUtil.defaultLog;
import static com.alibaba.nacos.config.server.utils.LogUtil.fatalLog;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import javax.annotation.PostConstruct;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import com.alibaba.nacos.config.server.constant.Constants; import com.alibaba.nacos.config.server.constant.Constants;
import com.alibaba.nacos.config.server.service.notify.NotifyService; import com.alibaba.nacos.config.server.service.notify.NotifyService;
import com.alibaba.nacos.config.server.service.notify.NotifyService.HttpResult; import com.alibaba.nacos.config.server.service.notify.NotifyService.HttpResult;
@ -56,6 +23,33 @@ import com.alibaba.nacos.config.server.utils.PropertyUtil;
import com.alibaba.nacos.config.server.utils.RunningConfigUtils; import com.alibaba.nacos.config.server.utils.RunningConfigUtils;
import com.alibaba.nacos.config.server.utils.SystemConfig; import com.alibaba.nacos.config.server.utils.SystemConfig;
import com.alibaba.nacos.config.server.utils.event.EventDispatcher; import com.alibaba.nacos.config.server.utils.event.EventDispatcher;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.StringReader;
import java.util.*;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import static com.alibaba.nacos.common.util.SystemUtils.STANDALONE_MODE;
import static com.alibaba.nacos.config.server.utils.LogUtil.defaultLog;
import static com.alibaba.nacos.config.server.utils.LogUtil.fatalLog;
/** /**
* Serverlist service * Serverlist service
@ -71,10 +65,8 @@ public class ServerListService implements ApplicationListener<WebServerInitializ
@Autowired @Autowired
private ServletContext servletContext; private ServletContext servletContext;
@Value("${server.port}")
private int port; private int port;
@PostConstruct @PostConstruct
public void init() { public void init() {
serverPort = System.getProperty("nacos.server.port", "8848"); serverPort = System.getProperty("nacos.server.port", "8848");
@ -249,7 +241,7 @@ public class ServerListService implements ApplicationListener<WebServerInitializ
defaultLog.error("nacos-XXXX", "[serverlist] failed to get serverlist from disk!", e); defaultLog.error("nacos-XXXX", "[serverlist] failed to get serverlist from disk!", e);
} }
if (isUseAddressServer() && !PropertyUtil.isStandaloneMode()) { if (isUseAddressServer() && !STANDALONE_MODE) {
try { try {
HttpResult result = NotifyService.invokeURL(addressServerUrl, null, null); HttpResult result = NotifyService.invokeURL(addressServerUrl, null, null);

View File

@ -15,19 +15,18 @@
*/ */
package com.alibaba.nacos.config.server.service; package com.alibaba.nacos.config.server.service;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import com.alibaba.nacos.config.server.utils.LogUtil; import com.alibaba.nacos.config.server.utils.LogUtil;
import org.apache.commons.io.IOUtils;
import static com.alibaba.nacos.config.server.utils.LogUtil.fatalLog; import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import java.io.IOException; import java.io.IOException;
import java.io.StringReader; import java.io.StringReader;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import static com.alibaba.nacos.config.server.utils.LogUtil.fatalLog;
/** /**
* Switch * Switch
* @author Nacos * @author Nacos

View File

@ -20,13 +20,12 @@ import com.alibaba.nacos.config.server.model.capacity.Capacity;
import com.alibaba.nacos.config.server.model.capacity.GroupCapacity; import com.alibaba.nacos.config.server.model.capacity.GroupCapacity;
import com.alibaba.nacos.config.server.model.capacity.TenantCapacity; import com.alibaba.nacos.config.server.model.capacity.TenantCapacity;
import com.alibaba.nacos.config.server.service.PersistService; import com.alibaba.nacos.config.server.service.PersistService;
import com.alibaba.nacos.config.server.utils.PropertyUtil;
import com.alibaba.nacos.config.server.utils.LogUtil; import com.alibaba.nacos.config.server.utils.LogUtil;
import com.alibaba.nacos.config.server.utils.PropertyUtil;
import com.alibaba.nacos.config.server.utils.TimeUtils; import com.alibaba.nacos.config.server.utils.TimeUtils;
import com.google.common.base.Stopwatch; import com.google.common.base.Stopwatch;
import com.google.common.util.concurrent.ThreadFactoryBuilder; import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang.StringUtils;
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;

View File

@ -17,16 +17,11 @@ package com.alibaba.nacos.config.server.service.capacity;
import com.alibaba.nacos.config.server.model.capacity.Capacity; import com.alibaba.nacos.config.server.model.capacity.Capacity;
import com.alibaba.nacos.config.server.model.capacity.GroupCapacity; import com.alibaba.nacos.config.server.model.capacity.GroupCapacity;
import com.alibaba.nacos.config.server.service.BasicDataSourceServiceImpl;
import com.alibaba.nacos.config.server.service.DataSourceService; import com.alibaba.nacos.config.server.service.DataSourceService;
import com.alibaba.nacos.config.server.service.DynamicDataSource; import com.alibaba.nacos.config.server.service.DynamicDataSource;
import com.alibaba.nacos.config.server.service.LocalDataSourceServiceImpl;
import com.alibaba.nacos.config.server.utils.PropertyUtil;
import com.alibaba.nacos.config.server.utils.TimeUtils; import com.alibaba.nacos.config.server.utils.TimeUtils;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.CannotGetJdbcConnectionException; import org.springframework.jdbc.CannotGetJdbcConnectionException;
import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.JdbcTemplate;
@ -35,12 +30,12 @@ import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.GeneratedKeyHolder; import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import static com.alibaba.nacos.config.server.utils.LogUtil.fatalLog; import javax.annotation.PostConstruct;
import java.sql.*; import java.sql.*;
import java.util.List; import java.util.List;
import javax.annotation.PostConstruct; import static com.alibaba.nacos.common.util.SystemUtils.STANDALONE_MODE;
import static com.alibaba.nacos.config.server.utils.LogUtil.fatalLog;
/** /**
* Group Capacity Service * Group Capacity Service
@ -284,7 +279,7 @@ public class GroupCapacityPersistService {
public List<GroupCapacity> getCapacityList4CorrectUsage(long lastId, int pageSize) { public List<GroupCapacity> getCapacityList4CorrectUsage(long lastId, int pageSize) {
String sql = "select id, group_id from group_capacity where id>? limit ?"; String sql = "select id, group_id from group_capacity where id>? limit ?";
if (PropertyUtil.isStandaloneMode()) { if (STANDALONE_MODE) {
sql = "select id, group_id from group_capacity where id>? OFFSET 0 ROWS FETCH NEXT ? ROWS ONLY"; sql = "select id, group_id from group_capacity where id>? OFFSET 0 ROWS FETCH NEXT ? ROWS ONLY";
} }
try { try {

View File

@ -16,16 +16,11 @@
package com.alibaba.nacos.config.server.service.capacity; package com.alibaba.nacos.config.server.service.capacity;
import com.alibaba.nacos.config.server.model.capacity.TenantCapacity; import com.alibaba.nacos.config.server.model.capacity.TenantCapacity;
import com.alibaba.nacos.config.server.service.BasicDataSourceServiceImpl;
import com.alibaba.nacos.config.server.service.DataSourceService; import com.alibaba.nacos.config.server.service.DataSourceService;
import com.alibaba.nacos.config.server.service.DynamicDataSource; import com.alibaba.nacos.config.server.service.DynamicDataSource;
import com.alibaba.nacos.config.server.service.LocalDataSourceServiceImpl;
import com.alibaba.nacos.config.server.utils.PropertyUtil;
import com.alibaba.nacos.config.server.utils.TimeUtils; import com.alibaba.nacos.config.server.utils.TimeUtils;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.CannotGetJdbcConnectionException; import org.springframework.jdbc.CannotGetJdbcConnectionException;
import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.JdbcTemplate;
@ -34,12 +29,12 @@ import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.GeneratedKeyHolder; import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import static com.alibaba.nacos.config.server.utils.LogUtil.fatalLog; import javax.annotation.PostConstruct;
import java.sql.*; import java.sql.*;
import java.util.List; import java.util.List;
import javax.annotation.PostConstruct; import static com.alibaba.nacos.common.util.SystemUtils.STANDALONE_MODE;
import static com.alibaba.nacos.config.server.utils.LogUtil.fatalLog;
/** /**
* Tenant Capacity Service * Tenant Capacity Service
@ -234,7 +229,7 @@ public class TenantCapacityPersistService {
public List<TenantCapacity> getCapacityList4CorrectUsage(long lastId, int pageSize) { public List<TenantCapacity> getCapacityList4CorrectUsage(long lastId, int pageSize) {
String sql = "select id, tenant_id from tenant_capacity where id>? limit ?"; String sql = "select id, tenant_id from tenant_capacity where id>? limit ?";
if (PropertyUtil.isStandaloneMode()) { if (STANDALONE_MODE) {
sql = "select id, tenant_id from tenant_capacity where id>? OFFSET 0 ROWS FETCH NEXT ? ROWS ONLY"; sql = "select id, tenant_id from tenant_capacity where id>? OFFSET 0 ROWS FETCH NEXT ? ROWS ONLY";
} }

View File

@ -21,41 +21,33 @@ import com.alibaba.nacos.config.server.model.ConfigInfo;
import com.alibaba.nacos.config.server.model.ConfigInfoAggr; import com.alibaba.nacos.config.server.model.ConfigInfoAggr;
import com.alibaba.nacos.config.server.model.ConfigInfoChanged; import com.alibaba.nacos.config.server.model.ConfigInfoChanged;
import com.alibaba.nacos.config.server.model.Page; import com.alibaba.nacos.config.server.model.Page;
import com.alibaba.nacos.config.server.service.ConfigService; import com.alibaba.nacos.config.server.service.*;
import com.alibaba.nacos.config.server.service.DiskUtil;
import com.alibaba.nacos.config.server.service.PersistService;
import com.alibaba.nacos.config.server.service.ServerListService;
import com.alibaba.nacos.config.server.service.TimerTaskService;
import com.alibaba.nacos.config.server.service.PersistService.ConfigInfoWrapper; import com.alibaba.nacos.config.server.service.PersistService.ConfigInfoWrapper;
import com.alibaba.nacos.config.server.service.merge.MergeTaskProcessor; import com.alibaba.nacos.config.server.service.merge.MergeTaskProcessor;
import com.alibaba.nacos.config.server.utils.*; import com.alibaba.nacos.config.server.utils.*;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang3.StringUtils;
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;
import org.springframework.core.env.Environment; import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import static com.alibaba.nacos.config.server.utils.LogUtil.fatalLog; import javax.annotation.PostConstruct;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
import java.net.URI;
import java.net.URL;
import java.sql.Timestamp; import java.sql.Timestamp;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Calendar; import java.util.Calendar;
import java.util.List; import java.util.List;
import java.util.Properties;
import java.util.Random; import java.util.Random;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.PostConstruct; import static com.alibaba.nacos.common.util.SystemUtils.STANDALONE_MODE;
import static com.alibaba.nacos.config.server.utils.LogUtil.fatalLog;
/** /**
* Dump data service * Dump data service
@ -161,7 +153,7 @@ public class DumpService {
throw new RuntimeException( throw new RuntimeException(
"Nacos Server did not start because dumpservice bean construction failure :\n" + e.getMessage()); "Nacos Server did not start because dumpservice bean construction failure :\n" + e.getMessage());
} }
if (!PropertyUtil.isStandaloneMode()) { if (!STANDALONE_MODE) {
Runnable heartbeat = new Runnable() { Runnable heartbeat = new Runnable() {
@Override @Override
public void run() { public void run() {

View File

@ -15,22 +15,13 @@
*/ */
package com.alibaba.nacos.config.server.service.dump; package com.alibaba.nacos.config.server.service.dump;
import static com.alibaba.nacos.config.server.utils.LogUtil.defaultLog;
import java.sql.Timestamp;
import java.util.List;
import com.alibaba.nacos.config.server.manager.AbstractTask; import com.alibaba.nacos.config.server.manager.AbstractTask;
import com.alibaba.nacos.config.server.manager.TaskProcessor; import com.alibaba.nacos.config.server.manager.TaskProcessor;
import com.alibaba.nacos.config.server.model.ConfigInfo; import com.alibaba.nacos.config.server.model.ConfigInfo;
import com.alibaba.nacos.config.server.model.ConfigInfo4Beta; import com.alibaba.nacos.config.server.model.ConfigInfo4Beta;
import com.alibaba.nacos.config.server.model.ConfigInfo4Tag; import com.alibaba.nacos.config.server.model.ConfigInfo4Tag;
import com.alibaba.nacos.config.server.model.Page; import com.alibaba.nacos.config.server.model.Page;
import com.alibaba.nacos.config.server.service.AggrWhitelist; import com.alibaba.nacos.config.server.service.*;
import com.alibaba.nacos.config.server.service.ClientIpWhiteList;
import com.alibaba.nacos.config.server.service.ConfigService;
import com.alibaba.nacos.config.server.service.PersistService;
import com.alibaba.nacos.config.server.service.SwitchService;
import com.alibaba.nacos.config.server.service.PersistService.ConfigInfoBetaWrapper; import com.alibaba.nacos.config.server.service.PersistService.ConfigInfoBetaWrapper;
import com.alibaba.nacos.config.server.service.PersistService.ConfigInfoTagWrapper; import com.alibaba.nacos.config.server.service.PersistService.ConfigInfoTagWrapper;
import com.alibaba.nacos.config.server.service.PersistService.ConfigInfoWrapper; import com.alibaba.nacos.config.server.service.PersistService.ConfigInfoWrapper;
@ -40,6 +31,11 @@ import com.alibaba.nacos.config.server.utils.LogUtil;
import com.alibaba.nacos.config.server.utils.MD5; import com.alibaba.nacos.config.server.utils.MD5;
import com.alibaba.nacos.config.server.utils.StringUtils; import com.alibaba.nacos.config.server.utils.StringUtils;
import java.sql.Timestamp;
import java.util.List;
import static com.alibaba.nacos.config.server.utils.LogUtil.defaultLog;
/** /**
* Dump data task * Dump data task
* @author Nacos * @author Nacos

View File

@ -15,16 +15,6 @@
*/ */
package com.alibaba.nacos.config.server.service.merge; package com.alibaba.nacos.config.server.service.merge;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.nacos.config.server.manager.TaskManager; import com.alibaba.nacos.config.server.manager.TaskManager;
import com.alibaba.nacos.config.server.model.ConfigInfo; import com.alibaba.nacos.config.server.model.ConfigInfo;
import com.alibaba.nacos.config.server.model.ConfigInfoAggr; import com.alibaba.nacos.config.server.model.ConfigInfoAggr;
@ -34,6 +24,15 @@ import com.alibaba.nacos.config.server.service.PersistService;
import com.alibaba.nacos.config.server.utils.ContentUtils; import com.alibaba.nacos.config.server.utils.ContentUtils;
import com.alibaba.nacos.config.server.utils.SystemConfig; import com.alibaba.nacos.config.server.utils.SystemConfig;
import com.alibaba.nacos.config.server.utils.TimeUtils; import com.alibaba.nacos.config.server.utils.TimeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
/** /**

View File

@ -29,13 +29,12 @@ import com.alibaba.nacos.config.server.utils.StringUtils;
import com.alibaba.nacos.config.server.utils.SystemConfig; import com.alibaba.nacos.config.server.utils.SystemConfig;
import com.alibaba.nacos.config.server.utils.TimeUtils; import com.alibaba.nacos.config.server.utils.TimeUtils;
import com.alibaba.nacos.config.server.utils.event.EventDispatcher; import com.alibaba.nacos.config.server.utils.event.EventDispatcher;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.sql.Timestamp; import java.sql.Timestamp;
import java.util.List;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List;
/** /**

View File

@ -15,19 +15,13 @@
*/ */
package com.alibaba.nacos.config.server.service.notify; package com.alibaba.nacos.config.server.service.notify;
import java.io.UnsupportedEncodingException; import com.alibaba.nacos.config.server.constant.Constants;
import java.net.URLEncoder; import com.alibaba.nacos.config.server.service.ConfigDataChangeEvent;
import java.text.MessageFormat; import com.alibaba.nacos.config.server.service.ServerListService;
import java.util.ArrayList; import com.alibaba.nacos.config.server.service.trace.ConfigTraceService;
import java.util.LinkedList; import com.alibaba.nacos.config.server.utils.*;
import java.util.List; import com.alibaba.nacos.config.server.utils.event.EventDispatcher.AbstractEventListener;
import java.util.Queue; import com.alibaba.nacos.config.server.utils.event.EventDispatcher.Event;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import org.apache.http.HttpResponse; import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus; import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig; import org.apache.http.client.config.RequestConfig;
@ -41,17 +35,14 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import com.alibaba.nacos.config.server.constant.Constants; import java.io.UnsupportedEncodingException;
import com.alibaba.nacos.config.server.service.ConfigDataChangeEvent; import java.net.URLEncoder;
import com.alibaba.nacos.config.server.service.ServerListService; import java.text.MessageFormat;
import com.alibaba.nacos.config.server.service.trace.ConfigTraceService; import java.util.ArrayList;
import com.alibaba.nacos.config.server.utils.LogUtil; import java.util.LinkedList;
import com.alibaba.nacos.config.server.utils.PropertyUtil; import java.util.List;
import com.alibaba.nacos.config.server.utils.RunningConfigUtils; import java.util.Queue;
import com.alibaba.nacos.config.server.utils.StringUtils; import java.util.concurrent.*;
import com.alibaba.nacos.config.server.utils.SystemConfig;
import com.alibaba.nacos.config.server.utils.event.EventDispatcher.AbstractEventListener;
import com.alibaba.nacos.config.server.utils.event.EventDispatcher.Event;
/** /**
* Async notify service * Async notify service

View File

@ -15,21 +15,19 @@
*/ */
package com.alibaba.nacos.config.server.service.notify; package com.alibaba.nacos.config.server.service.notify;
import com.alibaba.nacos.config.server.manager.TaskManager;
import com.alibaba.nacos.config.server.service.ServerListService;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException; import java.io.IOException;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
import java.net.URL; import java.net.URL;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import com.alibaba.nacos.config.server.manager.TaskManager;
import com.alibaba.nacos.config.server.service.ServerListService;
/** /**
* 通知其他节点取最新数据的服务 监听数据变更事件通知所有的server * 通知其他节点取最新数据的服务 监听数据变更事件通知所有的server

View File

@ -15,23 +15,16 @@
*/ */
package com.alibaba.nacos.config.server.service.notify; package com.alibaba.nacos.config.server.service.notify;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import com.alibaba.nacos.config.server.manager.AbstractTask; import com.alibaba.nacos.config.server.manager.AbstractTask;
import com.alibaba.nacos.config.server.service.ServerListService; import com.alibaba.nacos.config.server.service.ServerListService;
import com.alibaba.nacos.config.server.utils.GroupKey2; import com.alibaba.nacos.config.server.utils.GroupKey2;
import com.alibaba.nacos.config.server.utils.LogUtil; import com.alibaba.nacos.config.server.utils.LogUtil;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;
/** /**
* Notify Single server * Notify Single server

View File

@ -15,14 +15,6 @@
*/ */
package com.alibaba.nacos.config.server.service.notify; package com.alibaba.nacos.config.server.service.notify;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.List;
import org.apache.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.nacos.config.server.constant.Constants; import com.alibaba.nacos.config.server.constant.Constants;
import com.alibaba.nacos.config.server.manager.AbstractTask; import com.alibaba.nacos.config.server.manager.AbstractTask;
import com.alibaba.nacos.config.server.manager.TaskProcessor; import com.alibaba.nacos.config.server.manager.TaskProcessor;
@ -31,6 +23,13 @@ import com.alibaba.nacos.config.server.service.notify.NotifyService.HttpResult;
import com.alibaba.nacos.config.server.service.trace.ConfigTraceService; import com.alibaba.nacos.config.server.service.trace.ConfigTraceService;
import com.alibaba.nacos.config.server.utils.RunningConfigUtils; import com.alibaba.nacos.config.server.utils.RunningConfigUtils;
import com.alibaba.nacos.config.server.utils.SystemConfig; import com.alibaba.nacos.config.server.utils.SystemConfig;
import org.apache.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.List;
/** /**

View File

@ -18,8 +18,7 @@ package com.alibaba.nacos.config.server.service.trace;
import com.alibaba.nacos.config.server.utils.LogUtil; import com.alibaba.nacos.config.server.utils.LogUtil;
import com.alibaba.nacos.config.server.utils.MD5; import com.alibaba.nacos.config.server.utils.MD5;
import com.alibaba.nacos.config.server.utils.SystemConfig; import com.alibaba.nacos.config.server.utils.SystemConfig;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
/** /**
* Config trace * Config trace

View File

@ -15,10 +15,10 @@
*/ */
package com.alibaba.nacos.config.server.utils; package com.alibaba.nacos.config.server.utils;
import static com.alibaba.nacos.config.server.constant.Constants.WORD_SEPARATOR;
import com.alibaba.nacos.config.server.constant.Constants; import com.alibaba.nacos.config.server.constant.Constants;
import static com.alibaba.nacos.config.server.constant.Constants.WORD_SEPARATOR;
/** /**
* Content utils * Content utils
* @author Nacos * @author Nacos

View File

@ -15,13 +15,13 @@
*/ */
package com.alibaba.nacos.config.server.utils; package com.alibaba.nacos.config.server.utils;
import java.io.IOException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.DeserializationConfig.Feature; import org.codehaus.jackson.map.DeserializationConfig.Feature;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.JavaType; import org.codehaus.jackson.type.JavaType;
import org.codehaus.jackson.type.TypeReference; import org.codehaus.jackson.type.TypeReference;
import java.io.IOException;
/** /**
* json util * json util
* @author Nacos * @author Nacos

View File

@ -17,9 +17,6 @@ package com.alibaba.nacos.config.server.utils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.joran.spi.JoranException;
/** /**
* log util * log util
@ -28,30 +25,6 @@ import ch.qos.logback.core.joran.spi.JoranException;
*/ */
public class LogUtil { public class LogUtil {
static {
LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
lc.reset();
JoranConfigurator configurator = new JoranConfigurator();
String nacosDir = System.getProperty("nacos.home");
if (StringUtils.isBlank(nacosDir)) {
configurator.setContext(lc);
try {
configurator.doConfigure(LogUtil.class.getResource("/nacos-config-logback.xml"));
} catch (JoranException e) {
System.err.println("init logger fail by nacos-config-logback.xml");
}
} else {
configurator.setContext(lc);
try {
configurator.doConfigure(nacosDir + "/conf/nacos-logback.xml");
} catch (JoranException e) {
System.err.println("init logger fail by " + nacosDir + "/conf/nacos-logback.xml");
}
}
}
/** /**
* 默认的日志 * 默认的日志
*/ */

View File

@ -15,14 +15,14 @@
*/ */
package com.alibaba.nacos.config.server.utils; package com.alibaba.nacos.config.server.utils;
import com.alibaba.nacos.config.server.constant.Constants;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.security.MessageDigest; import java.security.MessageDigest;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantLock;
import com.alibaba.nacos.config.server.constant.Constants;
/** /**
* md5 * md5
* @author Nacos * @author Nacos

View File

@ -15,28 +15,21 @@
*/ */
package com.alibaba.nacos.config.server.utils; package com.alibaba.nacos.config.server.utils;
import static com.alibaba.nacos.config.server.constant.Constants.LINE_SEPARATOR; import com.alibaba.nacos.config.server.constant.Constants;
import static com.alibaba.nacos.config.server.constant.Constants.WORD_SEPARATOR; import com.alibaba.nacos.config.server.service.ConfigService;
import org.apache.commons.lang3.StringUtils;
import java.io.CharArrayWriter; import javax.servlet.http.HttpServletRequest;
import java.io.IOException; import javax.servlet.http.HttpServletResponse;
import java.io.InputStream; import java.io.*;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.Writer;
import java.net.URLEncoder; import java.net.URLEncoder;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import javax.servlet.http.HttpServletRequest; import static com.alibaba.nacos.config.server.constant.Constants.LINE_SEPARATOR;
import javax.servlet.http.HttpServletResponse; import static com.alibaba.nacos.config.server.constant.Constants.WORD_SEPARATOR;
import org.apache.commons.lang.StringUtils;
import com.alibaba.nacos.config.server.constant.Constants;
import com.alibaba.nacos.config.server.service.ConfigService;
/** /**
* 轮询逻辑封装类 * 轮询逻辑封装类

View File

@ -15,12 +15,13 @@
*/ */
package com.alibaba.nacos.config.server.utils; package com.alibaba.nacos.config.server.utils;
import java.util.List; import com.alibaba.nacos.config.server.model.Page;
import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.RowMapper;
import com.alibaba.nacos.config.server.model.Page; import java.util.List;
import static com.alibaba.nacos.common.util.SystemUtils.STANDALONE_MODE;
/** /**
@ -88,7 +89,7 @@ public class PaginationHelper<E> {
final int startRow = (pageNo - 1) * pageSize; final int startRow = (pageNo - 1) * pageSize;
String selectSQL = ""; String selectSQL = "";
if (PropertyUtil.isStandaloneMode()) { if (STANDALONE_MODE) {
selectSQL = sqlFetchRows + " OFFSET "+startRow+" ROWS FETCH NEXT "+pageSize+" ROWS ONLY"; selectSQL = sqlFetchRows + " OFFSET "+startRow+" ROWS FETCH NEXT "+pageSize+" ROWS ONLY";
} else if (lastMaxId != null) { } else if (lastMaxId != null) {
selectSQL = sqlFetchRows + " and id > " + lastMaxId + " order by id asc" + " limit " + 0 + "," + pageSize; selectSQL = sqlFetchRows + " and id > " + lastMaxId + " order by id asc" + " limit " + 0 + "," + pageSize;
@ -132,7 +133,7 @@ public class PaginationHelper<E> {
} }
String selectSQL = sqlFetchRows; String selectSQL = sqlFetchRows;
if (PropertyUtil.isStandaloneMode()) { if (STANDALONE_MODE) {
selectSQL = selectSQL.replaceAll("(?i)LIMIT \\?,\\?", "OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"); selectSQL = selectSQL.replaceAll("(?i)LIMIT \\?,\\?", "OFFSET ? ROWS FETCH NEXT ? ROWS ONLY");
} }
@ -172,7 +173,7 @@ public class PaginationHelper<E> {
} }
String selectSQL = sqlFetchRows; String selectSQL = sqlFetchRows;
if (PropertyUtil.isStandaloneMode()) { if (STANDALONE_MODE) {
selectSQL = selectSQL.replaceAll("(?i)LIMIT \\?,\\?", "OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"); selectSQL = selectSQL.replaceAll("(?i)LIMIT \\?,\\?", "OFFSET ? ROWS FETCH NEXT ? ROWS ONLY");
} }
@ -192,7 +193,7 @@ public class PaginationHelper<E> {
final Page<E> page = new Page<E>(); final Page<E> page = new Page<E>();
String selectSQL = sqlFetchRows; String selectSQL = sqlFetchRows;
if (PropertyUtil.isStandaloneMode()) { if (STANDALONE_MODE) {
selectSQL = selectSQL.replaceAll("(?i)LIMIT \\?,\\?", "OFFSET ? ROWS FETCH NEXT ? ROWS ONLY"); selectSQL = selectSQL.replaceAll("(?i)LIMIT \\?,\\?", "OFFSET ? ROWS FETCH NEXT ? ROWS ONLY");
} }
@ -206,7 +207,7 @@ public class PaginationHelper<E> {
public void updateLimit(final JdbcTemplate jt, final String sql, final Object args[]) { public void updateLimit(final JdbcTemplate jt, final String sql, final Object args[]) {
String sqlUpdate = sql; String sqlUpdate = sql;
if (PropertyUtil.isStandaloneMode()) { if (STANDALONE_MODE) {
sqlUpdate = sqlUpdate.replaceAll("limit \\?", "OFFSET 0 ROWS FETCH NEXT ? ROWS ONLY"); sqlUpdate = sqlUpdate.replaceAll("limit \\?", "OFFSET 0 ROWS FETCH NEXT ? ROWS ONLY");
} }

View File

@ -15,11 +15,10 @@
*/ */
package com.alibaba.nacos.config.server.utils; package com.alibaba.nacos.config.server.utils;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import com.alibaba.nacos.config.server.exception.NacosException; import com.alibaba.nacos.config.server.exception.NacosException;
import org.apache.commons.lang3.StringUtils;
import java.util.Map;
/** /**
* 参数合法性检查工具类 * 参数合法性检查工具类

View File

@ -15,262 +15,253 @@
*/ */
package com.alibaba.nacos.config.server.utils; package com.alibaba.nacos.config.server.utils;
import javax.annotation.PostConstruct;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment; import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import static com.alibaba.nacos.common.util.SystemUtils.STANDALONE_MODE;
/** /**
* properties utils * properties utils
*
* @author Nacos
* *
* @author Nacos
*/ */
@Component @Component
public class PropertyUtil { public class PropertyUtil {
private final static Logger logger = LogUtil.defaultLog; private final static Logger logger = LogUtil.defaultLog;
private static int notifyConnectTimeout = 100;
private static int notifySocketTimeout = 200;
private static int maxHealthCheckFailCount = 12;
private static boolean isHealthCheck = true;
private static int maxContent = 10 * 1024 * 1024;
/** private static int notifyConnectTimeout = 100;
* 是否开启容量管理 private static int notifySocketTimeout = 200;
*/ private static int maxHealthCheckFailCount = 12;
private static boolean isManageCapacity = true; private static boolean isHealthCheck = true;
/** private static int maxContent = 10 * 1024 * 1024;
* 是否开启容量管理的限制检验功能包括配置个数上限配置内容大小限制等
*/
private static boolean isCapacityLimitCheck = false;
/**
* 集群默认容量上限
*/
private static int defaultClusterQuota = 100000;
/**
* 每个Group默认容量上限
*/
private static int defaultGroupQuota = 200;
/**
* 每个Tenant默认容量上限
*/
private static int defaultTenantQuota = 200;
/**
* 单个配置中content的最大大小单位为字节
*/
private static int defaultMaxSize = 100 * 1024;
/**
* 聚合数据子配置最大个数
*/
private static int defaultMaxAggrCount = 10000;
/**
* 聚合数据单个子配置中content的最大大小单位为字节
*/
private static int defaultMaxAggrSize = 1024;
/**
* 初始化容量信息记录时发现已经到达限额时的扩容百分比
*/
private static int initialExpansionPercent = 100;
/**
* 修正容量信息表使用量usage的时间间隔单位为秒
*/
private static int correctUsageDelay = 10 * 60;
private static boolean standaloneMode = false; /**
* 是否开启容量管理
*/
private static boolean isManageCapacity = true;
/**
* 是否开启容量管理的限制检验功能包括配置个数上限配置内容大小限制等
*/
private static boolean isCapacityLimitCheck = false;
/**
* 集群默认容量上限
*/
private static int defaultClusterQuota = 100000;
/**
* 每个Group默认容量上限
*/
private static int defaultGroupQuota = 200;
/**
* 每个Tenant默认容量上限
*/
private static int defaultTenantQuota = 200;
/**
* 单个配置中content的最大大小单位为字节
*/
private static int defaultMaxSize = 100 * 1024;
/**
* 聚合数据子配置最大个数
*/
private static int defaultMaxAggrCount = 10000;
/**
* 聚合数据单个子配置中content的最大大小单位为字节
*/
private static int defaultMaxAggrSize = 1024;
/**
* 初始化容量信息记录时发现已经到达限额时的扩容百分比
*/
private static int initialExpansionPercent = 100;
/**
* 修正容量信息表使用量usage的时间间隔单位为秒
*/
private static int correctUsageDelay = 10 * 60;
@Autowired @Autowired
private Environment env; private Environment env;
static { @PostConstruct
setStandaloneMode(Boolean.parseBoolean(System.getProperty("nacos.standalone", "false"))); public void init() {
} try {
@PostConstruct setNotifyConnectTimeout(Integer.parseInt(env.getProperty("notifyConnectTimeout", "100")));
public void init() { logger.info("notifyConnectTimeout:{}", notifyConnectTimeout);
try { setNotifySocketTimeout(Integer.parseInt(env.getProperty("notifySocketTimeout", "200")));
logger.info("notifySocketTimeout:{}", notifySocketTimeout);
setHealthCheck(Boolean.valueOf(env.getProperty("isHealthCheck", "true")));
logger.info("isHealthCheck:{}", isHealthCheck);
setMaxHealthCheckFailCount(Integer.parseInt(env.getProperty("maxHealthCheckFailCount", "12")));
logger.info("maxHealthCheckFailCount:{}", maxHealthCheckFailCount);
setMaxContent(Integer.parseInt(env.getProperty("maxContent", String.valueOf(maxContent))));
logger.info("maxContent:{}", maxContent);
// 容量管理
setManageCapacity(getBoolean("isManageCapacity", isManageCapacity));
setCapacityLimitCheck(getBoolean("isCapacityLimitCheck", isCapacityLimitCheck));
setDefaultClusterQuota(getInt("defaultClusterQuota", defaultClusterQuota));
setDefaultGroupQuota(getInt("defaultGroupQuota", defaultGroupQuota));
setDefaultTenantQuota(getInt("defaultTenantQuota", defaultTenantQuota));
setDefaultMaxSize(getInt("defaultMaxSize", defaultMaxSize));
setDefaultMaxAggrCount(getInt("defaultMaxAggrCount", defaultMaxAggrCount));
setDefaultMaxAggrSize(getInt("defaultMaxAggrSize", defaultMaxAggrSize));
setCorrectUsageDelay(getInt("correctUsageDelay", correctUsageDelay));
setInitialExpansionPercent(getInt("initialExpansionPercent", initialExpansionPercent));
setNotifyConnectTimeout(Integer.parseInt(env.getProperty("notifyConnectTimeout", "100"))); } catch (Exception e) {
logger.info("notifyConnectTimeout:{}", notifyConnectTimeout); logger.error("read application.properties failed", e);
setNotifySocketTimeout(Integer.parseInt(env.getProperty("notifySocketTimeout", "200"))); }
logger.info("notifySocketTimeout:{}", notifySocketTimeout); }
setHealthCheck(Boolean.valueOf(env.getProperty("isHealthCheck", "true")));
logger.info("isHealthCheck:{}", isHealthCheck);
setMaxHealthCheckFailCount(Integer.parseInt(env.getProperty("maxHealthCheckFailCount", "12")));
logger.info("maxHealthCheckFailCount:{}", maxHealthCheckFailCount);
setMaxContent(Integer.parseInt(env.getProperty("maxContent", String.valueOf(maxContent))));
logger.info("maxContent:{}", maxContent);
// 容量管理
setManageCapacity(getBoolean("isManageCapacity", isManageCapacity));
setCapacityLimitCheck(getBoolean("isCapacityLimitCheck", isCapacityLimitCheck));
setDefaultClusterQuota(getInt("defaultClusterQuota", defaultClusterQuota));
setDefaultGroupQuota(getInt("defaultGroupQuota", defaultGroupQuota));
setDefaultTenantQuota(getInt("defaultTenantQuota", defaultTenantQuota));
setDefaultMaxSize(getInt("defaultMaxSize", defaultMaxSize));
setDefaultMaxAggrCount(getInt("defaultMaxAggrCount", defaultMaxAggrCount));
setDefaultMaxAggrSize(getInt("defaultMaxAggrSize", defaultMaxAggrSize));
setCorrectUsageDelay(getInt("correctUsageDelay", correctUsageDelay));
setInitialExpansionPercent(getInt("initialExpansionPercent", initialExpansionPercent));
} catch (Exception e) {
logger.error("read application.properties failed", e);
}
}
public static int getNotifyConnectTimeout() { public static int getNotifyConnectTimeout() {
return notifyConnectTimeout; return notifyConnectTimeout;
} }
public static int getNotifySocketTimeout() { public static int getNotifySocketTimeout() {
return notifySocketTimeout; return notifySocketTimeout;
} }
public static int getMaxHealthCheckFailCount() { public static int getMaxHealthCheckFailCount() {
return maxHealthCheckFailCount; return maxHealthCheckFailCount;
} }
public static boolean isHealthCheck() { public static boolean isHealthCheck() {
return isHealthCheck; return isHealthCheck;
} }
private boolean getBoolean(String key, boolean defaultValue) { private boolean getBoolean(String key, boolean defaultValue) {
return Boolean.valueOf(getString(key, String.valueOf(defaultValue))); return Boolean.valueOf(getString(key, String.valueOf(defaultValue)));
} }
private int getInt(String key, int defaultValue) { private int getInt(String key, int defaultValue) {
return Integer.parseInt(getString(key, String.valueOf(defaultValue))); return Integer.parseInt(getString(key, String.valueOf(defaultValue)));
} }
private String getString(String key, String defaultValue) { private String getString(String key, String defaultValue) {
String value = env.getProperty(key); String value = env.getProperty(key);
if (value == null) { if (value == null) {
return defaultValue; return defaultValue;
} }
logger.info("{}:{}", key, value); logger.info("{}:{}", key, value);
return value; return value;
} }
public String getProperty(String key) { public String getProperty(String key) {
return env.getProperty(key); return env.getProperty(key);
} }
public String getProperty(String key, String defaultValue) { public String getProperty(String key, String defaultValue) {
return env.getProperty(key, defaultValue); return env.getProperty(key, defaultValue);
} }
public static int getMaxContent() { public static int getMaxContent() {
return maxContent; return maxContent;
} }
public static boolean isManageCapacity() { public static boolean isManageCapacity() {
return isManageCapacity; return isManageCapacity;
} }
public static int getDefaultClusterQuota() { public static int getDefaultClusterQuota() {
return defaultClusterQuota; return defaultClusterQuota;
} }
public static boolean isCapacityLimitCheck() { public static boolean isCapacityLimitCheck() {
return isCapacityLimitCheck; return isCapacityLimitCheck;
} }
public static int getDefaultGroupQuota() { public static int getDefaultGroupQuota() {
return defaultGroupQuota; return defaultGroupQuota;
} }
public static int getDefaultTenantQuota() { public static int getDefaultTenantQuota() {
return defaultTenantQuota; return defaultTenantQuota;
} }
public static int getInitialExpansionPercent() { public static int getInitialExpansionPercent() {
return initialExpansionPercent; return initialExpansionPercent;
} }
public static int getDefaultMaxSize() { public static int getDefaultMaxSize() {
return defaultMaxSize; return defaultMaxSize;
} }
public static int getDefaultMaxAggrCount() { public static int getDefaultMaxAggrCount() {
return defaultMaxAggrCount; return defaultMaxAggrCount;
} }
public static int getDefaultMaxAggrSize() { public static int getDefaultMaxAggrSize() {
return defaultMaxAggrSize; return defaultMaxAggrSize;
} }
public static int getCorrectUsageDelay() { public static int getCorrectUsageDelay() {
return correctUsageDelay; return correctUsageDelay;
} }
public static boolean isStandaloneMode() { public static boolean isStandaloneMode() {
return standaloneMode; return STANDALONE_MODE;
} }
public static void setStandaloneMode(boolean standaloneMode) { public static void setNotifyConnectTimeout(int notifyConnectTimeout) {
PropertyUtil.standaloneMode = standaloneMode; PropertyUtil.notifyConnectTimeout = notifyConnectTimeout;
} }
public static void setNotifyConnectTimeout(int notifyConnectTimeout) { public static void setNotifySocketTimeout(int notifySocketTimeout) {
PropertyUtil.notifyConnectTimeout = notifyConnectTimeout; PropertyUtil.notifySocketTimeout = notifySocketTimeout;
} }
public static void setNotifySocketTimeout(int notifySocketTimeout) { public static void setMaxHealthCheckFailCount(int maxHealthCheckFailCount) {
PropertyUtil.notifySocketTimeout = notifySocketTimeout; PropertyUtil.maxHealthCheckFailCount = maxHealthCheckFailCount;
} }
public static void setMaxHealthCheckFailCount(int maxHealthCheckFailCount) { public static void setHealthCheck(boolean isHealthCheck) {
PropertyUtil.maxHealthCheckFailCount = maxHealthCheckFailCount; PropertyUtil.isHealthCheck = isHealthCheck;
} }
public static void setHealthCheck(boolean isHealthCheck) { public static void setMaxContent(int maxContent) {
PropertyUtil.isHealthCheck = isHealthCheck; PropertyUtil.maxContent = maxContent;
} }
public static void setMaxContent(int maxContent) { public static void setManageCapacity(boolean isManageCapacity) {
PropertyUtil.maxContent = maxContent; PropertyUtil.isManageCapacity = isManageCapacity;
} }
public static void setManageCapacity(boolean isManageCapacity) { public static void setCapacityLimitCheck(boolean isCapacityLimitCheck) {
PropertyUtil.isManageCapacity = isManageCapacity; PropertyUtil.isCapacityLimitCheck = isCapacityLimitCheck;
} }
public static void setCapacityLimitCheck(boolean isCapacityLimitCheck) { public static void setDefaultClusterQuota(int defaultClusterQuota) {
PropertyUtil.isCapacityLimitCheck = isCapacityLimitCheck; PropertyUtil.defaultClusterQuota = defaultClusterQuota;
} }
public static void setDefaultClusterQuota(int defaultClusterQuota) { public static void setDefaultGroupQuota(int defaultGroupQuota) {
PropertyUtil.defaultClusterQuota = defaultClusterQuota; PropertyUtil.defaultGroupQuota = defaultGroupQuota;
} }
public static void setDefaultGroupQuota(int defaultGroupQuota) { public static void setDefaultTenantQuota(int defaultTenantQuota) {
PropertyUtil.defaultGroupQuota = defaultGroupQuota; PropertyUtil.defaultTenantQuota = defaultTenantQuota;
} }
public static void setDefaultTenantQuota(int defaultTenantQuota) { public static void setDefaultMaxSize(int defaultMaxSize) {
PropertyUtil.defaultTenantQuota = defaultTenantQuota; PropertyUtil.defaultMaxSize = defaultMaxSize;
} }
public static void setDefaultMaxSize(int defaultMaxSize) { public static void setDefaultMaxAggrCount(int defaultMaxAggrCount) {
PropertyUtil.defaultMaxSize = defaultMaxSize; PropertyUtil.defaultMaxAggrCount = defaultMaxAggrCount;
} }
public static void setDefaultMaxAggrCount(int defaultMaxAggrCount) { public static void setDefaultMaxAggrSize(int defaultMaxAggrSize) {
PropertyUtil.defaultMaxAggrCount = defaultMaxAggrCount; PropertyUtil.defaultMaxAggrSize = defaultMaxAggrSize;
} }
public static void setDefaultMaxAggrSize(int defaultMaxAggrSize) { public static void setInitialExpansionPercent(int initialExpansionPercent) {
PropertyUtil.defaultMaxAggrSize = defaultMaxAggrSize; PropertyUtil.initialExpansionPercent = initialExpansionPercent;
} }
public static void setInitialExpansionPercent(int initialExpansionPercent) { public static void setCorrectUsageDelay(int correctUsageDelay) {
PropertyUtil.initialExpansionPercent = initialExpansionPercent; PropertyUtil.correctUsageDelay = correctUsageDelay;
} }
public static void setCorrectUsageDelay(int correctUsageDelay) {
PropertyUtil.correctUsageDelay = correctUsageDelay;
}
} }

View File

@ -15,9 +15,7 @@
*/ */
package com.alibaba.nacos.config.server.utils; package com.alibaba.nacos.config.server.utils;
import org.apache.commons.lang.CharUtils; import org.apache.commons.lang3.CharUtils;
import org.apache.commons.lang.NullArgumentException;
/** /**
@ -28,7 +26,7 @@ import org.apache.commons.lang.NullArgumentException;
*/ */
public class RegexParser { public class RegexParser {
private final static char QUESTION_MARK = '?'; private final static char QUESTION_MARK = '?';
/** /**
* 替换输入字符串中非正则特殊字符为标准正则表达式字符串; <br> * 替换输入字符串中非正则特殊字符为标准正则表达式字符串; <br>
@ -40,7 +38,7 @@ public class RegexParser {
*/ */
static public String regexFormat(String regex) { static public String regexFormat(String regex) {
if (regex == null) { if (regex == null) {
throw new NullArgumentException("regex string can't be null"); throw new NullPointerException("regex string can't be null");
} }
StringBuffer result = new StringBuffer(); StringBuffer result = new StringBuffer();
result.append("^"); result.append("^");
@ -75,8 +73,4 @@ public class RegexParser {
return (regex.contains("?") || regex.contains("*")); return (regex.contains("?") || regex.contains("*"));
} }
public static void main(String[] args) {
String str = "com.taobao.uic.*";
System.out.println(str + " -> " + regexFormat(str));
}
} }

View File

@ -15,16 +15,12 @@
*/ */
package com.alibaba.nacos.config.server.utils; package com.alibaba.nacos.config.server.utils;
import java.io.File; import com.alibaba.nacos.config.server.constant.Constants;
import java.io.IOException;
import java.io.InputStream; import java.io.*;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL; import java.net.URL;
import java.util.Properties; import java.util.Properties;
import com.alibaba.nacos.config.server.constant.Constants;
/** /**
* resource util * resource util

View File

@ -15,10 +15,10 @@
*/ */
package com.alibaba.nacos.config.server.utils; package com.alibaba.nacos.config.server.utils;
import static com.alibaba.nacos.config.server.utils.LogUtil.defaultLog;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import static com.alibaba.nacos.config.server.utils.LogUtil.defaultLog;
/** /**
* write response * write response

View File

@ -15,13 +15,13 @@
*/ */
package com.alibaba.nacos.config.server.utils; package com.alibaba.nacos.config.server.utils;
import javax.servlet.ServletContext;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.context.WebServerInitializedEvent; import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener; import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import javax.servlet.ServletContext;
/** /**
* Running config * Running config
* @author dungu.zpf * @author dungu.zpf

View File

@ -15,14 +15,14 @@
*/ */
package com.alibaba.nacos.config.server.utils; package com.alibaba.nacos.config.server.utils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.InetAddress; import java.net.InetAddress;
import java.net.NetworkInterface; import java.net.NetworkInterface;
import java.util.Enumeration; import java.util.Enumeration;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** /**
* System config * System config
* @author Nacos * @author Nacos

View File

@ -15,27 +15,26 @@
*/ */
package com.alibaba.nacos.config.server.utils; package com.alibaba.nacos.config.server.utils;
import org.apache.commons.lang3.time.FastDateFormat;
import java.sql.Timestamp; import java.sql.Timestamp;
import java.util.Calendar; import java.util.Calendar;
import java.util.Date; import java.util.Date;
import org.apache.commons.lang.time.FastDateFormat;
/** /**
* Time util * Time util
* @author Nacos
* *
* @author Nacos
*/ */
public class TimeUtils { public class TimeUtils {
public static Timestamp getCurrentTime() { public static Timestamp getCurrentTime() {
Date date = new Date(); Date date = new Date();
return new Timestamp(date.getTime()); return new Timestamp(date.getTime());
} }
public static void main(String[] args) {
System.out.println(getCurrentTime().toString()); static public String getCurrentTimeStr() {
}
static public String getCurrentTimeStr() {
Calendar c = Calendar.getInstance(); Calendar c = Calendar.getInstance();
c.setTime(new Date()); c.setTime(new Date());
FastDateFormat format = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss"); FastDateFormat format = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss");

View File

@ -15,11 +15,11 @@
*/ */
package com.alibaba.nacos.config.server.utils; package com.alibaba.nacos.config.server.utils;
import com.alibaba.nacos.config.server.constant.Constants;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import com.alibaba.nacos.config.server.constant.Constants;
/** /**
* 分析url的工具类 * 分析url的工具类

View File

@ -15,12 +15,12 @@
*/ */
package com.alibaba.nacos.config.server.utils.event; package com.alibaba.nacos.config.server.utils.event;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
/** /**
* Event dispatcher * Event dispatcher

View File

@ -1,283 +1,282 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xml> <included>
<configuration scan="true" scanPeriod="10 seconds"> <appender name="dumpFile"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<appender name="dumpFile" <file>${user.home}/nacos/logs/config-dump.log</file>
class="ch.qos.logback.core.rolling.RollingFileAppender"> <append>true</append>
<file>${user.home}/nacos/logs/config-dump.log</file> <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<append>true</append> <fileNamePattern>${user.home}/nacos/logs/config-dump.log.%d{yyyy-MM-dd}.%i</fileNamePattern>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy"> <maxFileSize>2GB</maxFileSize>
<fileNamePattern>${user.home}/nacos/logs/config-dump.log.%d{yyyy-MM-dd}.%i</fileNamePattern> <MaxHistory>15</MaxHistory>
<maxFileSize>2GB</maxFileSize> <totalSizeCap>7GB</totalSizeCap>
<MaxHistory>15</MaxHistory> <cleanHistoryOnStart>true</cleanHistoryOnStart>
<totalSizeCap>7GB</totalSizeCap> </rollingPolicy>
<cleanHistoryOnStart>true</cleanHistoryOnStart> <encoder>
</rollingPolicy> <Pattern>%date %level %msg%n%n</Pattern>
<encoder> <charset>GBK</charset>
<Pattern>%date %level %msg%n%n</Pattern> </encoder>
<charset>GBK</charset> </appender>
</encoder> <appender name="pullFile"
</appender> class="ch.qos.logback.core.rolling.RollingFileAppender">
<appender name="pullFile" <file>${user.home}/nacos/logs/config-pull.log</file>
class="ch.qos.logback.core.rolling.RollingFileAppender"> <append>true</append>
<file>${user.home}/nacos/logs/config-pull.log</file> <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<append>true</append> <fileNamePattern>${user.home}/nacos/logs/config-pull.log.%d{yyyy-MM-dd}.%i</fileNamePattern>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy"> <maxFileSize>20MB</maxFileSize>
<fileNamePattern>${user.home}/nacos/logs/config-pull.log.%d{yyyy-MM-dd}.%i</fileNamePattern> <MaxHistory>15</MaxHistory>
<maxFileSize>20MB</maxFileSize> <totalSizeCap>128MB</totalSizeCap>
<MaxHistory>15</MaxHistory> <cleanHistoryOnStart>true</cleanHistoryOnStart>
<totalSizeCap>128MB</totalSizeCap> </rollingPolicy>
<cleanHistoryOnStart>true</cleanHistoryOnStart> <encoder>
</rollingPolicy> <Pattern>%date %level %msg%n%n</Pattern>
<encoder> <charset>GBK</charset>
<Pattern>%date %level %msg%n%n</Pattern> </encoder>
<charset>GBK</charset> </appender>
</encoder> <appender name="fatalFile"
</appender> class="ch.qos.logback.core.rolling.RollingFileAppender">
<appender name="fatalFile" <file>${user.home}/nacos/logs/config-fatal.log</file>
class="ch.qos.logback.core.rolling.RollingFileAppender"> <append>true</append>
<file>${user.home}/nacos/logs/config-fatal.log</file> <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<append>true</append> <fileNamePattern>${user.home}/nacos/logs/config-fatal.log.%d{yyyy-MM-dd}.%i</fileNamePattern>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy"> <maxFileSize>20MB</maxFileSize>
<fileNamePattern>${user.home}/nacos/logs/config-fatal.log.%d{yyyy-MM-dd}.%i</fileNamePattern> <MaxHistory>15</MaxHistory>
<maxFileSize>20MB</maxFileSize> <totalSizeCap>128MB</totalSizeCap>
<MaxHistory>15</MaxHistory> <cleanHistoryOnStart>true</cleanHistoryOnStart>
<totalSizeCap>128MB</totalSizeCap> </rollingPolicy>
<cleanHistoryOnStart>true</cleanHistoryOnStart> <encoder>
</rollingPolicy> <Pattern>%date %level %msg%n%n</Pattern>
<encoder> <charset>GBK</charset>
<Pattern>%date %level %msg%n%n</Pattern> </encoder>
<charset>GBK</charset> </appender>
</encoder> <appender name="memoryFile"
</appender> class="ch.qos.logback.core.rolling.RollingFileAppender">
<appender name="memoryFile" <file>${user.home}/nacos/logs/config-memory.log</file>
class="ch.qos.logback.core.rolling.RollingFileAppender"> <append>true</append>
<file>${user.home}/nacos/logs/config-memory.log</file> <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<append>true</append> <fileNamePattern>${user.home}/nacos/logs/config-memory.log.%d{yyyy-MM-dd}.%i</fileNamePattern>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy"> <maxFileSize>20MB</maxFileSize>
<fileNamePattern>${user.home}/nacos/logs/config-memory.log.%d{yyyy-MM-dd}.%i</fileNamePattern> <MaxHistory>15</MaxHistory>
<maxFileSize>20MB</maxFileSize> <totalSizeCap>128MB</totalSizeCap>
<MaxHistory>15</MaxHistory> <cleanHistoryOnStart>true</cleanHistoryOnStart>
<totalSizeCap>128MB</totalSizeCap> </rollingPolicy>
<cleanHistoryOnStart>true</cleanHistoryOnStart> <encoder>
</rollingPolicy> <Pattern>%date %level %msg%n%n</Pattern>
<encoder> <charset>GBK</charset>
<Pattern>%date %level %msg%n%n</Pattern> </encoder>
<charset>GBK</charset> </appender>
</encoder> <appender name="pullCheckFile"
</appender> class="ch.qos.logback.core.rolling.RollingFileAppender">
<appender name="pullCheckFile" <file>${user.home}/nacos/logs/config-pull-check.log</file>
class="ch.qos.logback.core.rolling.RollingFileAppender"> <append>true</append>
<file>${user.home}/nacos/logs/config-pull-check.log</file> <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<append>true</append> <fileNamePattern>${user.home}/nacos/logs/config-pull-check.log.%d{yyyy-MM-dd}.%i</fileNamePattern>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy"> <maxFileSize>1GB</maxFileSize>
<fileNamePattern>${user.home}/nacos/logs/config-pull-check.log.%d{yyyy-MM-dd}.%i</fileNamePattern> <MaxHistory>15</MaxHistory>
<maxFileSize>1GB</maxFileSize> <totalSizeCap>3GB</totalSizeCap>
<MaxHistory>15</MaxHistory> <cleanHistoryOnStart>true</cleanHistoryOnStart>
<totalSizeCap>3GB</totalSizeCap> </rollingPolicy>
<cleanHistoryOnStart>true</cleanHistoryOnStart> <encoder>
</rollingPolicy> <Pattern>%msg%n</Pattern>
<encoder> <charset>GBK</charset>
<Pattern>%msg%n</Pattern> </encoder>
<charset>GBK</charset> </appender>
</encoder>
</appender> <appender name="aclLog"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<appender name="aclLog" <file>${user.home}/nacos/logs/config-acl.log</file>
class="ch.qos.logback.core.rolling.RollingFileAppender"> <append>true</append>
<file>${user.home}/nacos/logs/config-acl.log</file> <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<append>true</append> <fileNamePattern>${user.home}/nacos/logs/config-acl.log.%d{yyyy-MM-dd}.%i</fileNamePattern>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy"> <maxFileSize>50MB</maxFileSize>
<fileNamePattern>${user.home}/nacos/logs/config-acl.log.%d{yyyy-MM-dd}.%i</fileNamePattern> <MaxHistory>15</MaxHistory>
<maxFileSize>50MB</maxFileSize> <totalSizeCap>512MB</totalSizeCap>
<MaxHistory>15</MaxHistory> <cleanHistoryOnStart>true</cleanHistoryOnStart>
<totalSizeCap>512MB</totalSizeCap> </rollingPolicy>
<cleanHistoryOnStart>true</cleanHistoryOnStart> <encoder>
</rollingPolicy> <Pattern>%date %level %msg%n%n</Pattern>
<encoder> <charset>GBK</charset>
<Pattern>%date %level %msg%n%n</Pattern> </encoder>
<charset>GBK</charset> </appender>
</encoder>
</appender> <appender name="clientLog"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<appender name="clientLog" <file>${user.home}/nacos/logs/config-client-request.log</file>
class="ch.qos.logback.core.rolling.RollingFileAppender"> <append>true</append>
<file>${user.home}/nacos/logs/config-client-request.log</file> <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<append>true</append> <fileNamePattern>${user.home}/nacos/logs/config-client-request.log.%d{yyyy-MM-dd}.%i</fileNamePattern>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy"> <maxFileSize>2GB</maxFileSize>
<fileNamePattern>${user.home}/nacos/logs/config-client-request.log.%d{yyyy-MM-dd}.%i</fileNamePattern> <MaxHistory>15</MaxHistory>
<maxFileSize>2GB</maxFileSize> <totalSizeCap>7GB</totalSizeCap>
<MaxHistory>15</MaxHistory> <cleanHistoryOnStart>true</cleanHistoryOnStart>
<totalSizeCap>7GB</totalSizeCap> </rollingPolicy>
<cleanHistoryOnStart>true</cleanHistoryOnStart> <encoder>
</rollingPolicy> <Pattern>%date|%msg%n</Pattern>
<encoder> <charset>GBK</charset>
<Pattern>%date|%msg%n</Pattern> </encoder>
<charset>GBK</charset> </appender>
</encoder>
</appender> <appender name="sdkLog"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<appender name="sdkLog" <file>${user.home}/nacos/logs/config-sdk-request.log</file>
class="ch.qos.logback.core.rolling.RollingFileAppender"> <append>true</append>
<file>${user.home}/nacos/logs/config-sdk-request.log</file> <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<append>true</append> <fileNamePattern>${user.home}/nacos/logs/config-sdk-request.log.%d{yyyy-MM-dd}.%i</fileNamePattern>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy"> <maxFileSize>1GB</maxFileSize>
<fileNamePattern>${user.home}/nacos/logs/config-sdk-request.log.%d{yyyy-MM-dd}.%i</fileNamePattern> <MaxHistory>15</MaxHistory>
<maxFileSize>1GB</maxFileSize> <totalSizeCap>3GB</totalSizeCap>
<MaxHistory>15</MaxHistory> <cleanHistoryOnStart>true</cleanHistoryOnStart>
<totalSizeCap>3GB</totalSizeCap> </rollingPolicy>
<cleanHistoryOnStart>true</cleanHistoryOnStart> <encoder>
</rollingPolicy> <Pattern>%date|%msg%n</Pattern>
<encoder> <charset>GBK</charset>
<Pattern>%date|%msg%n</Pattern> </encoder>
<charset>GBK</charset> </appender>
</encoder>
</appender> <appender name="traceLog"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<appender name="traceLog" <file>${user.home}/nacos/logs/config-trace.log</file>
class="ch.qos.logback.core.rolling.RollingFileAppender"> <append>true</append>
<file>${user.home}/nacos/logs/config-trace.log</file> <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<append>true</append> <fileNamePattern>${user.home}/nacos/logs/config-trace.log.%d{yyyy-MM-dd}.%i</fileNamePattern>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy"> <maxFileSize>2GB</maxFileSize>
<fileNamePattern>${user.home}/nacos/logs/config-trace.log.%d{yyyy-MM-dd}.%i</fileNamePattern> <MaxHistory>15</MaxHistory>
<maxFileSize>2GB</maxFileSize> <totalSizeCap>7GB</totalSizeCap>
<MaxHistory>15</MaxHistory> <cleanHistoryOnStart>true</cleanHistoryOnStart>
<totalSizeCap>7GB</totalSizeCap> </rollingPolicy>
<cleanHistoryOnStart>true</cleanHistoryOnStart> <encoder>
</rollingPolicy> <Pattern>%date|%msg%n</Pattern>
<encoder> <charset>GBK</charset>
<Pattern>%date|%msg%n</Pattern> </encoder>
<charset>GBK</charset> </appender>
</encoder>
</appender> <appender name="notifyLog"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<appender name="notifyLog" <file>${user.home}/nacos/logs/config-notify.log</file>
class="ch.qos.logback.core.rolling.RollingFileAppender"> <append>true</append>
<file>${user.home}/nacos/logs/config-notify.log</file> <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<append>true</append> <fileNamePattern>${user.home}/nacos/logs/config-notify.log.%d{yyyy-MM-dd}.%i</fileNamePattern>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy"> <maxFileSize>1GB</maxFileSize>
<fileNamePattern>${user.home}/nacos/logs/config-notify.log.%d{yyyy-MM-dd}.%i</fileNamePattern> <MaxHistory>15</MaxHistory>
<maxFileSize>1GB</maxFileSize> <totalSizeCap>3GB</totalSizeCap>
<MaxHistory>15</MaxHistory> <cleanHistoryOnStart>true</cleanHistoryOnStart>
<totalSizeCap>3GB</totalSizeCap> </rollingPolicy>
<cleanHistoryOnStart>true</cleanHistoryOnStart> <encoder>
</rollingPolicy> <Pattern>%date %level %msg%n%n</Pattern>
<encoder> <charset>GBK</charset>
<Pattern>%date %level %msg%n%n</Pattern> </encoder>
<charset>GBK</charset> </appender>
</encoder>
</appender> <appender name="appCollectorLog"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<appender name="appCollectorLog" <file>${user.home}/nacos/logs/config-app.log</file>
class="ch.qos.logback.core.rolling.RollingFileAppender"> <append>true</append>
<file>${user.home}/nacos/logs/config-app.log</file> <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<append>true</append> <fileNamePattern>${user.home}/nacos/logs/config-app.log.%d{yyyy-MM-dd}.%i</fileNamePattern>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy"> <maxFileSize>20MB</maxFileSize>
<fileNamePattern>${user.home}/nacos/logs/config-app.log.%d{yyyy-MM-dd}.%i</fileNamePattern> <MaxHistory>15</MaxHistory>
<maxFileSize>20MB</maxFileSize> <totalSizeCap>128MB</totalSizeCap>
<MaxHistory>15</MaxHistory> <cleanHistoryOnStart>true</cleanHistoryOnStart>
<totalSizeCap>128MB</totalSizeCap> </rollingPolicy>
<cleanHistoryOnStart>true</cleanHistoryOnStart> <encoder>
</rollingPolicy> <Pattern>%date %level %msg%n%n</Pattern>
<encoder> <charset>GBK</charset>
<Pattern>%date %level %msg%n%n</Pattern> </encoder>
<charset>GBK</charset> </appender>
</encoder>
</appender> <appender name="startLog"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<appender name="startLog" <file>${user.home}/nacos/logs/config-server.log</file>
class="ch.qos.logback.core.rolling.RollingFileAppender"> <append>true</append>
<file>${user.home}/nacos/logs/config-server.log</file> <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<append>true</append> <fileNamePattern>${user.home}/nacos/logs/config-server.log.%d{yyyy-MM-dd}.%i</fileNamePattern>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy"> <maxFileSize>50MB</maxFileSize>
<fileNamePattern>${user.home}/nacos/logs/config-server.log.%d{yyyy-MM-dd}.%i</fileNamePattern> <MaxHistory>15</MaxHistory>
<maxFileSize>50MB</maxFileSize> <totalSizeCap>512MB</totalSizeCap>
<MaxHistory>15</MaxHistory> <cleanHistoryOnStart>true</cleanHistoryOnStart>
<totalSizeCap>512MB</totalSizeCap> </rollingPolicy>
<cleanHistoryOnStart>true</cleanHistoryOnStart> <encoder>
</rollingPolicy> <Pattern>%date %level %msg%n%n</Pattern>
<encoder> <charset>GBK</charset>
<Pattern>%date %level %msg%n%n</Pattern> </encoder>
<charset>GBK</charset> </appender>
</encoder>
</appender> <appender name="rootFile"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<appender name="rootFile" <file>${user.home}/nacos/logs/nacos.log</file>
class="ch.qos.logback.core.rolling.RollingFileAppender"> <append>true</append>
<file>${user.home}/nacos/logs/nacos.log</file> <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<append>true</append> <fileNamePattern>${user.home}/nacos/logs/nacos.log.%d{yyyy-MM-dd}.%i</fileNamePattern>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy"> <maxFileSize>50MB</maxFileSize>
<fileNamePattern>${user.home}/nacos/logs/nacos.log.%d{yyyy-MM-dd}.%i</fileNamePattern> <MaxHistory>15</MaxHistory>
<maxFileSize>50MB</maxFileSize> <totalSizeCap>512MB</totalSizeCap>
<MaxHistory>15</MaxHistory> <cleanHistoryOnStart>true</cleanHistoryOnStart>
<totalSizeCap>512MB</totalSizeCap> </rollingPolicy>
<cleanHistoryOnStart>true</cleanHistoryOnStart> <encoder>
</rollingPolicy> <Pattern>%date %level %msg%n%n</Pattern>
<encoder> <charset>GBK</charset>
<Pattern>%date %level %msg%n%n</Pattern> </encoder>
<charset>GBK</charset> </appender>
</encoder>
</appender> <logger name="com.alibaba.nacos.config.dumpLog" additivity="false">
<level value="INFO"/>
<logger name="com.alibaba.nacos.config.dumpLog" additivity="false"> <appender-ref ref="dumpFile"/>
<level value="INFO" /> </logger>
<appender-ref ref="dumpFile" /> <logger name="com.alibaba.nacos.config.pullLog" additivity="false">
</logger> <level value="INFO"/>
<logger name="com.alibaba.nacos.config.pullLog" additivity="false"> <appender-ref ref="pullFile"/>
<level value="INFO" /> </logger>
<appender-ref ref="pullFile" /> <logger name="com.alibaba.nacos.config.pullCheckLog" additivity="false">
</logger> <level value="INFO"/>
<logger name="com.alibaba.nacos.config.pullCheckLog" additivity="false"> <appender-ref ref="pullCheckFile"/>
<level value="INFO" /> </logger>
<appender-ref ref="pullCheckFile" /> <logger name="com.alibaba.nacos.config.fatal" additivity="false">
</logger> <level value="INFO"/>
<logger name="com.alibaba.nacos.config.fatal" additivity="false"> <appender-ref ref="fatalFile"/>
<level value="INFO" /> </logger>
<appender-ref ref="fatalFile" /> <logger name="com.alibaba.nacos.config.monitorLog" additivity="false">
</logger> <level value="INFO"/>
<logger name="com.alibaba.nacos.config.monitorLog" additivity="false"> <appender-ref ref="memoryFile"/>
<level value="INFO" /> </logger>
<appender-ref ref="memoryFile" />
</logger> <logger name="com.alibaba.nacos.config.aclLog" additivity="false">
<level value="INFO"/>
<logger name="com.alibaba.nacos.config.aclLog" additivity="false"> <appender-ref ref="aclLog"/>
<level value="INFO" /> </logger>
<appender-ref ref="aclLog" />
</logger> <logger name="com.alibaba.nacos.config.clientLog" additivity="false">
<level value="info"/>
<logger name="com.alibaba.nacos.config.clientLog" additivity="false"> <appender-ref ref="clientLog"/>
<level value="info" /> </logger>
<appender-ref ref="clientLog" />
</logger> <logger name="com.alibaba.nacos.config.sdkLog" additivity="false">
<level value="INFO"/>
<logger name="com.alibaba.nacos.config.sdkLog" additivity="false"> <appender-ref ref="sdkLog"/>
<level value="INFO" /> </logger>
<appender-ref ref="sdkLog" />
</logger> <logger name="com.alibaba.nacos.config.notifyLog" additivity="false">
<level value="INFO"/>
<logger name="com.alibaba.nacos.config.notifyLog" additivity="false"> <appender-ref ref="notifyLog"/>
<level value="INFO" /> </logger>
<appender-ref ref="notifyLog" />
</logger> <logger name="com.alibaba.nacos.config.traceLog" additivity="false">
<level value="info"/>
<logger name="com.alibaba.nacos.config.traceLog" additivity="false"> <appender-ref ref="traceLog"/>
<level value="info" /> </logger>
<appender-ref ref="traceLog" />
</logger> <logger name="com.alibaba.nacos.config.appCollectorLog" additivity="false">
<level value="INFO"/>
<logger name="com.alibaba.nacos.config.appCollectorLog" additivity="false"> <appender-ref ref="appCollectorLog"/>
<level value="INFO" /> </logger>
<appender-ref ref="appCollectorLog" />
</logger> <logger name="com.alibaba.nacos.config.startLog" additivity="false">
<level value="INFO"/>
<logger name="com.alibaba.nacos.config.startLog" additivity="false"> <appender-ref ref="startLog"/>
<level value="INFO" /> </logger>
<appender-ref ref="startLog" />
</logger> <root>
<level value="INFO"/>
<root> <appender-ref ref="rootFile"/>
<level value="INFO" /> </root>
<appender-ref ref="rootFile" />
</root> </included>
</configuration>

View File

@ -1,17 +0,0 @@
# spring
management.security.enabled=false
server.servlet.context-path=/nacos
server.port=8848
db.num=2
db.url.0=url1
db.url.1=url2
db.user=user
db.password=pwd
spring.http.encoding.force=true
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
server.tomcat.uri-encoding=UTF-8
spring.messages.encoding=UTF-8
security.headers.content-type=application/json;charset=UTF-8

View File

@ -1,56 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.mock;
import java.util.Enumeration;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
public class FilterConfigMock implements FilterConfig {
public FilterConfigMock(ServletContext context) {
this.context = context;
}
@Override
public String getFilterName() {
// TODO Auto-generated method stub
return null;
}
@Override
public ServletContext getServletContext() {
return context;
}
@Override
public String getInitParameter(String name) {
// TODO Auto-generated method stub
return null;
}
@Override
public Enumeration getInitParameterNames() {
// TODO Auto-generated method stub
return null;
}
final ServletContext context;
}

View File

@ -1,356 +0,0 @@
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.mock;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Enumeration;
import java.util.EventListener;
import java.util.Map;
import java.util.Set;
import javax.servlet.Filter;
import javax.servlet.FilterRegistration;
import javax.servlet.FilterRegistration.Dynamic;
import javax.servlet.RequestDispatcher;
import javax.servlet.Servlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import javax.servlet.SessionCookieConfig;
import javax.servlet.SessionTrackingMode;
import javax.servlet.descriptor.JspConfigDescriptor;
public class ServletContextMock implements ServletContext {
@Override
public String getContextPath() {
// TODO Auto-generated method stub
return null;
}
@Override
public ServletContext getContext(String uripath) {
// TODO Auto-generated method stub
return null;
}
@Override
public int getMajorVersion() {
// TODO Auto-generated method stub
return 0;
}
@Override
public int getMinorVersion() {
// TODO Auto-generated method stub
return 0;
}
@Override
public String getMimeType(String file) {
// TODO Auto-generated method stub
return null;
}
@Override
public Set getResourcePaths(String path) {
// TODO Auto-generated method stub
return null;
}
@Override
public URL getResource(String path) throws MalformedURLException {
// TODO Auto-generated method stub
return null;
}
@Override
public InputStream getResourceAsStream(String path) {
// TODO Auto-generated method stub
return null;
}
@Override
public RequestDispatcher getRequestDispatcher(String path) {
// TODO Auto-generated method stub
return null;
}
@Override
public RequestDispatcher getNamedDispatcher(String name) {
// TODO Auto-generated method stub
return null;
}
@Override
public Servlet getServlet(String name) throws ServletException {
// TODO Auto-generated method stub
return null;
}
@Override
public Enumeration getServlets() {
// TODO Auto-generated method stub
return null;
}
@Override
public Enumeration getServletNames() {
// TODO Auto-generated method stub
return null;
}
@Override
public void log(String msg) {
// TODO Auto-generated method stub
}
@Override
public void log(Exception exception, String msg) {
// TODO Auto-generated method stub
}
@Override
public void log(String message, Throwable throwable) {
// TODO Auto-generated method stub
}
@Override
public String getRealPath(String path) {
// TODO Auto-generated method stub
return null;
}
@Override
public String getServerInfo() {
// TODO Auto-generated method stub
return null;
}
@Override
public String getInitParameter(String name) {
// TODO Auto-generated method stub
return null;
}
@Override
public Enumeration getInitParameterNames() {
// TODO Auto-generated method stub
return null;
}
@Override
public Object getAttribute(String name) {
// TODO Auto-generated method stub
return null;
}
@Override
public Enumeration getAttributeNames() {
// TODO Auto-generated method stub
return null;
}
@Override
public void setAttribute(String name, Object object) {
// TODO Auto-generated method stub
}
@Override
public void removeAttribute(String name) {
// TODO Auto-generated method stub
}
@Override
public String getServletContextName() {
// TODO Auto-generated method stub
return null;
}
@Override
public Dynamic addFilter(String arg0, String arg1) {
// TODO Auto-generated method stub
return null;
}
@Override
public Dynamic addFilter(String arg0, Filter arg1) {
// TODO Auto-generated method stub
return null;
}
@Override
public Dynamic addFilter(String arg0, Class<? extends Filter> arg1) {
// TODO Auto-generated method stub
return null;
}
@Override
public void addListener(Class<? extends EventListener> arg0) {
// TODO Auto-generated method stub
}
@Override
public void addListener(String arg0) {
// TODO Auto-generated method stub
}
@Override
public <T extends EventListener> void addListener(T arg0) {
// TODO Auto-generated method stub
}
@Override
public javax.servlet.ServletRegistration.Dynamic addServlet(String arg0, String arg1) {
// TODO Auto-generated method stub
return null;
}
@Override
public javax.servlet.ServletRegistration.Dynamic addServlet(String arg0, Servlet arg1) {
// TODO Auto-generated method stub
return null;
}
@Override
public javax.servlet.ServletRegistration.Dynamic addServlet(String arg0,
Class<? extends Servlet> arg1) {
// TODO Auto-generated method stub
return null;
}
@Override
public <T extends Filter> T createFilter(Class<T> arg0) throws ServletException {
// TODO Auto-generated method stub
return null;
}
@Override
public <T extends EventListener> T createListener(Class<T> arg0) throws ServletException {
// TODO Auto-generated method stub
return null;
}
@Override
public <T extends Servlet> T createServlet(Class<T> arg0) throws ServletException {
// TODO Auto-generated method stub
return null;
}
@Override
public void declareRoles(String... arg0) {
// TODO Auto-generated method stub
}
@Override
public ClassLoader getClassLoader() {
// TODO Auto-generated method stub
return null;
}
@Override
public Set<SessionTrackingMode> getDefaultSessionTrackingModes() {
// TODO Auto-generated method stub
return null;
}
@Override
public int getEffectiveMajorVersion() {
// TODO Auto-generated method stub
return 0;
}
@Override
public int getEffectiveMinorVersion() {
// TODO Auto-generated method stub
return 0;
}
@Override
public Set<SessionTrackingMode> getEffectiveSessionTrackingModes() {
// TODO Auto-generated method stub
return null;
}
@Override
public FilterRegistration getFilterRegistration(String arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public Map<String, ? extends FilterRegistration> getFilterRegistrations() {
// TODO Auto-generated method stub
return null;
}
@Override
public JspConfigDescriptor getJspConfigDescriptor() {
// TODO Auto-generated method stub
return null;
}
@Override
public ServletRegistration getServletRegistration(String arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public Map<String, ? extends ServletRegistration> getServletRegistrations() {
// TODO Auto-generated method stub
return null;
}
@Override
public SessionCookieConfig getSessionCookieConfig() {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean setInitParameter(String arg0, String arg1) {
// TODO Auto-generated method stub
return false;
}
@Override
public void setSessionTrackingModes(Set<SessionTrackingMode> arg0)
throws IllegalStateException, IllegalArgumentException {
// TODO Auto-generated method stub
}
@Override
public String getVirtualServerName() {
// TODO Auto-generated method stub
return null;
}
}

View File

@ -0,0 +1,91 @@
///*
// * Licensed to the Apache Software Foundation (ASF) under one or more
// * contributor license agreements. See the NOTICE file distributed with
// * this work for additional information regarding copyright ownership.
// * The ASF licenses this file to You under the Apache License, Version 2.0
// * (the "License"); you may not use this file except in compliance with
// * the License. You may obtain a copy of the License at
// *
// * http://www.apache.org/licenses/LICENSE-2.0
// *
// * Unless required by applicable law or agreed to in writing, software
// * distributed under the License is distributed on an "AS IS" BASIS,
// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// * See the License for the specific language governing permissions and
// * limitations under the License.
// */
//package com.alibaba.nacos.config.server.configuration;
//
//import org.apache.commons.dbcp.BasicDataSource;
//import org.junit.Assert;
//import org.junit.Test;
//import org.junit.runner.RunWith;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.beans.factory.annotation.Qualifier;
//import org.springframework.jdbc.core.JdbcTemplate;
//import org.springframework.jdbc.datasource.DataSourceTransactionManager;
//import org.springframework.test.context.ActiveProfiles;
//import org.springframework.test.context.ContextConfiguration;
//import org.springframework.test.context.TestPropertySource;
//import org.springframework.test.context.junit4.SpringRunner;
//import org.springframework.transaction.PlatformTransactionManager;
//
//import javax.sql.DataSource;
//
//import static com.alibaba.nacos.config.server.configuration.DataBaseConfiguration.DATA_SOURCE_BEAN_NAME;
//
///**
// * {@link LocalDataSourceConfiguration} Test
// *
// * @author <a href="mailto:mercyblitz@gmail.com">Mercy</a>
// * @since 0.2.2
// */
//@RunWith(SpringRunner.class)
//@ContextConfiguration(classes = {
// LocalDataSourceConfiguration.class,
// DataBaseConfiguration.class,
// LocalDataSourceConfigurationTest.class
//})
//@TestPropertySource(properties = {
// "db.initialSize=1",
// "db.maxActive=2",
// "db.maxIdle=3",
// "db.maxWait=4",
//})
//@ActiveProfiles("standalone")
//public class LocalDataSourceConfigurationTest {
//
// @Autowired
// @Qualifier(DATA_SOURCE_BEAN_NAME)
// private DataSource nacosConfigDataSource;
//
// @Autowired
// private JdbcTemplate jdbcTemplate;
//
// @Autowired
// private PlatformTransactionManager platformTransactionManager;
//
// @Test
// public void testDataSource() {
// Assert.assertNotNull(nacosConfigDataSource);
// Assert.assertTrue(nacosConfigDataSource instanceof BasicDataSource);
// BasicDataSource dataSource = BasicDataSource.class.cast(nacosConfigDataSource);
// Assert.assertEquals(1, dataSource.getInitialSize());
// Assert.assertEquals(2, dataSource.getMaxActive());
// Assert.assertEquals(3, dataSource.getMaxIdle());
// Assert.assertEquals(4, dataSource.getMaxWait());
// }
//
// @Test
// public void testJdbcTemplate() {
// Assert.assertEquals(jdbcTemplate.getDataSource(), nacosConfigDataSource);
// }
//
// @Test
// public void testPlatformTransactionManager() {
// Assert.assertTrue(platformTransactionManager instanceof DataSourceTransactionManager);
// DataSourceTransactionManager transactionManager = (DataSourceTransactionManager) platformTransactionManager;
// Assert.assertEquals(transactionManager.getDataSource(), nacosConfigDataSource);
// }
//
//}

View File

@ -0,0 +1,55 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.config.server.constant;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.mock.env.MockEnvironment;
import static com.alibaba.nacos.config.server.constant.Constants.*;
/**
* {@link Constants} Test
*
* @author <a href="mailto:mercyblitz@gmail.com">Mercy</a>
* @since 0.2.2
*/
public class ConstantsTest {
@Test
public void testControllerPathsDefaultValues() {
MockEnvironment environment = new MockEnvironment();
Assert.assertEquals(DEFAULT_CAPACITY_CONTROLLER_PATH, environment.resolvePlaceholders(CAPACITY_CONTROLLER_PATH));
Assert.assertEquals(DEFAULT_COMMUNICATION_CONTROLLER_PATH, environment.resolvePlaceholders(COMMUNICATION_CONTROLLER_PATH));
Assert.assertEquals(DEFAULT_CONFIG_CONTROLLER_PATH, environment.resolvePlaceholders(CONFIG_CONTROLLER_PATH));
Assert.assertEquals(DEFAULT_HEALTH_CONTROLLER_PATH, environment.resolvePlaceholders(HEALTH_CONTROLLER_PATH));
Assert.assertEquals(DEFAULT_HISTORY_CONTROLLER_PATH, environment.resolvePlaceholders(HISTORY_CONTROLLER_PATH));
Assert.assertEquals(DEFAULT_LISTENER_CONTROLLER_PATH, environment.resolvePlaceholders(LISTENER_CONTROLLER_PATH));
Assert.assertEquals(DEFAULT_NAMESPACE_CONTROLLER_PATH, environment.resolvePlaceholders(NAMESPACE_CONTROLLER_PATH));
Assert.assertEquals("/nacos/v1/cs/capacity", DEFAULT_CAPACITY_CONTROLLER_PATH);
Assert.assertEquals("/nacos/v1/cs/communication", DEFAULT_COMMUNICATION_CONTROLLER_PATH);
Assert.assertEquals("/nacos/v1/cs/configs", DEFAULT_CONFIG_CONTROLLER_PATH);
Assert.assertEquals("/nacos/v1/cs/health", DEFAULT_HEALTH_CONTROLLER_PATH);
Assert.assertEquals("/nacos/v1/cs/history", DEFAULT_HISTORY_CONTROLLER_PATH);
Assert.assertEquals("/nacos/v1/cs/listener", DEFAULT_LISTENER_CONTROLLER_PATH);
Assert.assertEquals("/nacos/v1/cs/namespaces", DEFAULT_NAMESPACE_CONTROLLER_PATH);
}
}

View File

@ -12,85 +12,70 @@
limitations under the License. limitations under the License.
--> -->
<project xmlns="http://maven.apache.org/POM/4.0.0" <project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <modelVersion>4.0.0</modelVersion>
<parent> <parent>
<groupId>com.alibaba.nacos</groupId> <groupId>com.alibaba.nacos</groupId>
<artifactId>nacos-all</artifactId> <artifactId>nacos-all</artifactId>
<version>0.2.1</version> <version>0.2.2-SNAPSHOT</version>
</parent> <relativePath>../pom.xml</relativePath>
<artifactId>nacos-console</artifactId> </parent>
<!--<packaging>war</packaging>--> <artifactId>nacos-console</artifactId>
<packaging>jar</packaging> <!--<packaging>war</packaging>-->
<name>nacos-console ${project.version}</name> <packaging>jar</packaging>
<url>http://maven.apache.org</url> <name>nacos-console ${project.version}</name>
<properties> <url>http://maven.apache.org</url>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <properties>
</properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<dependencies> </properties>
<dependencies>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>nacos-config</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<version>7.0.59</version>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>nacos-naming</artifactId>
</dependency>
<!-- log -->
<!-- log4j通过slf4j来代理 -->
<dependency> <dependency>
<groupId>org.slf4j</groupId> <groupId>${project.groupId}</groupId>
<artifactId>log4j-over-slf4j</artifactId> <artifactId>nacos-config</artifactId>
</dependency>
<!-- apache commons logging通过slf4j来代理 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
</dependency>
<!-- java.util.logging 通过slf4j来代理 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jul-to-slf4j</artifactId>
</dependency> </dependency>
<!-- log --> <dependency>
</dependencies> <groupId>${project.groupId}</groupId>
<build> <artifactId>nacos-naming</artifactId>
<finalName>nacos-server</finalName> </dependency>
<plugins>
<plugin> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.apache.tomcat.embed</groupId>
<artifactId>spring-boot-maven-plugin</artifactId> <artifactId>tomcat-embed-jasper</artifactId>
<configuration> </dependency>
<mainClass>com.alibaba.nacos.Nacos</mainClass>
</configuration> </dependencies>
<executions> <build>
<execution> <finalName>nacos-server</finalName>
<goals> <plugins>
<goal>repackage</goal> <plugin>
</goals> <groupId>org.springframework.boot</groupId>
</execution> <artifactId>spring-boot-maven-plugin</artifactId>
</executions> <configuration>
</plugin> <mainClass>com.alibaba.nacos.Nacos</mainClass>
</plugins> </configuration>
<resources> <executions>
<resource> <execution>
<filtering>true</filtering> <goals>
<directory>src/main/resources</directory> <goal>repackage</goal>
<excludes> </goals>
<exclude>application.properties</exclude> </execution>
<exclude>banner.txt</exclude> </executions>
<exclude>diamond-server-logback.xml</exclude> </plugin>
<exclude>schema.sql</exclude> </plugins>
</excludes> <resources>
</resource> <resource>
</resources> <filtering>true</filtering>
</build> <directory>src/main/resources</directory>
<excludes>
<exclude>application.properties</exclude>
<exclude>banner.txt</exclude>
<exclude>diamond-server-logback.xml</exclude>
<exclude>schema.sql</exclude>
</excludes>
</resource>
</resources>
</build>
</project> </project>

View File

@ -1,8 +1,5 @@
# spring # Console Default Properties
management.security.enabled=false
server.contextPath=/nacos
server.servlet.contextPath=/nacos
server.port=8848
spring.mvc.view.prefix=/jsp/ spring.mvc.view.prefix=/jsp/
# 响应页面默认后缀 # 响应页面默认后缀
spring.mvc.view.suffix=.jsp spring.mvc.view.suffix=.jsp

View File

@ -1,15 +0,0 @@
,--.
,--.'|
,--,: : |
,`--.'`| ' : ,---.
| : : | | ' ,'\ .--.--.
: | \ | : ,--.--. ,---. / / | / / '
| : ' '; | / \ / \. ; ,. :| : /`./
' ' ;. ;.--. .-. | / / '' | |: :| : ;_
| | | \ | \__\/: . .. ' / ' | .; : \ \ `.
' : | ; .' ," .--.; |' ; :__| : | `----. \
| | '`--' / / ,. |' | '.'|\ \ / / /`--' /
' : | ; : .' \ : : `----' '--'. /
; |.' | , .-./\ \ / `--'---'
'---' `--`---' `----'

Some files were not shown because too many files have changed in this diff Show More