Merge remote-tracking branch 'upstream/develop' into feature_support_grpc_core

# Conflicts:
#	api/pom.xml
#	client/src/main/java/com/alibaba/nacos/client/config/NacosConfigService.java
#	client/src/main/java/com/alibaba/nacos/client/naming/NacosNamingService.java
#	client/src/main/java/com/alibaba/nacos/client/naming/core/HostReactor.java
#	client/src/main/java/com/alibaba/nacos/client/naming/remote/http/NamingHttpClientProxy.java
#	client/src/test/java/com/alibaba/nacos/client/naming/core/HostReactorTest.java
#	common/src/main/java/com/alibaba/nacos/common/notify/NotifyCenter.java
#	core/pom.xml
#	naming/src/main/java/com/alibaba/nacos/naming/healthcheck/HttpHealthCheckProcessor.java
#	naming/src/main/java/com/alibaba/nacos/naming/web/DistroFilter.java
#	pom.xml
This commit is contained in:
KomachiSion 2020-11-20 17:13:49 +08:00
commit e56eb3680c
410 changed files with 2531 additions and 4339 deletions

1
.gitignore vendored
View File

@ -15,3 +15,4 @@ derby.log
work
test/logs
derby.log
yarn.lock

View File

@ -18,6 +18,7 @@ package com.alibaba.nacos.address.component;
import com.alibaba.nacos.address.constant.AddressServerConstants;
import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.common.utils.IPUtil;
import com.alibaba.nacos.naming.core.Instance;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
@ -85,14 +86,11 @@ public class AddressServerGeneratorManager {
}
private String[] generateIpAndPort(String ip) {
int index = ip.indexOf(AddressServerConstants.IP_PORT_SEPARATOR);
if (index != -1) {
return new String[] {ip.substring(0, index), ip.substring(index + 1)};
String[] result = IPUtil.splitIPPortStr(ip);
if (result.length != IPUtil.SPLIT_IP_PORT_RESULT_LENGTH) {
return new String[] {result[0], String.valueOf(AddressServerConstants.DEFAULT_SERVER_PORT)};
}
return new String[] {ip, String.valueOf(AddressServerConstants.DEFAULT_SERVER_PORT)};
return result;
}
/**

View File

@ -38,11 +38,6 @@ public interface AddressServerConstants {
*/
String DEFAULT_PRODUCT = "nacos";
/**
* the separator between ip and port.
*/
String IP_PORT_SEPARATOR = ":";
/**
* the separator for service name between raw service name and group.
*/

View File

@ -20,9 +20,9 @@ import com.alibaba.nacos.address.component.AddressServerGeneratorManager;
import com.alibaba.nacos.address.component.AddressServerManager;
import com.alibaba.nacos.address.constant.AddressServerConstants;
import com.alibaba.nacos.address.misc.Loggers;
import com.alibaba.nacos.address.util.AddressServerParamCheckUtil;
import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.naming.pojo.healthcheck.AbstractHealthChecker;
import com.alibaba.nacos.common.utils.IPUtil;
import com.alibaba.nacos.naming.core.Cluster;
import com.alibaba.nacos.naming.core.Instance;
import com.alibaba.nacos.naming.core.Service;
@ -87,8 +87,8 @@ public class AddressServerClusterController {
clusterObj.setHealthChecker(new AbstractHealthChecker.None());
serviceManager.createServiceIfAbsent(Constants.DEFAULT_NAMESPACE_ID, serviceName, false, clusterObj);
String[] ipArray = addressServerManager.splitIps(ips);
String checkResult = AddressServerParamCheckUtil.checkIps(ipArray);
if (AddressServerParamCheckUtil.CHECK_OK.equals(checkResult)) {
String checkResult = IPUtil.checkIPs(ipArray);
if (IPUtil.checkOK(checkResult)) {
List<Instance> instanceList = addressServerGeneratorManager
.generateInstancesByIps(serviceName, rawProductName, clusterName, ipArray);
for (Instance instance : instanceList) {
@ -143,8 +143,8 @@ public class AddressServerClusterController {
} else {
// delete specified ip list
String[] ipArray = addressServerManager.splitIps(ips);
String checkResult = AddressServerParamCheckUtil.checkIps(ipArray);
if (AddressServerParamCheckUtil.CHECK_OK.equals(checkResult)) {
String checkResult = IPUtil.checkIPs(ipArray);
if (IPUtil.checkOK(checkResult)) {
List<Instance> instanceList = addressServerGeneratorManager
.generateInstancesByIps(serviceName, rawProductName, clusterName, ipArray);
serviceManager.removeInstance(Constants.DEFAULT_NAMESPACE_ID, serviceName, false,

View File

@ -1,67 +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.address.util;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Provides a unified tool class for address server parameter verification.
*
* @author pbting
* @date 2019-06-19 11:19 AM
* @since 1.1.0
*/
public class AddressServerParamCheckUtil {
public static final String CHECK_OK = "ok";
public static final String ILLEGAL_IP_PREFIX = "illegal ip: ";
private static final String IP_REGEX = "(2(5[0-5]{1}|[0-4]\\d{1})|[0-1]?\\d{1,2})(\\.(2(5[0-5]{1}|[0-4]\\d{1})|[0-1]?\\d{1,2})){3}";
private static final Pattern IP_PATTERN = Pattern.compile(IP_REGEX);
/**
* Check ips.
*
* @param ips ips
* @return 'ok' if check passed, otherwise illegal ip
*/
public static String checkIps(String... ips) {
if (ips == null || ips.length == 0) {
return CHECK_OK;
}
// illegal response
StringBuilder illegalResponse = new StringBuilder();
for (String ip : ips) {
Matcher matcher = IP_PATTERN.matcher(ip);
if (matcher.matches()) {
continue;
}
illegalResponse.append(ip + ",");
}
if (illegalResponse.length() == 0) {
return CHECK_OK;
}
return ILLEGAL_IP_PREFIX + illegalResponse.substring(0, illegalResponse.length() - 1);
}
}

View File

@ -16,17 +16,17 @@
package com.alibaba.nacos.address;
import com.alibaba.nacos.address.util.AddressServerParamCheckUtil;
import com.alibaba.nacos.common.utils.IPUtil;
import org.junit.Test;
public class ParamCheckUtilTests {
@Test
public void checkIps() {
public void checkIPs() {
String[] ips = {"127.0.0.1"};
System.out.println(AddressServerParamCheckUtil.checkIps(ips));
System.out.println(IPUtil.checkIPs(ips));
String[] illlegalIps = {"127.100.19", "127.0.0.1"};
System.err.println(AddressServerParamCheckUtil.checkIps(illlegalIps));
System.err.println(IPUtil.checkIPs(illlegalIps));
}
}

View File

@ -59,7 +59,6 @@
<target>6</target>
</configuration>
</plugin>
</plugins>
</build>
@ -80,10 +79,6 @@
<groupId>org.reflections</groupId>
<artifactId>reflections</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
@ -98,8 +93,7 @@
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-netty-shaded</artifactId>

View File

@ -79,6 +79,18 @@ public interface ConfigService {
*/
boolean publishConfig(String dataId, String group, String content) throws NacosException;
/**
* Publish config.
*
* @param dataId dataId
* @param group group
* @param content content
* @param type config type {@link ConfigType}
* @return Whether publish
* @throws NacosException NacosException
*/
boolean publishConfig(String dataId, String group, String content, String type) throws NacosException;
/**
* Remove config.
*

View File

@ -16,6 +16,8 @@
package com.alibaba.nacos.api.config;
import com.alibaba.nacos.api.utils.StringUtils;
/**
* Config data type.
*
@ -62,4 +64,26 @@ public enum ConfigType {
public String getType() {
return type;
}
public static ConfigType getDefaultType() {
return TEXT;
}
/**
* check input type is valid.
*
* @param type config type
* @return it the type valid
*/
public static Boolean isValidType(String type) {
if (StringUtils.isBlank(type)) {
return false;
}
for (ConfigType value : values()) {
if (value.type.equals(type)) {
return true;
}
}
return false;
}
}

View File

@ -0,0 +1,38 @@
/*
* 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.api.naming.listener;
import java.util.concurrent.Executor;
/**
* Abstract event listener, to support handle event by user custom executor.
*
* @author horizonzy
* @since 1.4.1
*/
public abstract class AbstractEventListener implements EventListener {
/**
* Get executor for execute this receive.
*
* @return Executor
*/
public Executor getExecutor() {
return null;
}
}

View File

@ -31,6 +31,7 @@ import java.util.List;
* ServiceInfo.
*
* @author nkorange
* @author shizhengxing
*/
@JsonInclude(Include.NON_NULL)
public class ServiceInfo {
@ -67,19 +68,28 @@ public class ServiceInfo {
this.allIPs = allIPs;
}
/**
* There is only one form of the key:groupName@@name@clusters. This constuctor used by DiskCache.read(String) and
* FailoverReactor.FailoverFileReader,you should know that 'groupName' must not be null,and 'clusters' can be null.
*/
public ServiceInfo(String key) {
int maxIndex = 2;
int clusterIndex = 1;
int serviceNameIndex = 0;
int clusterIndex = 2;
int serviceNameIndex = 1;
int groupIndex = 0;
String[] keys = key.split(Constants.SERVICE_INFO_SPLITER);
if (keys.length >= maxIndex) {
if (keys.length >= maxIndex + 1) {
this.groupName = keys[groupIndex];
this.name = keys[serviceNameIndex];
this.clusters = keys[clusterIndex];
} else if (keys.length == maxIndex) {
this.groupName = keys[groupIndex];
this.name = keys[serviceNameIndex];
} else {
//defensive programming
throw new IllegalArgumentException("Cann't parse out 'groupName',but it must not be null!");
}
this.name = keys[0];
}
public ServiceInfo(String name, String clusters) {
@ -190,7 +200,8 @@ public class ServiceInfo {
@JsonIgnore
public String getKey() {
return getKey(name, clusters);
String serviceName = getGroupedServiceName();
return getKey(serviceName, clusters);
}
@JsonIgnore
@ -205,11 +216,21 @@ public class ServiceInfo {
@JsonIgnore
public String getKeyEncoded() {
String serviceName = getGroupedServiceName();
try {
return getKey(URLEncoder.encode(name, "UTF-8"), clusters);
serviceName = URLEncoder.encode(serviceName, "UTF-8");
} catch (UnsupportedEncodingException e) {
return getKey();
//do nothing
}
return getKey(serviceName, clusters);
}
private String getGroupedServiceName() {
String serviceName = this.name;
if (!isEmpty(groupName) && serviceName.indexOf(Constants.SERVICE_INFO_SPLITER) == -1) {
serviceName = groupName + Constants.SERVICE_INFO_SPLITER + serviceName;
}
return serviceName;
}
/**

View File

@ -56,9 +56,7 @@ public class NamingUtils {
}
/**
* check combineServiceName format. the serviceName can't be blank. some relational logic in {@link
* com.alibaba.nacos.naming.web.DistroFilter#doFilter}, it will handle combineServiceName in some case, you should
* know it.
* check combineServiceName format. the serviceName can't be blank.
* <pre>
* serviceName = "@@"; the length = 0; illegal
* serviceName = "group@@"; the length = 1; illegal

View File

@ -23,6 +23,8 @@ import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
@ -38,13 +40,13 @@ public class ServiceInfoTest {
public void setUp() throws Exception {
mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
serviceInfo = new ServiceInfo("testName", "testClusters");
serviceInfo = new ServiceInfo("G@@testName", "testClusters");
}
@Test
public void testSerialize() throws JsonProcessingException {
String actual = mapper.writeValueAsString(serviceInfo);
assertTrue(actual.contains("\"name\":\"testName\""));
assertTrue(actual.contains("\"name\":\"G@@testName\""));
assertTrue(actual.contains("\"clusters\":\"testClusters\""));
assertTrue(actual.contains("\"cacheMillis\":1000"));
assertTrue(actual.contains("\"hosts\":[]"));
@ -58,11 +60,11 @@ public class ServiceInfoTest {
}
@Test
@SuppressWarnings("checkstyle:linelength")
public void testDeserialize() throws IOException {
String example = "{\"name\":\"testName\",\"clusters\":\"testClusters\",\"cacheMillis\":1000,\"hosts\":[],\"lastRefTime\":0,\"checksum\":\"\",\"allIPs\":false,\"valid\":true,\"groupName\":\"\"}";
String example = "{\"name\":\"G@@testName\",\"clusters\":\"testClusters\",\"cacheMillis\":1000,\"hosts\":[],"
+ "\"lastRefTime\":0,\"checksum\":\"\",\"allIPs\":false,\"valid\":true,\"groupName\":\"\"}";
ServiceInfo actual = mapper.readValue(example, ServiceInfo.class);
assertEquals("testName", actual.getName());
assertEquals("G@@testName", actual.getName());
assertEquals("testClusters", actual.getClusters());
assertEquals("", actual.getChecksum());
assertEquals("", actual.getGroupName());
@ -72,4 +74,32 @@ public class ServiceInfoTest {
assertTrue(actual.isValid());
assertFalse(actual.isAllIPs());
}
@Test
public void testGetKey() {
String key = serviceInfo.getKey();
assertEquals("G@@testName@@testClusters", key);
}
@Test
public void testGetKeyEncode() {
String key = serviceInfo.getKeyEncoded();
String encodeName = null;
try {
encodeName = URLEncoder.encode("G@@testName", "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
assertEquals(key, ServiceInfo.getKey(encodeName, "testClusters"));
}
@Test
public void testServiceInfoConstructor() {
String key1 = "group@@name";
String key2 = "group@@name@@c2";
ServiceInfo s1 = new ServiceInfo(key1);
ServiceInfo s2 = new ServiceInfo(key2);
assertEquals(key1, s1.getKey());
assertEquals(key2, s2.getKey());
}
}

View File

@ -19,6 +19,7 @@ package com.alibaba.nacos.client.config;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.ConfigType;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.client.config.filter.impl.ConfigFilterChainManager;
@ -88,7 +89,12 @@ public class NacosConfigService implements ConfigService {
@Override
public boolean publishConfig(String dataId, String group, String content) throws NacosException {
return publishConfigInner(namespace, dataId, group, null, null, null, content);
return publishConfig(dataId, group, content, ConfigType.getDefaultType().getType());
}
@Override
public boolean publishConfig(String dataId, String group, String content, String type) throws NacosException {
return publishConfigInner(namespace, dataId, group, null, null, null, content, type);
}
@Override
@ -157,7 +163,7 @@ public class NacosConfigService implements ConfigService {
}
private boolean publishConfigInner(String tenant, String dataId, String group, String tag, String appName,
String betaIps, String content) throws NacosException {
String betaIps, String content, String type) throws NacosException {
group = null2defaultGroup(group);
ParamUtils.checkParam(dataId, group, content);

View File

@ -30,6 +30,7 @@ import com.alibaba.nacos.common.http.param.Query;
import com.alibaba.nacos.common.lifecycle.Closeable;
import com.alibaba.nacos.common.notify.NotifyCenter;
import com.alibaba.nacos.common.utils.IoUtils;
import com.alibaba.nacos.common.utils.IPUtil;
import com.alibaba.nacos.common.utils.StringUtils;
import com.alibaba.nacos.common.utils.ThreadUtils;
import org.slf4j.Logger;
@ -87,9 +88,9 @@ public class ServerListManager implements Closeable {
this.isStarted = true;
List<String> serverAddrs = new ArrayList<String>();
for (String serverAddr : fixed) {
String[] serverAddrArr = serverAddr.split(":");
String[] serverAddrArr = IPUtil.splitIPPortStr(serverAddr);
if (serverAddrArr.length == 1) {
serverAddrs.add(serverAddrArr[0] + ":" + ParamUtil.getDefaultServerPort());
serverAddrs.add(serverAddrArr[0] + IPUtil.IP_PORT_SPLITER + ParamUtil.getDefaultServerPort());
} else {
serverAddrs.add(serverAddr);
}
@ -156,9 +157,10 @@ public class ServerListManager implements Closeable {
if (serverAddr.startsWith(HTTPS) || serverAddr.startsWith(HTTP)) {
serverAddrs.add(serverAddr);
} else {
String[] serverAddrArr = serverAddr.split(":");
String[] serverAddrArr = IPUtil.splitIPPortStr(serverAddr);
if (serverAddrArr.length == 1) {
serverAddrs.add(HTTP + serverAddrArr[0] + ":" + ParamUtil.getDefaultServerPort());
serverAddrs.add(HTTP + serverAddrArr[0] + IPUtil.IP_PORT_SPLITER + ParamUtil
.getDefaultServerPort());
} else {
serverAddrs.add(HTTP + serverAddr);
}
@ -355,10 +357,10 @@ public class ServerListManager implements Closeable {
List<String> result = new ArrayList<String>(lines.size());
for (String serverAddr : lines) {
if (StringUtils.isNotBlank(serverAddr)) {
String[] ipPort = serverAddr.trim().split(":");
String[] ipPort = IPUtil.splitIPPortStr(serverAddr.trim());
String ip = ipPort[0].trim();
if (ipPort.length == 1) {
result.add(ip + ":" + ParamUtil.getDefaultServerPort());
result.add(ip + IPUtil.IP_PORT_SPLITER + ParamUtil.getDefaultServerPort());
} else {
result.add(serverAddr);
}

View File

@ -17,7 +17,7 @@
package com.alibaba.nacos.client.config.utils;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.common.utils.IpUtils;
import com.alibaba.nacos.common.utils.IPUtil;
import com.alibaba.nacos.common.utils.StringUtils;
import java.util.List;
@ -190,7 +190,7 @@ public class ParamUtils {
}
String[] ipsArr = betaIps.split(",");
for (String ip : ipsArr) {
if (!IpUtils.isIpv4(ip)) {
if (!IPUtil.isIP(ip)) {
throw new NacosException(NacosException.CLIENT_INVALID_PARAM, "betaIps invalid");
}
}

View File

@ -1,189 +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.naming.core;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.listener.EventListener;
import com.alibaba.nacos.api.naming.listener.NamingEvent;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.api.naming.pojo.ServiceInfo;
import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.alibaba.nacos.common.lifecycle.Closeable;
import com.alibaba.nacos.common.utils.ThreadUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import static com.alibaba.nacos.client.utils.LogUtils.NAMING_LOGGER;
/**
* Event dispatcher.
*
* @author xuanyin
*/
@SuppressWarnings("PMD.ThreadPoolCreationRule")
public class EventDispatcher implements Closeable {
private ExecutorService executor = null;
private final BlockingQueue<ServiceInfo> changedServices = new LinkedBlockingQueue<ServiceInfo>();
private final ConcurrentMap<String, List<EventListener>> observerMap = new ConcurrentHashMap<String, List<EventListener>>();
private volatile boolean closed = false;
public EventDispatcher() {
this.executor = Executors.newSingleThreadExecutor(new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r, "com.alibaba.nacos.naming.client.listener");
thread.setDaemon(true);
return thread;
}
});
this.executor.execute(new Notifier());
}
/**
* Add listener.
*
* @param serviceInfo service info
* @param clusters clusters
* @param listener listener
*/
public void addListener(ServiceInfo serviceInfo, String clusters, EventListener listener) {
NAMING_LOGGER.info("[LISTENER] adding " + serviceInfo.getName() + " with " + clusters + " to listener map");
List<EventListener> observers = Collections.synchronizedList(new ArrayList<EventListener>());
observers.add(listener);
observers = observerMap.putIfAbsent(ServiceInfo.getKey(serviceInfo.getName(), clusters), observers);
if (observers != null) {
observers.add(listener);
}
serviceChanged(serviceInfo);
}
/**
* Remove listener.
*
* @param serviceName service name
* @param clusters clusters
* @param listener listener
*/
public void removeListener(String serviceName, String clusters, EventListener listener) {
NAMING_LOGGER.info("[LISTENER] removing " + serviceName + " with " + clusters + " from listener map");
List<EventListener> observers = observerMap.get(ServiceInfo.getKey(serviceName, clusters));
if (observers != null) {
Iterator<EventListener> iter = observers.iterator();
while (iter.hasNext()) {
EventListener oldListener = iter.next();
if (oldListener.equals(listener)) {
iter.remove();
}
}
if (observers.isEmpty()) {
observerMap.remove(ServiceInfo.getKey(serviceName, clusters));
}
}
}
public boolean isSubscribed(String serviceName, String clusters) {
return observerMap.containsKey(ServiceInfo.getKey(serviceName, clusters));
}
public List<ServiceInfo> getSubscribeServices() {
List<ServiceInfo> serviceInfos = new ArrayList<ServiceInfo>();
for (String key : observerMap.keySet()) {
serviceInfos.add(ServiceInfo.fromKey(key));
}
return serviceInfos;
}
/**
* Service changed.
*
* @param serviceInfo service info
*/
public void serviceChanged(ServiceInfo serviceInfo) {
if (serviceInfo == null) {
return;
}
changedServices.add(serviceInfo);
}
@Override
public void shutdown() throws NacosException {
String className = this.getClass().getName();
NAMING_LOGGER.info("{} do shutdown begin", className);
ThreadUtils.shutdownThreadPool(executor, NAMING_LOGGER);
closed = true;
NAMING_LOGGER.info("{} do shutdown stop", className);
}
private class Notifier implements Runnable {
@Override
public void run() {
while (!closed) {
ServiceInfo serviceInfo = null;
try {
serviceInfo = changedServices.poll(5, TimeUnit.MINUTES);
} catch (Exception ignore) {
}
if (serviceInfo == null) {
continue;
}
try {
List<EventListener> listeners = observerMap.get(serviceInfo.getKey());
if (!CollectionUtils.isEmpty(listeners)) {
for (EventListener listener : listeners) {
List<Instance> hosts = Collections.unmodifiableList(serviceInfo.getHosts());
listener.onEvent(new NamingEvent(serviceInfo.getName(), serviceInfo.getGroupName(),
serviceInfo.getClusters(), hosts));
}
}
} catch (Exception e) {
NAMING_LOGGER.error("[NA] notify error for service: " + serviceInfo.getName() + ", clusters: "
+ serviceInfo.getClusters(), e);
}
}
}
}
}

View File

@ -0,0 +1,65 @@
/*
* 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.naming.event;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.common.notify.Event;
import java.util.List;
/**
* Instances change event.
*
* @author horizonzy
* @since 1.4.1
*/
public class InstancesChangeEvent extends Event {
private static final long serialVersionUID = -8823087028212249603L;
private final String serviceName;
private final String groupName;
private final String clusters;
private final List<Instance> hosts;
public InstancesChangeEvent(String serviceName, String groupName, String clusters, List<Instance> hosts) {
this.serviceName = serviceName;
this.groupName = groupName;
this.clusters = clusters;
this.hosts = hosts;
}
public String getServiceName() {
return serviceName;
}
public String getGroupName() {
return groupName;
}
public String getClusters() {
return clusters;
}
public List<Instance> getHosts() {
return hosts;
}
}

View File

@ -0,0 +1,140 @@
/*
* 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.naming.event;
import com.alibaba.nacos.api.naming.listener.AbstractEventListener;
import com.alibaba.nacos.api.naming.listener.EventListener;
import com.alibaba.nacos.api.naming.listener.NamingEvent;
import com.alibaba.nacos.api.naming.pojo.ServiceInfo;
import com.alibaba.nacos.common.notify.Event;
import com.alibaba.nacos.common.notify.listener.Subscriber;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.alibaba.nacos.common.utils.ConcurrentHashSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* A subscriber to notify eventListener callback.
*
* @author horizonzy
* @since 1.4.1
*/
public class InstancesChangeNotifier extends Subscriber<InstancesChangeEvent> {
private final Map<String, ConcurrentHashSet<EventListener>> listenerMap = new ConcurrentHashMap<String, ConcurrentHashSet<EventListener>>();
private final Object lock = new Object();
/**
* register listener.
*
* @param serviceName combineServiceName, such as 'xxx@@xxx'
* @param clusters clusters, concat by ','. such as 'xxx,yyy'
* @param listener custom listener
*/
public void registerListener(String serviceName, String clusters, EventListener listener) {
String key = ServiceInfo.getKey(serviceName, clusters);
ConcurrentHashSet<EventListener> eventListeners = listenerMap.get(key);
if (eventListeners == null) {
synchronized (lock) {
eventListeners = listenerMap.get(key);
if (eventListeners == null) {
eventListeners = new ConcurrentHashSet<EventListener>();
listenerMap.put(key, eventListeners);
}
}
}
eventListeners.add(listener);
}
/**
* deregister listener.
*
* @param serviceName combineServiceName, such as 'xxx@@xxx'
* @param clusters clusters, concat by ','. such as 'xxx,yyy'
* @param listener custom listener
*/
public void deregisterListener(String serviceName, String clusters, EventListener listener) {
String key = ServiceInfo.getKey(serviceName, clusters);
ConcurrentHashSet<EventListener> eventListeners = listenerMap.get(key);
if (eventListeners == null) {
return;
}
eventListeners.remove(listener);
if (CollectionUtils.isEmpty(eventListeners)) {
listenerMap.remove(key);
}
}
/**
* check serviceName,clusters is subscribed.
*
* @param serviceName combineServiceName, such as 'xxx@@xxx'
* @param clusters clusters, concat by ','. such as 'xxx,yyy'
* @return is serviceName,clusters subscribed
*/
public boolean isSubscribed(String serviceName, String clusters) {
String key = ServiceInfo.getKey(serviceName, clusters);
ConcurrentHashSet<EventListener> eventListeners = listenerMap.get(key);
return CollectionUtils.isNotEmpty(eventListeners);
}
public List<ServiceInfo> getSubscribeServices() {
List<ServiceInfo> serviceInfos = new ArrayList<ServiceInfo>();
for (String key : listenerMap.keySet()) {
serviceInfos.add(ServiceInfo.fromKey(key));
}
return serviceInfos;
}
@Override
public void onEvent(InstancesChangeEvent event) {
String key = ServiceInfo.getKey(event.getServiceName(), event.getClusters());
ConcurrentHashSet<EventListener> eventListeners = listenerMap.get(key);
if (CollectionUtils.isEmpty(eventListeners)) {
return;
}
for (final EventListener listener : eventListeners) {
final com.alibaba.nacos.api.naming.listener.Event namingEvent = transferToNamingEvent(event);
if (listener instanceof AbstractEventListener && ((AbstractEventListener) listener).getExecutor() != null) {
((AbstractEventListener) listener).getExecutor().execute(new Runnable() {
@Override
public void run() {
listener.onEvent(namingEvent);
}
});
continue;
}
listener.onEvent(namingEvent);
}
}
private com.alibaba.nacos.api.naming.listener.Event transferToNamingEvent(
InstancesChangeEvent instancesChangeEvent) {
return new NamingEvent(instancesChangeEvent.getServiceName(), instancesChangeEvent.getGroupName(),
instancesChangeEvent.getClusters(), instancesChangeEvent.getHosts());
}
@Override
public Class<? extends Event> subscribeType() {
return InstancesChangeEvent.class;
}
}

View File

@ -50,6 +50,8 @@ import com.alibaba.nacos.common.http.client.NacosRestTemplate;
import com.alibaba.nacos.common.http.param.Header;
import com.alibaba.nacos.common.http.param.Query;
import com.alibaba.nacos.common.utils.HttpMethod;
import com.alibaba.nacos.common.utils.IoUtils;
import com.alibaba.nacos.common.utils.IPUtil;
import com.alibaba.nacos.common.utils.JacksonUtils;
import com.alibaba.nacos.common.utils.StringUtils;
import com.alibaba.nacos.common.utils.ThreadUtils;
@ -474,8 +476,8 @@ public class NamingHttpClientProxy implements NamingClientProxy {
if (curServer.startsWith(UtilAndComs.HTTPS) || curServer.startsWith(UtilAndComs.HTTP)) {
url = curServer + api;
} else {
if (!curServer.contains(UtilAndComs.SERVER_ADDR_IP_SPLITER)) {
curServer = curServer + UtilAndComs.SERVER_ADDR_IP_SPLITER + serverPort;
if (!IPUtil.containsPort(curServer)) {
curServer = curServer + IPUtil.IP_PORT_SPLITER + serverPort;
}
url = NamingHttpClientManager.getInstance().getPrefix() + curServer + api;
}

View File

@ -53,8 +53,6 @@ public class UtilAndComs {
public static final String NACOS_NAMING_LOG_LEVEL = "com.alibaba.nacos.naming.log.level";
public static final String SERVER_ADDR_IP_SPLITER = ":";
public static final int DEFAULT_CLIENT_BEAT_THREAD_COUNT =
Runtime.getRuntime().availableProcessors() > 1 ? Runtime.getRuntime().availableProcessors() / 2 : 1;

View File

@ -41,7 +41,7 @@ public class DiskCacheTest {
@Before
public void setUp() throws Exception {
System.out.println(CACHE_DIR);
serviceInfo = new ServiceInfo("testName", "testClusters");
serviceInfo = new ServiceInfo("G@@testName", "testClusters");
instance = new Instance();
instance.setClusterName("testClusters");
instance.setIp("1.1.1.1");
@ -66,8 +66,8 @@ public class DiskCacheTest {
DiskCache.write(serviceInfo, CACHE_DIR);
Map<String, ServiceInfo> actual = DiskCache.read(CACHE_DIR);
assertEquals(1, actual.size());
assertTrue(actual.containsKey(serviceInfo.getKeyEncoded()));
assertServiceInfo(actual.get(serviceInfo.getKeyEncoded()), serviceInfo);
assertTrue(actual.containsKey(serviceInfo.getKey()));
assertServiceInfo(actual.get(serviceInfo.getKey()), serviceInfo);
}
private void assertServiceInfo(ServiceInfo actual, ServiceInfo expected) {

View File

@ -18,8 +18,8 @@ package com.alibaba.nacos.common.http;
import com.alibaba.nacos.common.http.client.NacosRestTemplate;
import com.alibaba.nacos.common.http.client.request.DefaultHttpClientRequest;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.RequestContent;
/**
* apache http client factory implements.
@ -31,9 +31,10 @@ public abstract class AbstractApacheHttpClientFactory extends AbstractHttpClient
@Override
public final NacosRestTemplate createNacosRestTemplate() {
final HttpClientConfig originalRequestConfig = buildHttpClientConfig();
final RequestConfig requestConfig = getRequestConfig();
return new NacosRestTemplate(assignLogger(), new DefaultHttpClientRequest(
HttpClients.custom().setDefaultRequestConfig(requestConfig)
HttpClients.custom()
.addInterceptorLast(new RequestContent(true))
.setDefaultRequestConfig(getRequestConfig())
.setUserAgent(originalRequestConfig.getUserAgent())
.setMaxConnTotal(originalRequestConfig.getMaxConnTotal())
.setMaxConnPerRoute(originalRequestConfig.getMaxConnPerRoute())

View File

@ -27,6 +27,8 @@ import com.alibaba.nacos.common.tls.TlsSystemConfig;
import com.alibaba.nacos.common.utils.BiConsumer;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.protocol.RequestContent;
import org.apache.http.impl.nio.reactor.IOReactorConfig;
import org.slf4j.Logger;
import javax.net.ssl.HostnameVerifier;
@ -68,19 +70,27 @@ public abstract class AbstractHttpClientFactory implements HttpClientFactory {
@Override
public NacosAsyncRestTemplate createNacosAsyncRestTemplate() {
final HttpClientConfig originalRequestConfig = buildHttpClientConfig();
final RequestConfig requestConfig = getRequestConfig();
return new NacosAsyncRestTemplate(assignLogger(), new DefaultAsyncHttpClientRequest(
HttpAsyncClients.custom().setDefaultRequestConfig(requestConfig)
HttpAsyncClients.custom()
.addInterceptorLast(new RequestContent(true))
.setDefaultIOReactorConfig(getIoReactorConfig())
.setDefaultRequestConfig(getRequestConfig())
.setMaxConnTotal(originalRequestConfig.getMaxConnTotal())
.setMaxConnPerRoute(originalRequestConfig.getMaxConnPerRoute())
.setUserAgent(originalRequestConfig.getUserAgent()).build()));
}
protected IOReactorConfig getIoReactorConfig() {
HttpClientConfig httpClientConfig = buildHttpClientConfig();
return IOReactorConfig.custom().setIoThreadCount(httpClientConfig.getIoThreadCount()).build();
}
protected RequestConfig getRequestConfig() {
HttpClientConfig httpClientConfig = buildHttpClientConfig();
return RequestConfig.custom().setConnectTimeout(httpClientConfig.getConTimeOutMillis())
.setSocketTimeout(httpClientConfig.getReadTimeOutMillis())
.setConnectionRequestTimeout(httpClientConfig.getConnectionRequestTimeout())
.setContentCompressionEnabled(httpClientConfig.getContentCompressionEnabled())
.setMaxRedirects(httpClientConfig.getMaxRedirects()).build();
}

View File

@ -18,10 +18,14 @@ package com.alibaba.nacos.common.http;
import com.alibaba.nacos.common.http.client.NacosAsyncRestTemplate;
import com.alibaba.nacos.common.http.client.NacosRestTemplate;
import com.alibaba.nacos.common.utils.ExceptionUtil;
import com.alibaba.nacos.common.utils.ThreadUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Create a rest template to ensure that each custom client config and rest template are in one-to-one correspondence.
@ -30,11 +34,24 @@ import java.util.Map;
*/
public final class HttpClientBeanHolder {
private static final Logger LOGGER = LoggerFactory.getLogger(HttpClientBeanHolder.class);
private static final Map<String, NacosRestTemplate> SINGLETON_REST = new HashMap<String, NacosRestTemplate>(10);
private static final Map<String, NacosAsyncRestTemplate> SINGLETON_ASYNC_REST = new HashMap<String, NacosAsyncRestTemplate>(
10);
private static final AtomicBoolean ALREADY_SHUTDOWN = new AtomicBoolean(false);
static {
ThreadUtils.addShutdownHook(new Runnable() {
@Override
public void run() {
shutdown();
}
});
}
public static NacosRestTemplate getNacosRestTemplate(Logger logger) {
return getNacosRestTemplate(new DefaultHttpClientFactory(logger));
}
@ -81,6 +98,22 @@ public final class HttpClientBeanHolder {
return nacosAsyncRestTemplate;
}
/**
* Shutdown common http client.
*/
private static void shutdown() {
if (!ALREADY_SHUTDOWN.compareAndSet(false, true)) {
return;
}
LOGGER.warn("[HttpClientBeanHolder] Start destroying common HttpClient");
try {
shutdown(DefaultHttpClientFactory.class.getName());
} catch (Exception ex) {
LOGGER.error("An exception occurred when the common HTTP client was closed : {}", ExceptionUtil.getStackTrace(ex));
}
LOGGER.warn("[HttpClientBeanHolder] Destruction of the end");
}
/**
* Shutdown http client holder and close remove template.
*

View File

@ -65,13 +65,24 @@ public class HttpClientConfig {
*/
private final int maxConnPerRoute;
/**
* is HTTP compression enabled.
*/
private final boolean contentCompressionEnabled;
/**
* io thread count.
*/
private final int ioThreadCount;
/**
* user agent.
*/
private final String userAgent;
public HttpClientConfig(int conTimeOutMillis, int readTimeOutMillis, long connTimeToLive, TimeUnit timeUnit,
int connectionRequestTimeout, int maxRedirects, int maxConnTotal, int maxConnPerRoute, String userAgent) {
int connectionRequestTimeout, int maxRedirects, int maxConnTotal, int maxConnPerRoute,
boolean contentCompressionEnabled, int ioThreadCount, String userAgent) {
this.conTimeOutMillis = conTimeOutMillis;
this.readTimeOutMillis = readTimeOutMillis;
this.connTimeToLive = connTimeToLive;
@ -80,6 +91,8 @@ public class HttpClientConfig {
this.maxRedirects = maxRedirects;
this.maxConnTotal = maxConnTotal;
this.maxConnPerRoute = maxConnPerRoute;
this.contentCompressionEnabled = contentCompressionEnabled;
this.ioThreadCount = ioThreadCount;
this.userAgent = userAgent;
}
@ -115,6 +128,14 @@ public class HttpClientConfig {
return maxConnPerRoute;
}
public boolean getContentCompressionEnabled() {
return contentCompressionEnabled;
}
public int getIoThreadCount() {
return ioThreadCount;
}
public String getUserAgent() {
return userAgent;
}
@ -141,6 +162,10 @@ public class HttpClientConfig {
private int maxConnPerRoute = 0;
private boolean contentCompressionEnabled = true;
private int ioThreadCount = Runtime.getRuntime().availableProcessors();
private String userAgent;
public HttpClientConfigBuilder setConTimeOutMillis(int conTimeOutMillis) {
@ -158,7 +183,7 @@ public class HttpClientConfig {
this.connTimeToLiveTimeUnit = connTimeToLiveTimeUnit;
return this;
}
public HttpClientConfigBuilder setConnectionRequestTimeout(int connectionRequestTimeout) {
this.connectionRequestTimeout = connectionRequestTimeout;
return this;
@ -179,14 +204,30 @@ public class HttpClientConfig {
return this;
}
public HttpClientConfigBuilder setContentCompressionEnabled(boolean contentCompressionEnabled) {
this.contentCompressionEnabled = contentCompressionEnabled;
return this;
}
public HttpClientConfigBuilder setIoThreadCount(int ioThreadCount) {
this.ioThreadCount = ioThreadCount;
return this;
}
public HttpClientConfigBuilder setUserAgent(String userAgent) {
this.userAgent = userAgent;
return this;
}
/**
* build http client config.
*
* @return HttpClientConfig
*/
public HttpClientConfig build() {
return new HttpClientConfig(conTimeOutMillis, readTimeOutMillis, connTimeToLive, connTimeToLiveTimeUnit,
connectionRequestTimeout, maxRedirects, maxConnTotal, maxConnPerRoute, userAgent);
connectionRequestTimeout, maxRedirects, maxConnTotal, maxConnPerRoute, contentCompressionEnabled,
ioThreadCount, userAgent);
}
}
}

View File

@ -27,12 +27,14 @@ import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicNameValuePair;
import java.io.UnsupportedEncodingException;
import java.net.SocketTimeoutException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLDecoder;
@ -42,6 +44,7 @@ import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeoutException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@ -58,7 +61,7 @@ public final class HttpUtils {
* Init http header.
*
* @param requestBase requestBase {@link HttpRequestBase}
* @param header header
* @param header header
*/
public static void initRequestHeader(HttpRequestBase requestBase, Header header) {
Iterator<Map.Entry<String, String>> iterator = header.iterator();
@ -72,8 +75,8 @@ public final class HttpUtils {
* Init http entity.
*
* @param requestBase requestBase {@link HttpRequestBase}
* @param body body
* @param header request header
* @param body body
* @param header request header
* @throws Exception exception
*/
public static void initRequestEntity(HttpRequestBase requestBase, Object body, Header header) throws Exception {
@ -88,7 +91,8 @@ public final class HttpUtils {
if (body instanceof byte[]) {
entity = new ByteArrayEntity((byte[]) body, contentType);
} else {
entity = new StringEntity(body instanceof String ? (String) body : JacksonUtils.toJson(body), contentType);
entity = new StringEntity(body instanceof String ? (String) body : JacksonUtils.toJson(body),
contentType);
}
request.setEntity(entity);
}
@ -98,11 +102,12 @@ public final class HttpUtils {
* Init request from entity map.
*
* @param requestBase requestBase {@link HttpRequestBase}
* @param body body map
* @param charset charset of entity
* @param body body map
* @param charset charset of entity
* @throws Exception exception
*/
public static void initRequestFromEntity(HttpRequestBase requestBase, Map<String, String> body, String charset) throws Exception {
public static void initRequestFromEntity(HttpRequestBase requestBase, Map<String, String> body, String charset)
throws Exception {
if (body == null || body.isEmpty()) {
return;
}
@ -244,6 +249,17 @@ public final class HttpUtils {
return new URI(url);
}
/**
* HTTP request exception is a timeout exception.
*
* @param throwable http request throwable
* @return boolean
*/
public static boolean isTimeoutException(Throwable throwable) {
return throwable instanceof SocketTimeoutException || throwable instanceof ConnectTimeoutException
|| throwable instanceof TimeoutException || throwable.getCause() instanceof TimeoutException;
}
private static String innerDecode(String pre, String now, String encode) throws UnsupportedEncodingException {
// Because the data may be encoded by the URL more than once,
// it needs to be decoded recursively until it is fully successful
@ -254,4 +270,5 @@ public final class HttpUtils {
now = URLDecoder.decode(now, encode);
return innerDecode(pre, now, encode);
}
}

View File

@ -17,9 +17,9 @@
package com.alibaba.nacos.common.notify;
import com.alibaba.nacos.common.notify.listener.Subscriber;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.alibaba.nacos.common.utils.ConcurrentHashSet;
import com.alibaba.nacos.common.utils.ThreadUtils;
import com.alibaba.nacos.common.utils.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

View File

@ -71,4 +71,5 @@ public interface EventPublisher extends Closeable {
* @param event {@link Event}
*/
void notifySubscriber(Subscriber subscriber, Event event);
}
}

View File

@ -171,7 +171,6 @@ public class NotifyCenter {
* @param <T> event type
*/
public static <T> void registerSubscriber(final Subscriber consumer) {
final Class<? extends Event> cls = consumer.subscribeType();
// If you want to listen to multiple events, you do it separately,
// based on subclass's subscribeTypes method return list, it can register to publisher.
if (consumer instanceof SmartSubscriber) {
@ -187,16 +186,17 @@ public class NotifyCenter {
return;
}
if (ClassUtils.isAssignableFrom(SlowEvent.class, cls)) {
INSTANCE.sharePublisher.addSubscriber(consumer, cls);
final Class<? extends Event> subscribeType = consumer.subscribeType();
if (ClassUtils.isAssignableFrom(SlowEvent.class, subscribeType)) {
INSTANCE.sharePublisher.addSubscriber(consumer, subscribeType);
return;
}
addSubscriber(consumer, consumer.subscribeType());
addSubscriber(consumer, subscribeType);
}
/**
* Add a subscriber to pusblisher.
* Add a subscriber to publisher.
*
* @param consumer subscriber instance.
* @param subscribeType subscribeType.
@ -218,7 +218,6 @@ public class NotifyCenter {
* @param consumer subscriber instance.
*/
public static <T> void deregisterSubscriber(final Subscriber consumer) {
final Class<? extends Event> cls = consumer.subscribeType();
if (consumer instanceof SmartSubscriber) {
for (Class<? extends Event> subscribeType : ((SmartSubscriber) consumer).subscribeTypes()) {
if (ClassUtils.isAssignableFrom(SlowEvent.class, subscribeType)) {
@ -230,15 +229,16 @@ public class NotifyCenter {
return;
}
if (ClassUtils.isAssignableFrom(SlowEvent.class, cls)) {
INSTANCE.sharePublisher.removeSubscriber(consumer, cls);
final Class<? extends Event> subscribeType = consumer.subscribeType();
if (ClassUtils.isAssignableFrom(SlowEvent.class, subscribeType)) {
INSTANCE.sharePublisher.removeSubscriber(consumer, subscribeType);
return;
}
if (removeSubscriber(consumer, consumer.subscribeType())) {
if (removeSubscriber(consumer, subscribeType)) {
return;
}
throw new NoSuchElementException("The subcriber has no event publisher");
throw new NoSuchElementException("The subscriber has no event publisher");
}
/**
@ -251,12 +251,11 @@ public class NotifyCenter {
private static boolean removeSubscriber(final Subscriber consumer, Class<? extends Event> subscribeType) {
final String topic = ClassUtils.getCanonicalName(subscribeType);
if (INSTANCE.publisherMap.containsKey(topic)) {
EventPublisher publisher = INSTANCE.publisherMap.get(topic);
publisher.removeSubscriber(consumer);
EventPublisher eventPublisher = INSTANCE.publisherMap.get(topic);
if (eventPublisher != null) {
eventPublisher.removeSubscriber(consumer);
return true;
}
return false;
}
@ -282,16 +281,16 @@ public class NotifyCenter {
* @param event event instance.
*/
private static boolean publishEvent(final Class<? extends Event> eventType, final Event event) {
final String topic = ClassUtils.getCanonicalName(eventType);
if (ClassUtils.isAssignableFrom(SlowEvent.class, eventType)) {
return INSTANCE.sharePublisher.publish(event);
}
if (INSTANCE.publisherMap.containsKey(topic)) {
EventPublisher publisher = INSTANCE.publisherMap.get(topic);
final String topic = ClassUtils.getCanonicalName(eventType);
EventPublisher publisher = INSTANCE.publisherMap.get(topic);
if (publisher != null) {
return publisher.publish(event);
}
LOGGER.warn("There are no [{}] publishers for this event, please register", topic);
return false;
}
@ -322,8 +321,7 @@ public class NotifyCenter {
// MapUtils.computeIfAbsent is a unsafe method.
MapUtil.computeIfAbsent(INSTANCE.publisherMap, topic, publisherFactory, eventType, queueMaxSize);
}
EventPublisher publisher = INSTANCE.publisherMap.get(topic);
return publisher;
return INSTANCE.publisherMap.get(topic);
}
/**

View File

@ -16,7 +16,7 @@
package com.alibaba.nacos.common.tls;
import com.alibaba.nacos.common.utils.IpUtils;
import com.alibaba.nacos.common.utils.IPUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -38,7 +38,7 @@ public final class SelfHostnameVerifier implements HostnameVerifier {
private static ConcurrentHashMap<String, Boolean> hosts = new ConcurrentHashMap<String, Boolean>();
private static final String[] LOCALHOST_HOSTNAME = new String[] {"localhost", "127.0.0.1"};
private static final String[] LOCALHOST_HOSTNAME = new String[] {"localhost", IPUtil.localHostIP()};
public SelfHostnameVerifier(HostnameVerifier hv) {
this.hv = hv;
@ -49,22 +49,22 @@ public final class SelfHostnameVerifier implements HostnameVerifier {
if (LOCALHOST_HOSTNAME[0].equalsIgnoreCase(hostname) || LOCALHOST_HOSTNAME[1].equals(hostname)) {
return true;
}
if (isIpv4(hostname)) {
if (isIP(hostname)) {
return true;
}
return hv.verify(hostname, session);
}
private static boolean isIpv4(String host) {
private static boolean isIP(String host) {
if (host == null || host.isEmpty()) {
LOGGER.warn("host is empty, isIPv4 = false");
LOGGER.warn("host is empty, isIP = false");
return false;
}
Boolean cacheHostVerify = hosts.get(host);
if (cacheHostVerify != null) {
return cacheHostVerify;
}
boolean isIp = IpUtils.isIpv4(host);
boolean isIp = IPUtil.isIP(host);
hosts.putIfAbsent(host, isIp);
return isIp;
}

View File

@ -0,0 +1,222 @@
/*
* 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.utils;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* ip tool.
*
* @author Nacos
*/
@SuppressWarnings({"checkstyle:AbbreviationAsWordInName", "PMD.ClassNamingShouldBeCamelRule"})
public class IPUtil {
public static final boolean PREFER_IPV6_ADDRESSES = Boolean.parseBoolean(System.getProperty("java.net.preferIPv6Addresses"));
public static final String IPV6_START_MARK = "[";
public static final String IPV6_END_MARK = "]";
public static final String ILLEGAL_IP_PREFIX = "illegal ip: ";
public static final String IP_PORT_SPLITER = ":";
public static final int SPLIT_IP_PORT_RESULT_LENGTH = 2;
public static final String PERCENT_SIGN_IN_IPV6 = "%";
private static final String LOCAL_HOST_IP_V4 = "127.0.0.1";
private static final String LOCAL_HOST_IP_V6 = "[::1]";
private static Pattern ipv4Pattern = Pattern.compile("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}");
private static final int IPV4_ADDRESS_LENGTH = 4;
private static final int IPV6_ADDRESS_LENGTH = 16;
private static final String CHECK_OK = "ok";
/**
* get localhost ip.
* @return java.lang.String
*/
public static String localHostIP() {
if (PREFER_IPV6_ADDRESSES) {
return LOCAL_HOST_IP_V6;
}
return LOCAL_HOST_IP_V4;
}
/**
* check whether the ip address is IPv4.
*
* @param addr ip address
* @return boolean
*/
public static boolean isIPv4(String addr) {
try {
return InetAddress.getByName(addr).getAddress().length == IPV4_ADDRESS_LENGTH;
} catch (UnknownHostException e) {
return false;
}
}
/**
* check whether the ip address is IPv6.
*
* @param addr ip address
* @return boolean
*/
public static boolean isIPv6(String addr) {
try {
return InetAddress.getByName(addr).getAddress().length == IPV6_ADDRESS_LENGTH;
} catch (UnknownHostException e) {
return false;
}
}
/**
* check whether the str is ip address (IPv4 or IPv6).
*
* @param addr ip address str
* @return boolean
*/
public static boolean isIP(String addr) {
try {
InetAddress.getByName(addr);
return true;
} catch (UnknownHostException e) {
return false;
}
}
/**
* Check if the address contains a port.
* 2020/9/3 14:53
* @param address address string
* @return boolean
*/
public static boolean containsPort(String address) {
return splitIPPortStr(address).length == SPLIT_IP_PORT_RESULT_LENGTH;
}
/**
* Split IP and port strings, support IPv4 and IPv6, IP in IPv6 must be enclosed with [].
*
* @param str ip and port string
* @return java.lang.String[]
*/
public static String[] splitIPPortStr(String str) {
if (StringUtils.isBlank(str)) {
throw new IllegalArgumentException("ip and port string cannot be empty!");
}
String[] serverAddrArr;
if (str.startsWith(IPV6_START_MARK) && StringUtils.containsIgnoreCase(str, IPV6_END_MARK)) {
if (str.endsWith(IPV6_END_MARK)) {
serverAddrArr = new String[1];
serverAddrArr[0] = str;
} else {
serverAddrArr = new String[2];
serverAddrArr[0] = str.substring(0, (str.indexOf(IPV6_END_MARK) + 1));
serverAddrArr[1] = str.substring((str.indexOf(IPV6_END_MARK) + 2));
}
if (!isIPv6(serverAddrArr[0])) {
throw new IllegalArgumentException("The IPv6 address(\"" + serverAddrArr[0] + "\") is incorrect.");
}
} else {
serverAddrArr = str.split(":");
if (serverAddrArr.length > SPLIT_IP_PORT_RESULT_LENGTH) {
throw new IllegalArgumentException("The IP address(\"" + str
+ "\") is incorrect. If it is an IPv6 address, please use [] to enclose the IP part!");
}
if (!isIPv4(serverAddrArr[0])) {
throw new IllegalArgumentException("The IPv4 address(\"" + serverAddrArr[0] + "\") is incorrect.");
}
}
return serverAddrArr;
}
/**
* Resolve the IP from the string containing the IP address.
* @param str string containing IP address
* @return java.lang.String
*/
public static String getIPFromString(String str) {
if (StringUtils.isBlank(str)) {
return "";
}
String result = "";
if (StringUtils.containsIgnoreCase(str, IPV6_START_MARK) && StringUtils.containsIgnoreCase(str, IPV6_END_MARK)) {
result = str.substring(str.indexOf(IPV6_START_MARK), (str.indexOf(IPV6_END_MARK) + 1));
if (!isIPv6(result)) {
result = "";
}
} else {
Matcher m = ipv4Pattern.matcher(str);
if (m.find()) {
result = m.group();
if (!isIPv4(result)) {
result = "";
}
}
}
return result;
}
/**
* Check ips.
*
* @param ips ips
* @return 'ok' if check passed, otherwise illegal ip
*/
public static String checkIPs(String... ips) {
if (ips == null || ips.length == 0) {
return CHECK_OK;
}
// illegal response
StringBuilder illegalResponse = new StringBuilder();
for (String ip : ips) {
if (IPUtil.isIP(ip)) {
continue;
}
illegalResponse.append(ip + ",");
}
if (illegalResponse.length() == 0) {
return CHECK_OK;
}
return ILLEGAL_IP_PREFIX + illegalResponse.substring(0, illegalResponse.length() - 1);
}
/**
* Check whether checkIPs result is "ok".
* @param checkIPsResult checkIPs result
* @return boolean
*/
public static boolean checkOK(String checkIPsResult) {
return CHECK_OK.equals(checkIPsResult);
}
}

View File

@ -1,49 +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.utils;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* ip tool.
*
* @author Nacos
*/
public class IpUtils {
private static final Pattern IPV4_PATTERN = Pattern
.compile("^((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)$");
private static final Pattern IPV6_PATTERN = Pattern.compile("^([\\da-fA-F]{1,4}:){7}[\\da-fA-F]{1,4}$");
public static boolean isIpv4(String addr) {
return isMatch(addr, IPV4_PATTERN);
}
public static boolean isIpv6(String addr) {
return isMatch(addr, IPV6_PATTERN);
}
private static boolean isMatch(String data, Pattern pattern) {
if (StringUtils.isBlank(data)) {
return false;
}
Matcher mat = pattern.matcher(data);
return mat.find();
}
}

View File

@ -0,0 +1,120 @@
/*
* 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.utils;
import org.junit.Assert;
import org.junit.Test;
/**
* test IpUtil.
* @ClassName: IpUtilTest
* @date 2020/9/3 10:31
*/
@SuppressWarnings("checkstyle:AbbreviationAsWordInName")
public class IPUtilTest {
@Test
public void testIsIPv4() {
Assert.assertTrue(IPUtil.isIPv4("127.0.0.1"));
Assert.assertFalse(IPUtil.isIPv4("[::1]"));
Assert.assertFalse(IPUtil.isIPv4("asdfasf"));
Assert.assertFalse(IPUtil.isIPv4("ffgertert"));
}
@Test
public void testIsIPv6() {
Assert.assertTrue(IPUtil.isIPv6("[::1]"));
Assert.assertFalse(IPUtil.isIPv6("127.0.0.1"));
Assert.assertFalse(IPUtil.isIPv6("er34234"));
}
@Test
public void testIsIP() {
Assert.assertTrue(IPUtil.isIP("[::1]"));
Assert.assertTrue(IPUtil.isIP("127.0.0.1"));
Assert.assertFalse(IPUtil.isIP("er34234"));
}
@Test
public void testGetIPFromString() {
Assert.assertEquals("[::1]", IPUtil.getIPFromString("http://[::1]:666/xzdsfasdf/awerwef" + "?eewer=2&xxx=3"));
Assert.assertEquals("[::1]", IPUtil.getIPFromString(
"jdbc:mysql://[::1]:3306/nacos_config_test?characterEncoding=utf8&connectTimeout=1000"
+ "&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC"));
Assert.assertEquals("127.0.0.1",
IPUtil.getIPFromString("http://127.0.0.1:666/xzdsfasdf/awerwef" + "?eewer=2&xxx=3"));
Assert.assertEquals("127.0.0.1", IPUtil.getIPFromString(
"jdbc:mysql://127.0.0.1:3306/nacos_config_test?characterEncoding=utf8&connectTimeout=1000"
+ "&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC"));
Assert.assertEquals("",
IPUtil.getIPFromString("http://[dddd]:666/xzdsfasdf/awerwef" + "?eewer=2&xxx=3"));
Assert.assertEquals("", IPUtil.getIPFromString(
"jdbc:mysql://[127.0.0.1]:3306/nacos_config_test?characterEncoding=utf8&connectTimeout=1000"
+ "&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC"));
Assert.assertEquals("", IPUtil.getIPFromString(
"jdbc:mysql://666.288.333.444:3306/nacos_config_test?characterEncoding=utf8&connectTimeout=1000"
+ "&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC"));
}
@Test
public void testSplitIpPort() {
checkSplitIPPortStr("[::1]:88", false, "[::1]", "88");
checkSplitIPPortStr("[::1]", false, "[::1]");
checkSplitIPPortStr("127.0.0.1:88", false, "127.0.0.1", "88");
checkSplitIPPortStr("127.0.0.1", false, "127.0.0.1");
checkSplitIPPortStr("[2001:db8:0:0:1:0:0:1]:88", false, "[2001:db8:0:0:1:0:0:1]", "88");
checkSplitIPPortStr("[2001:0db8:0:0:1:0:0:1]:88", false, "[2001:0db8:0:0:1:0:0:1]", "88");
checkSplitIPPortStr("[2001:db8::1:0:0:1]:88", false, "[2001:db8::1:0:0:1]", "88");
checkSplitIPPortStr("[2001:db8::0:1:0:0:1]:88", false, "[2001:db8::0:1:0:0:1]", "88");
checkSplitIPPortStr("[2001:0db8::1:0:0:1]:88", false, "[2001:0db8::1:0:0:1]", "88");
checkSplitIPPortStr("[2001:db8:0:0:1::1]:88", false, "[2001:db8:0:0:1::1]", "88");
checkSplitIPPortStr("[2001:db8:0000:0:1::1]:88", false, "[2001:db8:0000:0:1::1]", "88");
checkSplitIPPortStr("[2001:DB8:0:0:1::1]:88", false, "[2001:DB8:0:0:1::1]", "88");
checkSplitIPPortStr("[fe80::3ce6:7132:808e:707a%19]:88", false, "[fe80::3ce6:7132:808e:707a%19]", "88");
checkSplitIPPortStr("::1:88", true);
checkSplitIPPortStr("[::1:88", true);
checkSplitIPPortStr("[127.0.0.1]:88", true);
}
/**
* checkSplitIpPortStr.
* 2020/9/4 14:12
* @param addr addr
* @param isEx isEx
* @param equalsStrs equalsStrs
*/
public static void checkSplitIPPortStr(String addr, boolean isEx, String... equalsStrs) {
try {
String[] array = IPUtil.splitIPPortStr(addr);
Assert.assertTrue(array.length == equalsStrs.length);
if (array.length > 1) {
Assert.assertTrue(array[0].equals(equalsStrs[0]));
Assert.assertTrue(array[1].equals(equalsStrs[1]));
} else {
Assert.assertTrue(array[0].equals(equalsStrs[0]));
}
} catch (Exception ex) {
if (!isEx) {
// No exception is expected here, but an exception has occurred
Assert.assertTrue("Unexpected exception", false);
}
}
}
}

View File

@ -65,10 +65,6 @@
<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>

View File

@ -18,9 +18,9 @@ package com.alibaba.nacos.config.server.auth;
import com.alibaba.nacos.config.server.configuration.ConditionOnEmbeddedStorage;
import com.alibaba.nacos.config.server.model.Page;
import com.alibaba.nacos.config.server.service.repository.embedded.EmbeddedStoragePersistServiceImpl;
import com.alibaba.nacos.config.server.service.repository.PaginationHelper;
import com.alibaba.nacos.config.server.service.repository.embedded.DatabaseOperate;
import com.alibaba.nacos.config.server.service.repository.embedded.EmbeddedStoragePersistServiceImpl;
import com.alibaba.nacos.config.server.service.sql.EmbeddedStorageContextUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
@ -28,6 +28,8 @@ import org.springframework.context.annotation.Conditional;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static com.alibaba.nacos.config.server.service.repository.RowMapperManager.PERMISSION_ROW_MAPPER;
@ -51,15 +53,17 @@ public class EmbeddedPermissionPersistServiceImpl implements PermissionPersistSe
String sqlCountRows = "select count(*) from permissions where ";
String sqlFetchRows = "select role,resource,action from permissions where ";
String where = " role='" + role + "' ";
if (StringUtils.isBlank(role)) {
String where = " role= ? ";
List<String> params = new ArrayList<>();
if (StringUtils.isNotBlank(role)) {
params = Collections.singletonList(role);
} else {
where = " 1=1 ";
}
Page<PermissionInfo> pageInfo = helper
.fetchPage(sqlCountRows + where, sqlFetchRows + where, new ArrayList<String>().toArray(), pageNo,
.fetchPage(sqlCountRows + where, sqlFetchRows + where, params.toArray(), pageNo,
pageSize, PERMISSION_ROW_MAPPER);
if (pageInfo == null) {

View File

@ -18,9 +18,9 @@ package com.alibaba.nacos.config.server.auth;
import com.alibaba.nacos.config.server.configuration.ConditionOnEmbeddedStorage;
import com.alibaba.nacos.config.server.model.Page;
import com.alibaba.nacos.config.server.service.repository.embedded.EmbeddedStoragePersistServiceImpl;
import com.alibaba.nacos.config.server.service.repository.PaginationHelper;
import com.alibaba.nacos.config.server.service.repository.embedded.DatabaseOperate;
import com.alibaba.nacos.config.server.service.repository.embedded.EmbeddedStoragePersistServiceImpl;
import com.alibaba.nacos.config.server.service.sql.EmbeddedStorageContextUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
@ -28,6 +28,7 @@ import org.springframework.context.annotation.Conditional;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static com.alibaba.nacos.config.server.service.repository.RowMapperManager.ROLE_INFO_ROW_MAPPER;
@ -74,14 +75,16 @@ public class EmbeddedRolePersistServiceImpl implements RolePersistService {
String sqlCountRows = "select count(*) from roles where ";
String sqlFetchRows = "select role,username from roles where ";
String where = " username='" + username + "' ";
if (StringUtils.isBlank(username)) {
String where = " username= ? ";
List<String> params = new ArrayList<>();
if (StringUtils.isNotBlank(username)) {
params = Collections.singletonList(username);
} else {
where = " 1=1 ";
}
return helper.fetchPage(sqlCountRows + where, sqlFetchRows + where, new ArrayList<String>().toArray(), pageNo,
return helper.fetchPage(sqlCountRows + where, sqlFetchRows + where, params.toArray(), pageNo,
pageSize, ROLE_INFO_ROW_MAPPER);
}

View File

@ -18,8 +18,8 @@ package com.alibaba.nacos.config.server.auth;
import com.alibaba.nacos.config.server.configuration.ConditionOnExternalStorage;
import com.alibaba.nacos.config.server.model.Page;
import com.alibaba.nacos.config.server.service.repository.extrnal.ExternalStoragePersistServiceImpl;
import com.alibaba.nacos.config.server.service.repository.PaginationHelper;
import com.alibaba.nacos.config.server.service.repository.extrnal.ExternalStoragePersistServiceImpl;
import com.alibaba.nacos.config.server.utils.LogUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
@ -30,6 +30,8 @@ import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static com.alibaba.nacos.config.server.service.repository.RowMapperManager.PERMISSION_ROW_MAPPER;
@ -57,16 +59,18 @@ public class ExternalPermissionPersistServiceImpl implements PermissionPersistSe
String sqlCountRows = "select count(*) from permissions where ";
String sqlFetchRows = "select role,resource,action from permissions where ";
String where = " role='" + role + "' ";
if (StringUtils.isBlank(role)) {
String where = " role= ? ";
List<String> params = new ArrayList<>();
if (StringUtils.isNotBlank(role)) {
params = Collections.singletonList(role);
} else {
where = " 1=1 ";
}
try {
Page<PermissionInfo> pageInfo = helper
.fetchPage(sqlCountRows + where, sqlFetchRows + where, new ArrayList<String>().toArray(), pageNo,
.fetchPage(sqlCountRows + where, sqlFetchRows + where, params.toArray(), pageNo,
pageSize, PERMISSION_ROW_MAPPER);
if (pageInfo == null) {

View File

@ -18,8 +18,8 @@ package com.alibaba.nacos.config.server.auth;
import com.alibaba.nacos.config.server.configuration.ConditionOnExternalStorage;
import com.alibaba.nacos.config.server.model.Page;
import com.alibaba.nacos.config.server.service.repository.extrnal.ExternalStoragePersistServiceImpl;
import com.alibaba.nacos.config.server.service.repository.PaginationHelper;
import com.alibaba.nacos.config.server.service.repository.extrnal.ExternalStoragePersistServiceImpl;
import com.alibaba.nacos.config.server.utils.LogUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
@ -33,6 +33,7 @@ import javax.annotation.PostConstruct;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static com.alibaba.nacos.config.server.service.repository.RowMapperManager.ROLE_INFO_ROW_MAPPER;
@ -88,16 +89,17 @@ public class ExternalRolePersistServiceImpl implements RolePersistService {
String sqlCountRows = "select count(*) from roles where ";
String sqlFetchRows = "select role,username from roles where ";
String where = " username='" + username + "' ";
if (StringUtils.isBlank(username)) {
String where = " username= ? ";
List<String> params = new ArrayList<>();
if (StringUtils.isNotBlank(username)) {
params = Collections.singletonList(username);
} else {
where = " 1=1 ";
}
try {
return helper
.fetchPage(sqlCountRows + where, sqlFetchRows + where, new ArrayList<String>().toArray(), pageNo,
pageSize, ROLE_INFO_ROW_MAPPER);
return helper.fetchPage(sqlCountRows + where, sqlFetchRows + where, params.toArray(), pageNo, pageSize,
ROLE_INFO_ROW_MAPPER);
} catch (CannotGetJdbcConnectionException e) {
LogUtil.FATAL_LOG.error("[db-error] " + e.toString(), e);
throw e;
@ -107,7 +109,7 @@ public class ExternalRolePersistServiceImpl implements RolePersistService {
/**
* Execute add role operation.
*
* @param role role string value.
* @param role role string value.
* @param userName username string value.
*/
public void addRole(String role, String userName) {
@ -140,7 +142,7 @@ public class ExternalRolePersistServiceImpl implements RolePersistService {
/**
* Execute delete role operation.
*
* @param role role string value.
* @param role role string value.
* @param username username string value.
*/
public void deleteRole(String role, String username) {
@ -156,7 +158,7 @@ public class ExternalRolePersistServiceImpl implements RolePersistService {
@Override
public List<String> findRolesLikeRoleName(String role) {
String sql = "SELECT role FROM roles WHERE role like '%' ? '%'";
List<String> users = this.jt.queryForList(sql, new String[]{role}, String.class);
List<String> users = this.jt.queryForList(sql, new String[] {role}, String.class);
return users;
}

View File

@ -16,6 +16,7 @@
package com.alibaba.nacos.config.server.controller;
import com.alibaba.nacos.api.config.ConfigType;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.auth.annotation.Secured;
import com.alibaba.nacos.auth.common.ActionTypes;
@ -134,6 +135,10 @@ public class ConfigController {
final String srcIp = RequestUtil.getRemoteIp(request);
final String requestIpApp = RequestUtil.getAppName(request);
srcUser = RequestUtil.getSrcUserName(request);
//check type
if (!ConfigType.isValidType(type)) {
type = ConfigType.getDefaultType().getType();
}
// check tenant
ParamUtils.checkTenant(tenant);
ParamUtils.checkParam(dataId, group, "datumId", content);

View File

@ -0,0 +1,84 @@
/*
* Copyright 1999-2020 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.server.service.datasource;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.boot.context.properties.bind.Bindable;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.core.env.Environment;
import java.util.concurrent.TimeUnit;
/**
* DataSource pool properties.
*
* <p>Nacos server use HikariCP as the datasource pool. So the basic pool properties will based on {@link
* com.zaxxer.hikari.HikariDataSource}.
*
* @author xiweng.yy
*/
public class DataSourcePoolProperties {
public static final long DEFAULT_CONNECTION_TIMEOUT = TimeUnit.SECONDS.toMillis(30L);
public static final long DEFAULT_VALIDATION_TIMEOUT = TimeUnit.SECONDS.toMillis(10L);
public static final int DEFAULT_MAX_POOL_SIZE = 20;
public static final int DEFAULT_MINIMUM_IDLE = 2;
private final HikariDataSource dataSource;
private DataSourcePoolProperties() {
dataSource = new HikariDataSource();
dataSource.setConnectionTimeout(DEFAULT_CONNECTION_TIMEOUT);
dataSource.setValidationTimeout(DEFAULT_VALIDATION_TIMEOUT);
dataSource.setMaximumPoolSize(DEFAULT_MAX_POOL_SIZE);
dataSource.setMinimumIdle(DEFAULT_MINIMUM_IDLE);
}
/**
* Build new Hikari config.
*
* @return new hikari config
*/
public static DataSourcePoolProperties build(Environment environment) {
DataSourcePoolProperties result = new DataSourcePoolProperties();
Binder.get(environment).bind("db.pool.config", Bindable.ofInstance(result.getDataSource()));
return result;
}
public void setDriverClassName(final String driverClassName) {
dataSource.setDriverClassName(driverClassName);
}
public void setJdbcUrl(final String jdbcUrl) {
dataSource.setJdbcUrl(jdbcUrl);
}
public void setUsername(final String username) {
dataSource.setUsername(username);
}
public void setPassword(final String password) {
dataSource.setPassword(password);
}
public HikariDataSource getDataSource() {
return dataSource;
}
}

View File

@ -13,20 +13,18 @@
package com.alibaba.nacos.config.server.service.datasource;
import static com.alibaba.nacos.common.utils.CollectionUtils.getOrDefault;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import com.google.common.base.Preconditions;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.boot.context.properties.bind.Bindable;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.core.env.Environment;
import com.google.common.base.Preconditions;
import com.zaxxer.hikari.HikariDataSource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import static com.alibaba.nacos.common.utils.CollectionUtils.getOrDefault;
/**
* Properties of external DataSource.
@ -37,15 +35,7 @@ public class ExternalDataSourceProperties {
private static final String JDBC_DRIVER_NAME = "com.mysql.cj.jdbc.Driver";
public static final long CONNECTION_TIMEOUT_MS = 3000L;
public static final long VALIDATION_TIMEOUT = 10L;
public static final String TEST_QUERY = "SELECT 1 FROM dual";
public static final int DEFAULT_MAX_POOL_SIZE = 20;
public static final int DEFAULT_MINIMUM_IDLE = 20;
private static final String TEST_QUERY = "SELECT 1";
private Integer num;
@ -55,10 +45,6 @@ public class ExternalDataSourceProperties {
private List<String> password = new ArrayList<>();
private List<Integer> maxPoolSize = new ArrayList<>();
private List<Integer> minIdle = new ArrayList<>();
public void setNum(Integer num) {
this.num = num;
}
@ -75,14 +61,6 @@ public class ExternalDataSourceProperties {
this.password = password;
}
public void setMaxPoolSize(List<Integer> maxPoolSize) {
this.maxPoolSize = maxPoolSize;
}
public void setMinIdle(List<Integer> minIdle) {
this.minIdle = minIdle;
}
/**
* Build serveral HikariDataSource.
*
@ -99,16 +77,12 @@ public class ExternalDataSourceProperties {
for (int index = 0; index < num; index++) {
int currentSize = index + 1;
Preconditions.checkArgument(url.size() >= currentSize, "db.url.%s is null", index);
HikariDataSource ds = new HikariDataSource();
ds.setDriverClassName(JDBC_DRIVER_NAME);
ds.setJdbcUrl(url.get(index).trim());
ds.setUsername(getOrDefault(user, index, user.get(0)).trim());
ds.setPassword(getOrDefault(password, index, password.get(0)).trim());
ds.setConnectionTimeout(CONNECTION_TIMEOUT_MS);
ds.setMaximumPoolSize(getOrDefault(maxPoolSize, index, DEFAULT_MAX_POOL_SIZE));
ds.setMinimumIdle(getOrDefault(minIdle, index, DEFAULT_MINIMUM_IDLE));
// Check the connection pool every 10 minutes
ds.setValidationTimeout(TimeUnit.MINUTES.toMillis(VALIDATION_TIMEOUT));
DataSourcePoolProperties poolProperties = DataSourcePoolProperties.build(environment);
poolProperties.setDriverClassName(JDBC_DRIVER_NAME);
poolProperties.setJdbcUrl(url.get(index).trim());
poolProperties.setUsername(getOrDefault(user, index, user.get(0)).trim());
poolProperties.setPassword(getOrDefault(password, index, password.get(0)).trim());
HikariDataSource ds = poolProperties.getDataSource();
ds.setConnectionTestQuery(TEST_QUERY);
dataSources.add(ds);
callback.accept(ds);

View File

@ -16,34 +16,29 @@
package com.alibaba.nacos.config.server.service.datasource;
import static com.alibaba.nacos.config.server.service.repository.RowMapperManager.CONFIG_INFO4BETA_ROW_MAPPER;
import static com.alibaba.nacos.config.server.utils.LogUtil.DEFAULT_LOG;
import static com.alibaba.nacos.config.server.utils.LogUtil.FATAL_LOG;
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.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.CannotGetJdbcConnectionException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;
import com.alibaba.nacos.common.utils.ConvertUtils;
import com.alibaba.nacos.common.utils.IPUtil;
import com.alibaba.nacos.common.utils.StringUtils;
import com.alibaba.nacos.config.server.monitor.MetricsMonitor;
import com.alibaba.nacos.config.server.utils.ConfigExecutor;
import com.alibaba.nacos.config.server.utils.PropertyUtil;
import com.alibaba.nacos.sys.utils.ApplicationUtils;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.CannotGetJdbcConnectionException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;
import javax.sql.DataSource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static com.alibaba.nacos.config.server.service.repository.RowMapperManager.CONFIG_INFO4BETA_ROW_MAPPER;
import static com.alibaba.nacos.config.server.utils.LogUtil.DEFAULT_LOG;
import static com.alibaba.nacos.config.server.utils.LogUtil.FATAL_LOG;
/**
* Base data source.
@ -52,10 +47,6 @@ import com.zaxxer.hikari.HikariDataSource;
*/
public class ExternalDataSourceServiceImpl implements DataSourceService {
private static final Logger LOGGER = LoggerFactory.getLogger(ExternalDataSourceServiceImpl.class);
private static final String JDBC_DRIVER_NAME = "com.mysql.cj.jdbc.Driver";
/**
* JDBC execute timeout value, unit:second.
*/
@ -83,8 +74,6 @@ public class ExternalDataSourceServiceImpl implements DataSourceService {
private volatile int masterIndex;
private static Pattern ipPattern = Pattern.compile("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}");
@Override
public void init() {
queryTimeout = ConvertUtils.toInt(System.getProperty("QUERYTIMEOUT"), 3);
@ -190,10 +179,10 @@ public class ExternalDataSourceServiceImpl implements DataSourceService {
if (!isHealthList.get(i)) {
if (i == masterIndex) {
// The master is unhealthy.
return "DOWN:" + getIpFromUrl(dataSourceList.get(i).getJdbcUrl());
return "DOWN:" + IPUtil.getIPFromString(dataSourceList.get(i).getJdbcUrl());
} else {
// The slave is unhealthy.
return "WARN:" + getIpFromUrl(dataSourceList.get(i).getJdbcUrl());
return "WARN:" + IPUtil.getIPFromString(dataSourceList.get(i).getJdbcUrl());
}
}
}
@ -201,20 +190,6 @@ public class ExternalDataSourceServiceImpl implements DataSourceService {
return "UP";
}
private String getIpFromUrl(String url) {
Matcher m = ipPattern.matcher(url);
if (m.find()) {
return m.group();
}
return "";
}
static String defaultIfNull(String value, String defaultValue) {
return null == value ? defaultValue : value;
}
class SelectMasterTask implements Runnable {
@Override
@ -269,10 +244,10 @@ public class ExternalDataSourceServiceImpl implements DataSourceService {
} catch (DataAccessException e) {
if (i == masterIndex) {
FATAL_LOG.error("[db-error] master db {} down.",
getIpFromUrl(dataSourceList.get(i).getJdbcUrl()));
IPUtil.getIPFromString(dataSourceList.get(i).getJdbcUrl()));
} else {
FATAL_LOG.error("[db-error] slave db {} down.",
getIpFromUrl(dataSourceList.get(i).getJdbcUrl()));
IPUtil.getIPFromString(dataSourceList.get(i).getJdbcUrl()));
}
isHealthList.set(i, Boolean.FALSE);

View File

@ -24,7 +24,13 @@ import com.alibaba.nacos.config.server.utils.PropertyUtil;
import com.alibaba.nacos.sys.utils.ApplicationUtils;
import com.alibaba.nacos.sys.utils.DiskUtils;
import com.zaxxer.hikari.HikariDataSource;
import org.apache.commons.lang3.StringUtils;
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.File;
import java.io.FileInputStream;
import java.io.InputStream;
@ -36,13 +42,6 @@ import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.support.TransactionTemplate;
/**
* local data source.
@ -121,7 +120,7 @@ public class LocalDataSourceServiceImpl implements DataSourceService {
/**
* Restore derby.
*
* @param jdbcUrl jdbcUrl string value.
* @param jdbcUrl jdbcUrl string value.
* @param callable callable.
* @throws Exception exception.
*/
@ -145,14 +144,12 @@ public class LocalDataSourceServiceImpl implements DataSourceService {
}
private synchronized void initialize(String jdbcUrl) {
HikariDataSource ds = new HikariDataSource();
ds.setDriverClassName(jdbcDriverName);
ds.setJdbcUrl(jdbcUrl);
ds.setUsername(userName);
ds.setPassword(password);
ds.setIdleTimeout(30_000L);
ds.setMaximumPoolSize(80);
ds.setConnectionTimeout(10000L);
DataSourcePoolProperties poolProperties = DataSourcePoolProperties.build(ApplicationUtils.getEnvironment());
poolProperties.setDriverClassName(jdbcDriverName);
poolProperties.setJdbcUrl(jdbcUrl);
poolProperties.setUsername(userName);
poolProperties.setPassword(password);
HikariDataSource ds = poolProperties.getDataSource();
DataSourceTransactionManager tm = new DataSourceTransactionManager();
tm.setDataSource(ds);
if (jdbcTemplateInit) {

View File

@ -48,10 +48,10 @@ import com.alibaba.nacos.config.server.utils.LogUtil;
import com.alibaba.nacos.consistency.SerializeFactory;
import com.alibaba.nacos.consistency.Serializer;
import com.alibaba.nacos.consistency.cp.CPProtocol;
import com.alibaba.nacos.consistency.cp.LogProcessor4CP;
import com.alibaba.nacos.consistency.entity.GetRequest;
import com.alibaba.nacos.consistency.entity.Log;
import com.alibaba.nacos.consistency.cp.RequestProcessor4CP;
import com.alibaba.nacos.consistency.entity.ReadRequest;
import com.alibaba.nacos.consistency.entity.Response;
import com.alibaba.nacos.consistency.entity.WriteRequest;
import com.alibaba.nacos.consistency.exception.ConsistencyException;
import com.alibaba.nacos.consistency.snapshot.SnapshotOperation;
import com.alibaba.nacos.core.cluster.ServerMemberManager;
@ -142,7 +142,7 @@ import java.util.stream.Collectors;
@Conditional(ConditionDistributedEmbedStorage.class)
@Component
@SuppressWarnings({"unchecked"})
public class DistributedDatabaseOperateImpl extends LogProcessor4CP implements BaseDatabaseOperate {
public class DistributedDatabaseOperateImpl extends RequestProcessor4CP implements BaseDatabaseOperate {
/**
* The data import operation is dedicated key, which ACTS as an identifier.
@ -227,7 +227,7 @@ public class DistributedDatabaseOperateImpl extends LogProcessor4CP implements B
.containsExtendInfo(Constants.EXTEND_NEED_READ_UNTIL_HAVE_DATA);
Response response = innerRead(
GetRequest.newBuilder().setGroup(group()).setData(ByteString.copyFrom(data)).build(), blockRead);
ReadRequest.newBuilder().setGroup(group()).setData(ByteString.copyFrom(data)).build(), blockRead);
if (response.getSuccess()) {
return serializer.deserialize(response.getData().toByteArray(), cls);
}
@ -251,7 +251,7 @@ public class DistributedDatabaseOperateImpl extends LogProcessor4CP implements B
.containsExtendInfo(Constants.EXTEND_NEED_READ_UNTIL_HAVE_DATA);
Response response = innerRead(
GetRequest.newBuilder().setGroup(group()).setData(ByteString.copyFrom(data)).build(), blockRead);
ReadRequest.newBuilder().setGroup(group()).setData(ByteString.copyFrom(data)).build(), blockRead);
if (response.getSuccess()) {
return serializer.deserialize(response.getData().toByteArray(), cls);
}
@ -275,7 +275,7 @@ public class DistributedDatabaseOperateImpl extends LogProcessor4CP implements B
.containsExtendInfo(Constants.EXTEND_NEED_READ_UNTIL_HAVE_DATA);
Response response = innerRead(
GetRequest.newBuilder().setGroup(group()).setData(ByteString.copyFrom(data)).build(), blockRead);
ReadRequest.newBuilder().setGroup(group()).setData(ByteString.copyFrom(data)).build(), blockRead);
if (response.getSuccess()) {
return serializer.deserialize(response.getData().toByteArray(),
ClassUtils.resolveGenericTypeByInterface(mapper.getClass()));
@ -300,7 +300,7 @@ public class DistributedDatabaseOperateImpl extends LogProcessor4CP implements B
.containsExtendInfo(Constants.EXTEND_NEED_READ_UNTIL_HAVE_DATA);
Response response = innerRead(
GetRequest.newBuilder().setGroup(group()).setData(ByteString.copyFrom(data)).build(), blockRead);
ReadRequest.newBuilder().setGroup(group()).setData(ByteString.copyFrom(data)).build(), blockRead);
if (response.getSuccess()) {
return serializer.deserialize(response.getData().toByteArray(), List.class);
}
@ -324,7 +324,7 @@ public class DistributedDatabaseOperateImpl extends LogProcessor4CP implements B
.containsExtendInfo(Constants.EXTEND_NEED_READ_UNTIL_HAVE_DATA);
Response response = innerRead(
GetRequest.newBuilder().setGroup(group()).setData(ByteString.copyFrom(data)).build(), blockRead);
ReadRequest.newBuilder().setGroup(group()).setData(ByteString.copyFrom(data)).build(), blockRead);
if (response.getSuccess()) {
return serializer.deserialize(response.getData().toByteArray(), List.class);
}
@ -348,7 +348,7 @@ public class DistributedDatabaseOperateImpl extends LogProcessor4CP implements B
.containsExtendInfo(Constants.EXTEND_NEED_READ_UNTIL_HAVE_DATA);
Response response = innerRead(
GetRequest.newBuilder().setGroup(group()).setData(ByteString.copyFrom(data)).build(), blockRead);
ReadRequest.newBuilder().setGroup(group()).setData(ByteString.copyFrom(data)).build(), blockRead);
if (response.getSuccess()) {
return serializer.deserialize(response.getData().toByteArray(), List.class);
}
@ -362,12 +362,12 @@ public class DistributedDatabaseOperateImpl extends LogProcessor4CP implements B
/**
* In some business situations, you need to avoid the timeout issue, so blockRead is used to determine this.
*
* @param request {@link GetRequest}
* @param request {@link ReadRequest}
* @param blockRead is async read operation
* @return {@link Response}
* @throws Exception Exception
*/
private Response innerRead(GetRequest request, boolean blockRead) throws Exception {
private Response innerRead(ReadRequest request, boolean blockRead) throws Exception {
if (blockRead) {
return (Response) protocol.aGetData(request).join();
}
@ -390,7 +390,7 @@ public class DistributedDatabaseOperateImpl extends LogProcessor4CP implements B
if (submit) {
List<ModifyRequest> requests = batchUpdate.stream().map(ModifyRequest::new)
.collect(Collectors.toList());
CompletableFuture<Response> future = protocol.submitAsync(Log.newBuilder().setGroup(group())
CompletableFuture<Response> future = protocol.submitAsync(WriteRequest.newBuilder().setGroup(group())
.setData(ByteString.copyFrom(serializer.serialize(requests)))
.putExtendInfo(DATA_IMPORT_KEY, Boolean.TRUE.toString()).build());
futures.add(future);
@ -427,19 +427,19 @@ public class DistributedDatabaseOperateImpl extends LogProcessor4CP implements B
final String key =
System.currentTimeMillis() + "-" + group() + "-" + memberManager.getSelf().getAddress() + "-"
+ MD5Utils.md5Hex(sqlContext.toString(), Constants.ENCODE);
Log log = Log.newBuilder().setGroup(group()).setKey(key)
WriteRequest request = WriteRequest.newBuilder().setGroup(group()).setKey(key)
.setData(ByteString.copyFrom(serializer.serialize(sqlContext)))
.putAllExtendInfo(EmbeddedStorageContextUtils.getCurrentExtendInfo())
.setType(sqlContext.getClass().getCanonicalName()).build();
if (Objects.isNull(consumer)) {
Response response = this.protocol.submit(log);
Response response = this.protocol.submit(request);
if (response.getSuccess()) {
return true;
}
LogUtil.DEFAULT_LOG.error("execute sql modify operation failed : {}", response.getErrMsg());
return false;
} else {
this.protocol.submitAsync(log).whenComplete((BiConsumer<Response, Throwable>) (response, ex) -> {
this.protocol.submitAsync(request).whenComplete((BiConsumer<Response, Throwable>) (response, ex) -> {
String errMsg = Objects.isNull(ex) ? response.getErrMsg() : ExceptionUtil.getCause(ex).getMessage();
consumer.accept(response.getSuccess(),
StringUtils.isBlank(errMsg) ? null : new NJdbcException(errMsg));
@ -462,7 +462,7 @@ public class DistributedDatabaseOperateImpl extends LogProcessor4CP implements B
@SuppressWarnings("all")
@Override
public Response onRequest(final GetRequest request) {
public Response onRequest(final ReadRequest request) {
final SelectRequest selectRequest = serializer
.deserialize(request.getData().toByteArray(), SelectRequest.class);
@ -511,7 +511,7 @@ public class DistributedDatabaseOperateImpl extends LogProcessor4CP implements B
}
@Override
public Response onApply(Log log) {
public Response onApply(WriteRequest log) {
LoggerUtils.printIfDebugEnabled(LogUtil.DEFAULT_LOG, "onApply info : log : {}", log);
final ByteString byteString = log.getData();
Preconditions.checkArgument(byteString != null, "Log.getData() must not null");

View File

@ -18,8 +18,8 @@ package com.alibaba.nacos.config.server.service.repository.embedded;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.exception.runtime.NacosRuntimeException;
import com.alibaba.nacos.common.utils.MD5Utils;
import com.alibaba.nacos.common.notify.NotifyCenter;
import com.alibaba.nacos.common.utils.MD5Utils;
import com.alibaba.nacos.config.server.configuration.ConditionOnEmbeddedStorage;
import com.alibaba.nacos.config.server.constant.Constants;
import com.alibaba.nacos.config.server.enums.FileTypeEnum;
@ -53,7 +53,7 @@ import com.alibaba.nacos.core.distributed.id.IdGeneratorManager;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Conditional;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

View File

@ -16,6 +16,7 @@
package com.alibaba.nacos.config.server.utils;
import com.alibaba.nacos.common.utils.IPUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ -40,7 +41,7 @@ public class SystemConfig {
if (StringUtils.isNotEmpty(address)) {
return address;
} else {
address = "127.0.0.1";
address = IPUtil.localHostIP();
}
try {
Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();

View File

@ -0,0 +1,68 @@
/*
* Copyright 1999-2020 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.server.service.datasource;
import com.zaxxer.hikari.HikariDataSource;
import org.junit.Before;
import org.junit.Test;
import org.springframework.mock.env.MockEnvironment;
import static org.junit.Assert.assertEquals;
public class DataSourcePoolPropertiesTest {
private static final String JDBC_URL = "jdbc:derby://127.0.0.1:3306/nacos_devtest?characterEncoding=utf8&serverTimezone=UTC";
private static final String JDBC_DRIVER_CLASS_NAME = "org.apache.derby.jdbc.EmbeddedDriver";
private static final String PASSWORD = "nacos";
private static final String USERNAME = "nacos_devtest";
private static final Long CONNECTION_TIMEOUT = 10000L;
private static final Integer MAX_POOL_SIZE = 50;
private MockEnvironment environment;
@Before
public void setUp() throws Exception {
environment = new MockEnvironment();
environment.setProperty("db.user", USERNAME);
environment.setProperty("db.password", PASSWORD);
environment.setProperty("db.pool.config.connectionTimeout", CONNECTION_TIMEOUT.toString());
environment.setProperty("db.pool.config.maximumPoolSize", MAX_POOL_SIZE.toString());
}
@Test
public void testBuild() {
DataSourcePoolProperties poolProperties = DataSourcePoolProperties.build(environment);
poolProperties.setJdbcUrl(JDBC_URL);
poolProperties.setDriverClassName(JDBC_DRIVER_CLASS_NAME);
poolProperties.setUsername(USERNAME);
poolProperties.setPassword(PASSWORD);
HikariDataSource actual = poolProperties.getDataSource();
assertEquals(JDBC_URL, actual.getJdbcUrl());
assertEquals(JDBC_DRIVER_CLASS_NAME, actual.getDriverClassName());
assertEquals(USERNAME, actual.getUsername());
assertEquals(PASSWORD, actual.getPassword());
assertEquals(CONNECTION_TIMEOUT.longValue(), actual.getConnectionTimeout());
assertEquals(DataSourcePoolProperties.DEFAULT_VALIDATION_TIMEOUT, actual.getValidationTimeout());
assertEquals(MAX_POOL_SIZE.intValue(), actual.getMaximumPoolSize());
assertEquals(DataSourcePoolProperties.DEFAULT_MINIMUM_IDLE, actual.getMinimumIdle());
}
}

View File

@ -107,7 +107,7 @@ public class ExternalDataSourcePropertiesTest {
environment.setProperty("db.url.0", JDBC_URL);
List<HikariDataSource> dataSources = new ExternalDataSourceProperties().build(environment, (dataSource -> {
dataSource.validate();
Assert.assertEquals(dataSource.getMinimumIdle(), ExternalDataSourceProperties.DEFAULT_MINIMUM_IDLE);
Assert.assertEquals(dataSource.getMinimumIdle(), DataSourcePoolProperties.DEFAULT_MINIMUM_IDLE);
}));
Assert.assertEquals(dataSources.size(), 1);
}

View File

@ -1,16 +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.
#

View File

@ -30,32 +30,32 @@
</extensions>
<plugins>
<!-- Grpc coding plug-in-->
<!-- <plugin>-->
<!-- <groupId>org.xolstice.maven.plugins</groupId>-->
<!-- <artifactId>protobuf-maven-plugin</artifactId>-->
<!-- <version>0.5.0</version>-->
<!-- <configuration>-->
<!-- <protocArtifact>com.google.protobuf:protoc:${protobuf-java.version}:exe:${os.detected.classifier}</protocArtifact>-->
<!-- <pluginId>grpc-java</pluginId>-->
<!-- <pluginArtifact>io.grpc:protoc-gen-grpc-java:${grpc-java.version}:exe:${os.detected.classifier}</pluginArtifact>-->
<!-- </configuration>-->
<!-- <executions>-->
<!-- <execution>-->
<!-- <goals>-->
<!-- <goal>compile</goal>-->
<!-- <goal>compile-custom</goal>-->
<!-- </goals>-->
<!-- </execution>-->
<!-- </executions>-->
<!-- </plugin>-->
<!-- <plugin>-->
<!-- <groupId>org.apache.maven.plugins</groupId>-->
<!-- <artifactId>maven-compiler-plugin</artifactId>-->
<!-- <configuration>-->
<!-- <source>8</source>-->
<!-- <target>8</target>-->
<!-- </configuration>-->
<!-- </plugin>-->
<plugin>
<groupId>org.xolstice.maven.plugins</groupId>
<artifactId>protobuf-maven-plugin</artifactId>
<version>0.5.0</version>
<configuration>
<protocArtifact>com.google.protobuf:protoc:${protobuf-java.version}:exe:${os.detected.classifier}</protocArtifact>
<pluginId>grpc-java</pluginId>
<pluginArtifact>io.grpc:protoc-gen-grpc-java:${grpc-java.version}:exe:${os.detected.classifier}</pluginArtifact>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>compile-custom</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
</build>

View File

@ -22,7 +22,7 @@ import java.util.Set;
/**
* Consistent protocol related configuration objects.
*
* <p>{@link LogProcessor} : The consistency protocol provides services for all businesses, but each business only cares
* <p>{@link RequestProcessor} : The consistency protocol provides services for all businesses, but each business only cares
* about the transaction information belonging to that business, and the transaction processing between the various
* services should not block each other. Therefore, the LogProcessor is abstracted to implement the parallel processing
* of transactions of different services. Corresponding LogProcessor sub-interface: LogProcessor4AP or LogProcessor4CP,
@ -30,7 +30,7 @@ import java.util.Set;
*
* @author <a href="mailto:liaochuntao@live.com">liaochuntao</a>
*/
public interface Config<L extends LogProcessor> extends Serializable {
public interface Config<L extends RequestProcessor> extends Serializable {
/**
* Set the cluster node information to initializelike [ip:port, ip:port, ip:port].

View File

@ -16,9 +16,9 @@
package com.alibaba.nacos.consistency;
import com.alibaba.nacos.consistency.entity.GetRequest;
import com.alibaba.nacos.consistency.entity.Log;
import com.alibaba.nacos.consistency.entity.ReadRequest;
import com.alibaba.nacos.consistency.entity.Response;
import com.alibaba.nacos.consistency.entity.WriteRequest;
import java.util.Collection;
import java.util.Set;
@ -37,7 +37,7 @@ import java.util.concurrent.CompletableFuture;
*
* @author <a href="mailto:liaochuntao@live.com">liaochuntao</a>
*/
public interface ConsistencyProtocol<T extends Config, P extends LogProcessor> extends CommandOperations {
public interface ConsistencyProtocol<T extends Config, P extends RequestProcessor> extends CommandOperations {
/**
* Consistency protocol initialization: perform initialization operations based on the incoming.
@ -50,7 +50,7 @@ public interface ConsistencyProtocol<T extends Config, P extends LogProcessor> e
/**
* Add a log handler.
*
* @param processors {@link LogProcessor}
* @param processors {@link RequestProcessor}
*/
void addLogProcessors(Collection<P> processors);
@ -69,7 +69,7 @@ public interface ConsistencyProtocol<T extends Config, P extends LogProcessor> e
* @return data {@link Response}
* @throws Exception {@link Exception}
*/
Response getData(GetRequest request) throws Exception;
Response getData(ReadRequest request) throws Exception;
/**
* Get data asynchronously.
@ -77,27 +77,27 @@ public interface ConsistencyProtocol<T extends Config, P extends LogProcessor> e
* @param request request
* @return data {@link CompletableFuture}
*/
CompletableFuture<Response> aGetData(GetRequest request);
CompletableFuture<Response> aGetData(ReadRequest request);
/**
* Data operation, returning submission results synchronously.
* 同步数据提交 Datum 中已携带相应的数据操作信息
*
* @param data {@link Log}
* @param request {@link com.alibaba.nacos.consistency.entity.WriteRequest}
* @return submit operation result {@link Response}
* @throws Exception {@link Exception}
*/
Response submit(Log data) throws Exception;
Response submit(WriteRequest request) throws Exception;
/**
* Data submission operation, returning submission results asynchronously.
* 异步数据提交 Datum中已携带相应的数据操作信息返回一个Future自行操作提交发生的异常会在CompleteFuture中
*
* @param data {@link Log}
* @param request {@link com.alibaba.nacos.consistency.entity.WriteRequest}
* @return {@link CompletableFuture} submit result
* @throws Exception when submit throw Exception
*/
CompletableFuture<Response> submitAsync(Log data);
CompletableFuture<Response> submitAsync(WriteRequest request);
/**
* New member list .

View File

@ -0,0 +1,97 @@
/*
* 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.consistency;
import com.alibaba.nacos.consistency.entity.GetRequest;
import com.alibaba.nacos.consistency.entity.Log;
import com.alibaba.nacos.consistency.entity.ReadRequest;
import com.alibaba.nacos.consistency.entity.WriteRequest;
import com.alibaba.nacos.consistency.exception.ConsistencyException;
import com.google.protobuf.Message;
/**
* protobuf message utils.
*
* @author <a href="mailto:liaochuntao@live.com">liaochuntao</a>
*/
public class ProtoMessageUtil {
/**
* Converts the byte array to a specific Protobuf object.
* Internally, the protobuf new and old objects are compatible.
*
* @param bytes An array of bytes
* @return Message
*/
public static Message parse(byte[] bytes) {
Message result;
try {
result = WriteRequest.parseFrom(bytes);
return result;
} catch (Throwable ignore) {
}
try {
result = ReadRequest.parseFrom(bytes);
return result;
} catch (Throwable ignore) {
}
// old consistency entity, will be @Deprecated in future
try {
Log log = Log.parseFrom(bytes);
return convertToWriteRequest(log);
} catch (Throwable ignore) {
}
try {
GetRequest request = GetRequest.parseFrom(bytes);
return convertToReadRequest(request);
} catch (Throwable ignore) {
}
throw new ConsistencyException("The current array cannot be serialized to the corresponding object");
}
/**
* convert Log to WriteRequest.
*
* @param log log
* @return {@link WriteRequest}
*/
public static WriteRequest convertToWriteRequest(Log log) {
return WriteRequest.newBuilder().setKey(log.getKey()).setGroup(log.getGroup())
.setData(log.getData())
.setType(log.getType())
.setOperation(log.getOperation())
.putAllExtendInfo(log.getExtendInfoMap())
.build();
}
/**
* convert Log to ReadRequest.
*
* @param request request
* @return {@link ReadRequest}
*/
public static ReadRequest convertToReadRequest(GetRequest request) {
return ReadRequest.newBuilder()
.setGroup(request.getGroup())
.setData(request.getData())
.putAllExtendInfo(request.getExtendInfoMap())
.build();
}
}

View File

@ -16,9 +16,9 @@
package com.alibaba.nacos.consistency;
import com.alibaba.nacos.consistency.entity.GetRequest;
import com.alibaba.nacos.consistency.entity.Log;
import com.alibaba.nacos.consistency.entity.ReadRequest;
import com.alibaba.nacos.consistency.entity.Response;
import com.alibaba.nacos.consistency.entity.WriteRequest;
/**
* Can be discovered through SPI or Spring, This interface is just a function definition interface. Different
@ -27,23 +27,23 @@ import com.alibaba.nacos.consistency.entity.Response;
* @author <a href="mailto:liaochuntao@live.com">liaochuntao</a>
*/
@SuppressWarnings("PMD.AbstractClassShouldStartWithAbstractNamingRule")
public abstract class LogProcessor {
public abstract class RequestProcessor {
/**
* get data by key.
*
* @param request request {@link GetRequest}
* @param request request {@link com.alibaba.nacos.consistency.entity.ReadRequest}
* @return target type data
*/
public abstract Response onRequest(GetRequest request);
public abstract Response onRequest(ReadRequest request);
/**
* Process Submitted Log.
*
* @param log {@link Log}
* @param log {@link WriteRequest}
* @return {@link boolean}
*/
public abstract Response onApply(Log log);
public abstract Response onApply(WriteRequest log);
/**
* Irremediable errors that need to trigger business price cuts.

View File

@ -25,6 +25,6 @@ import com.alibaba.nacos.consistency.ConsistencyProtocol;
* @author <a href="mailto:liaochuntao@live.com">liaochuntao</a>
*/
@SuppressWarnings("all")
public interface APProtocol<C extends Config, P extends LogProcessor4AP> extends ConsistencyProtocol<C, P> {
public interface APProtocol<C extends Config, P extends RequestProcessor4AP> extends ConsistencyProtocol<C, P> {
}

View File

@ -16,7 +16,7 @@
package com.alibaba.nacos.consistency.ap;
import com.alibaba.nacos.consistency.LogProcessor;
import com.alibaba.nacos.consistency.RequestProcessor;
/**
* log processor for ap.
@ -24,6 +24,6 @@ import com.alibaba.nacos.consistency.LogProcessor;
* @author <a href="mailto:liaochuntao@live.com">liaochuntao</a>
*/
@SuppressWarnings("all")
public abstract class LogProcessor4AP extends LogProcessor {
public abstract class RequestProcessor4AP extends RequestProcessor {
}

View File

@ -25,7 +25,7 @@ import com.alibaba.nacos.consistency.ConsistencyProtocol;
* @author <a href="mailto:liaochuntao@live.com">liaochuntao</a>
*/
@SuppressWarnings("all")
public interface CPProtocol<C extends Config, P extends LogProcessor4CP> extends ConsistencyProtocol<C, P> {
public interface CPProtocol<C extends Config, P extends RequestProcessor4CP> extends ConsistencyProtocol<C, P> {
/**
* Returns whether this node is a leader node

View File

@ -16,7 +16,7 @@
package com.alibaba.nacos.consistency.cp;
import com.alibaba.nacos.consistency.LogProcessor;
import com.alibaba.nacos.consistency.RequestProcessor;
import com.alibaba.nacos.consistency.snapshot.SnapshotOperation;
import java.util.Collections;
@ -28,7 +28,7 @@ import java.util.List;
* @author <a href="mailto:liaochuntao@live.com">liaochuntao</a>
*/
@SuppressWarnings("all")
public abstract class LogProcessor4CP extends LogProcessor {
public abstract class RequestProcessor4CP extends RequestProcessor {
/**

View File

@ -1,95 +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.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: Data.proto
package com.alibaba.nacos.consistency.entity;
@SuppressWarnings("all")
public final class Data {
static final com.google.protobuf.Descriptors.Descriptor internal_static_Log_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_Log_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor internal_static_Log_ExtendInfoEntry_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_Log_ExtendInfoEntry_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor internal_static_GetRequest_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_GetRequest_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor internal_static_GetRequest_ExtendInfoEntry_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_GetRequest_ExtendInfoEntry_fieldAccessorTable;
static final com.google.protobuf.Descriptors.Descriptor internal_static_Response_descriptor;
static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_Response_fieldAccessorTable;
private static com.google.protobuf.Descriptors.FileDescriptor descriptor;
static {
String[] descriptorData = {"\n\nData.proto\"\255\001\n\003Log\022\r\n\005group\030\001 \001(\t\022\013\n\003k"
+ "ey\030\002 \001(\t\022\014\n\004data\030\003 \001(\014\022\014\n\004type\030\004 \001(\t\022\021\n\t"
+ "operation\030\005 \001(\t\022(\n\nextendInfo\030\006 \003(\0132\024.Lo"
+ "g.ExtendInfoEntry\0321\n\017ExtendInfoEntry\022\013\n\003"
+ "key\030\001 \001(\t\022\r\n\005value\030\002 \001(\t:\0028\001\"\215\001\n\nGetRequ"
+ "est\022\r\n\005group\030\001 \001(\t\022\014\n\004data\030\002 \001(\014\022/\n\nexte"
+ "ndInfo\030\003 \003(\0132\033.GetRequest.ExtendInfoEntr"
+ "y\0321\n\017ExtendInfoEntry\022\013\n\003key\030\001 \001(\t\022\r\n\005val"
+ "ue\030\002 \001(\t:\0028\001\"9\n\010Response\022\014\n\004data\030\001 \001(\014\022\016"
+ "\n\006errMsg\030\002 \001(\t\022\017\n\007success\030\003 \001(\010B(\n$com.a"
+ "libaba.nacos.consistency.entityP\001b\006proto" + "3"};
descriptor = com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom(descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {});
internal_static_Log_descriptor = getDescriptor().getMessageTypes().get(0);
internal_static_Log_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_Log_descriptor,
new String[] {"Group", "Key", "Data", "Type", "Operation", "ExtendInfo",});
internal_static_Log_ExtendInfoEntry_descriptor = internal_static_Log_descriptor.getNestedTypes().get(0);
internal_static_Log_ExtendInfoEntry_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_Log_ExtendInfoEntry_descriptor, new String[] {"Key", "Value",});
internal_static_GetRequest_descriptor = getDescriptor().getMessageTypes().get(1);
internal_static_GetRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_GetRequest_descriptor, new String[] {"Group", "Data", "ExtendInfo",});
internal_static_GetRequest_ExtendInfoEntry_descriptor = internal_static_GetRequest_descriptor.getNestedTypes()
.get(0);
internal_static_GetRequest_ExtendInfoEntry_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_GetRequest_ExtendInfoEntry_descriptor, new String[] {"Key", "Value",});
internal_static_Response_descriptor = getDescriptor().getMessageTypes().get(2);
internal_static_Response_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
internal_static_Response_descriptor, new String[] {"Data", "ErrMsg", "Success",});
}
private Data() {
}
public static void registerAllExtensions(com.google.protobuf.ExtensionRegistryLite registry) {
}
public static void registerAllExtensions(com.google.protobuf.ExtensionRegistry registry) {
registerAllExtensions((com.google.protobuf.ExtensionRegistryLite) registry);
}
public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() {
return descriptor;
}
// @@protoc_insertion_point(outer_class_scope)
}

View File

@ -1,884 +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.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: Data.proto
package com.alibaba.nacos.consistency.entity;
/**
* Protobuf type {@code GetRequest}.
*/
@SuppressWarnings("all")
public final class GetRequest extends com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:GetRequest)
GetRequestOrBuilder {
public static final int GROUP_FIELD_NUMBER = 1;
public static final int DATA_FIELD_NUMBER = 2;
public static final int EXTENDINFO_FIELD_NUMBER = 3;
private static final long serialVersionUID = 0L;
// @@protoc_insertion_point(class_scope:GetRequest)
private static final GetRequest DEFAULT_INSTANCE;
private static final com.google.protobuf.Parser<GetRequest> PARSER = new com.google.protobuf.AbstractParser<GetRequest>() {
@Override
public GetRequest parsePartialFrom(com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new GetRequest(input, extensionRegistry);
}
};
static {
DEFAULT_INSTANCE = new GetRequest();
}
private volatile Object group_;
private com.google.protobuf.ByteString data_;
private com.google.protobuf.MapField<String, String> extendInfo_;
private byte memoizedIsInitialized = -1;
// Use GetRequest.newBuilder() to construct.
private GetRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private GetRequest() {
group_ = "";
data_ = com.google.protobuf.ByteString.EMPTY;
}
private GetRequest(com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new NullPointerException();
}
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10: {
String s = input.readStringRequireUtf8();
group_ = s;
break;
}
case 18: {
data_ = input.readBytes();
break;
}
case 26: {
if (!((mutable_bitField0_ & 0x00000001) != 0)) {
extendInfo_ = com.google.protobuf.MapField
.newMapField(ExtendInfoDefaultEntryHolder.defaultEntry);
mutable_bitField0_ |= 0x00000001;
}
com.google.protobuf.MapEntry<String, String> extendInfo__ = input
.readMessage(ExtendInfoDefaultEntryHolder.defaultEntry.getParserForType(),
extensionRegistry);
extendInfo_.getMutableMap().put(extendInfo__.getKey(), extendInfo__.getValue());
break;
}
default: {
if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return Data.internal_static_GetRequest_descriptor;
}
public static GetRequest parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static GetRequest parseFrom(java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static GetRequest parseFrom(com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static GetRequest parseFrom(com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static GetRequest parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static GetRequest parseFrom(byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static GetRequest parseFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static GetRequest parseFrom(java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, extensionRegistry);
}
public static GetRequest parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static GetRequest parseDelimitedFrom(java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static GetRequest parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static GetRequest parseFrom(com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, extensionRegistry);
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(GetRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
public static GetRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
public static com.google.protobuf.Parser<GetRequest> parser() {
return PARSER;
}
@Override
@SuppressWarnings({"unused"})
protected Object newInstance(UnusedPrivateParameter unused) {
return new GetRequest();
}
@Override
public final com.google.protobuf.UnknownFieldSet getUnknownFields() {
return this.unknownFields;
}
@SuppressWarnings({"rawtypes"})
@Override
protected com.google.protobuf.MapField internalGetMapField(int number) {
switch (number) {
case 3:
return internalGetExtendInfo();
default:
throw new RuntimeException("Invalid map field number: " + number);
}
}
@Override
protected FieldAccessorTable internalGetFieldAccessorTable() {
return Data.internal_static_GetRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(GetRequest.class, GetRequest.Builder.class);
}
/**
* <code>string group = 1;</code>
*/
public String getGroup() {
Object ref = group_;
if (ref instanceof String) {
return (String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
String s = bs.toStringUtf8();
group_ = s;
return s;
}
}
/**
* <code>string group = 1;</code>
*/
public com.google.protobuf.ByteString getGroupBytes() {
Object ref = group_;
if (ref instanceof String) {
com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((String) ref);
group_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>bytes data = 2;</code>
*/
public com.google.protobuf.ByteString getData() {
return data_;
}
private com.google.protobuf.MapField<String, String> internalGetExtendInfo() {
if (extendInfo_ == null) {
return com.google.protobuf.MapField.emptyMapField(ExtendInfoDefaultEntryHolder.defaultEntry);
}
return extendInfo_;
}
public int getExtendInfoCount() {
return internalGetExtendInfo().getMap().size();
}
/**
* <code>map&lt;string, string&gt; extendInfo = 3;</code>
*/
public boolean containsExtendInfo(String key) {
if (key == null) {
throw new NullPointerException();
}
return internalGetExtendInfo().getMap().containsKey(key);
}
/**
* Use {@link #getExtendInfoMap()} instead.
*/
@Deprecated
public java.util.Map<String, String> getExtendInfo() {
return getExtendInfoMap();
}
/**
* <code>map&lt;string, string&gt; extendInfo = 3;</code>
*/
public java.util.Map<String, String> getExtendInfoMap() {
return internalGetExtendInfo().getMap();
}
/**
* <code>map&lt;string, string&gt; extendInfo = 3;</code>
*/
public String getExtendInfoOrDefault(String key, String defaultValue) {
if (key == null) {
throw new NullPointerException();
}
java.util.Map<String, String> map = internalGetExtendInfo().getMap();
return map.containsKey(key) ? map.get(key) : defaultValue;
}
/**
* <code>map&lt;string, string&gt; extendInfo = 3;</code>
*/
public String getExtendInfoOrThrow(String key) {
if (key == null) {
throw new NullPointerException();
}
java.util.Map<String, String> map = internalGetExtendInfo().getMap();
if (!map.containsKey(key)) {
throw new IllegalArgumentException();
}
return map.get(key);
}
@Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) {
return true;
}
if (isInitialized == 0) {
return false;
}
memoizedIsInitialized = 1;
return true;
}
@Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!getGroupBytes().isEmpty()) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, group_);
}
if (!data_.isEmpty()) {
output.writeBytes(2, data_);
}
com.google.protobuf.GeneratedMessageV3
.serializeStringMapTo(output, internalGetExtendInfo(), ExtendInfoDefaultEntryHolder.defaultEntry, 3);
unknownFields.writeTo(output);
}
@Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) {
return size;
}
size = 0;
if (!getGroupBytes().isEmpty()) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, group_);
}
if (!data_.isEmpty()) {
size += com.google.protobuf.CodedOutputStream.computeBytesSize(2, data_);
}
for (java.util.Map.Entry<String, String> entry : internalGetExtendInfo().getMap().entrySet()) {
com.google.protobuf.MapEntry<String, String> extendInfo__ = ExtendInfoDefaultEntryHolder.defaultEntry
.newBuilderForType().setKey(entry.getKey()).setValue(entry.getValue()).build();
size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, extendInfo__);
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@Override
public boolean equals(final Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof GetRequest)) {
return super.equals(obj);
}
GetRequest other = (GetRequest) obj;
if (!getGroup().equals(other.getGroup())) {
return false;
}
if (!getData().equals(other.getData())) {
return false;
}
if (!internalGetExtendInfo().equals(other.internalGetExtendInfo())) {
return false;
}
if (!unknownFields.equals(other.unknownFields)) {
return false;
}
return true;
}
@Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + GROUP_FIELD_NUMBER;
hash = (53 * hash) + getGroup().hashCode();
hash = (37 * hash) + DATA_FIELD_NUMBER;
hash = (53 * hash) + getData().hashCode();
if (!internalGetExtendInfo().getMap().isEmpty()) {
hash = (37 * hash) + EXTENDINFO_FIELD_NUMBER;
hash = (53 * hash) + internalGetExtendInfo().hashCode();
}
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
@Override
public Builder newBuilderForType() {
return newBuilder();
}
@Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@Override
protected Builder newBuilderForType(BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
@Override
public com.google.protobuf.Parser<GetRequest> getParserForType() {
return PARSER;
}
@Override
public GetRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
private static final class ExtendInfoDefaultEntryHolder {
static final com.google.protobuf.MapEntry<String, String> defaultEntry = com.google.protobuf.MapEntry.<String, String>newDefaultInstance(
Data.internal_static_GetRequest_ExtendInfoEntry_descriptor,
com.google.protobuf.WireFormat.FieldType.STRING, "", com.google.protobuf.WireFormat.FieldType.STRING,
"");
}
/**
* Protobuf type {@code GetRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:GetRequest)
GetRequestOrBuilder {
private int bitField0_;
private Object group_ = "";
private com.google.protobuf.ByteString data_ = com.google.protobuf.ByteString.EMPTY;
private com.google.protobuf.MapField<String, String> extendInfo_;
// Construct using com.alibaba.nacos.consistency.entity.GetRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return Data.internal_static_GetRequest_descriptor;
}
@SuppressWarnings({"rawtypes"})
protected com.google.protobuf.MapField internalGetMapField(int number) {
switch (number) {
case 3:
return internalGetExtendInfo();
default:
throw new RuntimeException("Invalid map field number: " + number);
}
}
@SuppressWarnings({"rawtypes"})
protected com.google.protobuf.MapField internalGetMutableMapField(int number) {
switch (number) {
case 3:
return internalGetMutableExtendInfo();
default:
throw new RuntimeException("Invalid map field number: " + number);
}
}
@Override
protected FieldAccessorTable internalGetFieldAccessorTable() {
return Data.internal_static_GetRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(GetRequest.class, GetRequest.Builder.class);
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
}
}
@Override
public Builder clear() {
super.clear();
group_ = "";
data_ = com.google.protobuf.ByteString.EMPTY;
internalGetMutableExtendInfo().clear();
return this;
}
@Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return Data.internal_static_GetRequest_descriptor;
}
@Override
public GetRequest getDefaultInstanceForType() {
return GetRequest.getDefaultInstance();
}
@Override
public GetRequest build() {
GetRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@Override
public GetRequest buildPartial() {
GetRequest result = new GetRequest(this);
int from_bitField0_ = bitField0_;
result.group_ = group_;
result.data_ = data_;
result.extendInfo_ = internalGetExtendInfo();
result.extendInfo_.makeImmutable();
onBuilt();
return result;
}
@Override
public Builder clone() {
return super.clone();
}
@Override
public Builder setField(com.google.protobuf.Descriptors.FieldDescriptor field, Object value) {
return super.setField(field, value);
}
@Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@Override
public Builder setRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, int index,
Object value) {
return super.setRepeatedField(field, index, value);
}
@Override
public Builder addRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, Object value) {
return super.addRepeatedField(field, value);
}
@Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof GetRequest) {
return mergeFrom((GetRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(GetRequest other) {
if (other == GetRequest.getDefaultInstance()) {
return this;
}
if (!other.getGroup().isEmpty()) {
group_ = other.group_;
onChanged();
}
if (other.getData() != com.google.protobuf.ByteString.EMPTY) {
setData(other.getData());
}
internalGetMutableExtendInfo().mergeFrom(other.internalGetExtendInfo());
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@Override
public final boolean isInitialized() {
return true;
}
@Override
public Builder mergeFrom(com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException {
GetRequest parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (GetRequest) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
/**
* <code>string group = 1;</code>
*/
public String getGroup() {
Object ref = group_;
if (!(ref instanceof String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
String s = bs.toStringUtf8();
group_ = s;
return s;
} else {
return (String) ref;
}
}
/**
* <code>string group = 1;</code>
*/
public Builder setGroup(String value) {
if (value == null) {
throw new NullPointerException();
}
group_ = value;
onChanged();
return this;
}
/**
* <code>string group = 1;</code>
*/
public com.google.protobuf.ByteString getGroupBytes() {
Object ref = group_;
if (ref instanceof String) {
com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((String) ref);
group_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>string group = 1;</code>
*/
public Builder setGroupBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
group_ = value;
onChanged();
return this;
}
/**
* <code>string group = 1;</code>
*/
public Builder clearGroup() {
group_ = getDefaultInstance().getGroup();
onChanged();
return this;
}
/**
* <code>bytes data = 2;</code>
*/
public com.google.protobuf.ByteString getData() {
return data_;
}
/**
* <code>bytes data = 2;</code>
*/
public Builder setData(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
data_ = value;
onChanged();
return this;
}
/**
* <code>bytes data = 2;</code>
*/
public Builder clearData() {
data_ = getDefaultInstance().getData();
onChanged();
return this;
}
private com.google.protobuf.MapField<String, String> internalGetExtendInfo() {
if (extendInfo_ == null) {
return com.google.protobuf.MapField.emptyMapField(ExtendInfoDefaultEntryHolder.defaultEntry);
}
return extendInfo_;
}
private com.google.protobuf.MapField<String, String> internalGetMutableExtendInfo() {
onChanged();
;
if (extendInfo_ == null) {
extendInfo_ = com.google.protobuf.MapField.newMapField(ExtendInfoDefaultEntryHolder.defaultEntry);
}
if (!extendInfo_.isMutable()) {
extendInfo_ = extendInfo_.copy();
}
return extendInfo_;
}
public int getExtendInfoCount() {
return internalGetExtendInfo().getMap().size();
}
/**
* <code>map&lt;string, string&gt; extendInfo = 3;</code>
*/
public boolean containsExtendInfo(String key) {
if (key == null) {
throw new NullPointerException();
}
return internalGetExtendInfo().getMap().containsKey(key);
}
/**
* Use {@link #getExtendInfoMap()} instead.
*/
@Deprecated
public java.util.Map<String, String> getExtendInfo() {
return getExtendInfoMap();
}
/**
* <code>map&lt;string, string&gt; extendInfo = 3;</code>
*/
public java.util.Map<String, String> getExtendInfoMap() {
return internalGetExtendInfo().getMap();
}
/**
* <code>map&lt;string, string&gt; extendInfo = 3;</code>
*/
public String getExtendInfoOrDefault(String key, String defaultValue) {
if (key == null) {
throw new NullPointerException();
}
java.util.Map<String, String> map = internalGetExtendInfo().getMap();
return map.containsKey(key) ? map.get(key) : defaultValue;
}
/**
* <code>map&lt;string, string&gt; extendInfo = 3;</code>
*/
public String getExtendInfoOrThrow(String key) {
if (key == null) {
throw new NullPointerException();
}
java.util.Map<String, String> map = internalGetExtendInfo().getMap();
if (!map.containsKey(key)) {
throw new IllegalArgumentException();
}
return map.get(key);
}
public Builder clearExtendInfo() {
internalGetMutableExtendInfo().getMutableMap().clear();
return this;
}
/**
* <code>map&lt;string, string&gt; extendInfo = 3;</code>
*/
public Builder removeExtendInfo(String key) {
if (key == null) {
throw new NullPointerException();
}
internalGetMutableExtendInfo().getMutableMap().remove(key);
return this;
}
/**
* Use alternate mutation accessors instead.
*/
@Deprecated
public java.util.Map<String, String> getMutableExtendInfo() {
return internalGetMutableExtendInfo().getMutableMap();
}
/**
* <code>map&lt;string, string&gt; extendInfo = 3;</code>
*/
public Builder putExtendInfo(String key, String value) {
if (key == null) {
throw new NullPointerException();
}
if (value == null) {
throw new NullPointerException();
}
internalGetMutableExtendInfo().getMutableMap().put(key, value);
return this;
}
/**
* <code>map&lt;string, string&gt; extendInfo = 3;</code>
*/
public Builder putAllExtendInfo(java.util.Map<String, String> values) {
internalGetMutableExtendInfo().getMutableMap().putAll(values);
return this;
}
@Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@Override
public final Builder mergeUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:GetRequest)
}
}

View File

@ -1,74 +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.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: Data.proto
package com.alibaba.nacos.consistency.entity;
@SuppressWarnings("all")
public interface GetRequestOrBuilder extends
// @@protoc_insertion_point(interface_extends:GetRequest)
com.google.protobuf.MessageOrBuilder {
/**
* <code>string group = 1;</code>
*/
String getGroup();
/**
* <code>string group = 1;</code>
*/
com.google.protobuf.ByteString getGroupBytes();
/**
* <code>bytes data = 2;</code>
*/
com.google.protobuf.ByteString getData();
/**
* <code>map&lt;string, string&gt; extendInfo = 3;</code>
*/
int getExtendInfoCount();
/**
* <code>map&lt;string, string&gt; extendInfo = 3;</code>
*/
boolean containsExtendInfo(String key);
/**
* Use {@link #getExtendInfoMap()} instead.
*/
@Deprecated
java.util.Map<String, String> getExtendInfo();
/**
* <code>map&lt;string, string&gt; extendInfo = 3;</code>
*/
java.util.Map<String, String> getExtendInfoMap();
/**
* <code>map&lt;string, string&gt; extendInfo = 3;</code>
*/
String getExtendInfoOrDefault(String key, String defaultValue);
/**
* <code>map&lt;string, string&gt; extendInfo = 3;</code>
*/
String getExtendInfoOrThrow(String key);
}

View File

@ -1,104 +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.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: Data.proto
package com.alibaba.nacos.consistency.entity;
@SuppressWarnings("all")
public interface LogOrBuilder extends
// @@protoc_insertion_point(interface_extends:Log)
com.google.protobuf.MessageOrBuilder {
/**
* <code>string group = 1;</code>
*/
String getGroup();
/**
* <code>string group = 1;</code>
*/
com.google.protobuf.ByteString getGroupBytes();
/**
* <code>string key = 2;</code>
*/
String getKey();
/**
* <code>string key = 2;</code>
*/
com.google.protobuf.ByteString getKeyBytes();
/**
* <code>bytes data = 3;</code>
*/
com.google.protobuf.ByteString getData();
/**
* <code>string type = 4;</code>
*/
String getType();
/**
* <code>string type = 4;</code>
*/
com.google.protobuf.ByteString getTypeBytes();
/**
* <code>string operation = 5;</code>
*/
String getOperation();
/**
* <code>string operation = 5;</code>
*/
com.google.protobuf.ByteString getOperationBytes();
/**
* <code>map&lt;string, string&gt; extendInfo = 6;</code>
*/
int getExtendInfoCount();
/**
* <code>map&lt;string, string&gt; extendInfo = 6;</code>
*/
boolean containsExtendInfo(String key);
/**
* Use {@link #getExtendInfoMap()} instead.
*/
@Deprecated
java.util.Map<String, String> getExtendInfo();
/**
* <code>map&lt;string, string&gt; extendInfo = 6;</code>
*/
java.util.Map<String, String> getExtendInfoMap();
/**
* <code>map&lt;string, string&gt; extendInfo = 6;</code>
*/
String getExtendInfoOrDefault(String key, String defaultValue);
/**
* <code>map&lt;string, string&gt; extendInfo = 6;</code>
*/
String getExtendInfoOrThrow(String key);
}

View File

@ -1,677 +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.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: Data.proto
package com.alibaba.nacos.consistency.entity;
/**
* Protobuf type {@code Response}.
*/
@SuppressWarnings("all")
public final class Response extends com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:Response)
ResponseOrBuilder {
public static final int DATA_FIELD_NUMBER = 1;
public static final int ERRMSG_FIELD_NUMBER = 2;
public static final int SUCCESS_FIELD_NUMBER = 3;
private static final long serialVersionUID = 0L;
// @@protoc_insertion_point(class_scope:Response)
private static final Response DEFAULT_INSTANCE;
private static final com.google.protobuf.Parser<Response> PARSER = new com.google.protobuf.AbstractParser<Response>() {
@Override
public Response parsePartialFrom(com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new Response(input, extensionRegistry);
}
};
static {
DEFAULT_INSTANCE = new Response();
}
private com.google.protobuf.ByteString data_;
private volatile Object errMsg_;
private boolean success_;
private byte memoizedIsInitialized = -1;
// Use Response.newBuilder() to construct.
private Response(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private Response() {
data_ = com.google.protobuf.ByteString.EMPTY;
errMsg_ = "";
}
private Response(com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new NullPointerException();
}
com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10: {
data_ = input.readBytes();
break;
}
case 18: {
String s = input.readStringRequireUtf8();
errMsg_ = s;
break;
}
case 24: {
success_ = input.readBool();
break;
}
default: {
if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return Data.internal_static_Response_descriptor;
}
public static Response parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static Response parseFrom(java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static Response parseFrom(com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static Response parseFrom(com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static Response parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static Response parseFrom(byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static Response parseFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static Response parseFrom(java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, extensionRegistry);
}
public static Response parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static Response parseDelimitedFrom(java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static Response parseFrom(com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static Response parseFrom(com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input, extensionRegistry);
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(Response prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
public static Response getDefaultInstance() {
return DEFAULT_INSTANCE;
}
public static com.google.protobuf.Parser<Response> parser() {
return PARSER;
}
@Override
@SuppressWarnings({"unused"})
protected Object newInstance(UnusedPrivateParameter unused) {
return new Response();
}
@Override
public final com.google.protobuf.UnknownFieldSet getUnknownFields() {
return this.unknownFields;
}
@Override
protected FieldAccessorTable internalGetFieldAccessorTable() {
return Data.internal_static_Response_fieldAccessorTable
.ensureFieldAccessorsInitialized(Response.class, Response.Builder.class);
}
/**
* <code>bytes data = 1;</code>
*/
public com.google.protobuf.ByteString getData() {
return data_;
}
/**
* <code>string errMsg = 2;</code>
*/
public String getErrMsg() {
Object ref = errMsg_;
if (ref instanceof String) {
return (String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
String s = bs.toStringUtf8();
errMsg_ = s;
return s;
}
}
/**
* <code>string errMsg = 2;</code>
*/
public com.google.protobuf.ByteString getErrMsgBytes() {
Object ref = errMsg_;
if (ref instanceof String) {
com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((String) ref);
errMsg_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>bool success = 3;</code>
*/
public boolean getSuccess() {
return success_;
}
@Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) {
return true;
}
if (isInitialized == 0) {
return false;
}
memoizedIsInitialized = 1;
return true;
}
@Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!data_.isEmpty()) {
output.writeBytes(1, data_);
}
if (!getErrMsgBytes().isEmpty()) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 2, errMsg_);
}
if (success_ != false) {
output.writeBool(3, success_);
}
unknownFields.writeTo(output);
}
@Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) {
return size;
}
size = 0;
if (!data_.isEmpty()) {
size += com.google.protobuf.CodedOutputStream.computeBytesSize(1, data_);
}
if (!getErrMsgBytes().isEmpty()) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, errMsg_);
}
if (success_ != false) {
size += com.google.protobuf.CodedOutputStream.computeBoolSize(3, success_);
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@Override
public boolean equals(final Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof Response)) {
return super.equals(obj);
}
Response other = (Response) obj;
if (!getData().equals(other.getData())) {
return false;
}
if (!getErrMsg().equals(other.getErrMsg())) {
return false;
}
if (getSuccess() != other.getSuccess()) {
return false;
}
if (!unknownFields.equals(other.unknownFields)) {
return false;
}
return true;
}
@Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + DATA_FIELD_NUMBER;
hash = (53 * hash) + getData().hashCode();
hash = (37 * hash) + ERRMSG_FIELD_NUMBER;
hash = (53 * hash) + getErrMsg().hashCode();
hash = (37 * hash) + SUCCESS_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(getSuccess());
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
@Override
public Builder newBuilderForType() {
return newBuilder();
}
@Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@Override
protected Builder newBuilderForType(BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
@Override
public com.google.protobuf.Parser<Response> getParserForType() {
return PARSER;
}
@Override
public Response getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
/**
* Protobuf type {@code Response}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:Response)
ResponseOrBuilder {
private com.google.protobuf.ByteString data_ = com.google.protobuf.ByteString.EMPTY;
private Object errMsg_ = "";
private boolean success_;
// Construct using com.alibaba.nacos.consistency.entity.Response.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return Data.internal_static_Response_descriptor;
}
@Override
protected FieldAccessorTable internalGetFieldAccessorTable() {
return Data.internal_static_Response_fieldAccessorTable
.ensureFieldAccessorsInitialized(Response.class, Response.Builder.class);
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
}
}
@Override
public Builder clear() {
super.clear();
data_ = com.google.protobuf.ByteString.EMPTY;
errMsg_ = "";
success_ = false;
return this;
}
@Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return Data.internal_static_Response_descriptor;
}
@Override
public Response getDefaultInstanceForType() {
return Response.getDefaultInstance();
}
@Override
public Response build() {
Response result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@Override
public Response buildPartial() {
Response result = new Response(this);
result.data_ = data_;
result.errMsg_ = errMsg_;
result.success_ = success_;
onBuilt();
return result;
}
@Override
public Builder clone() {
return super.clone();
}
@Override
public Builder setField(com.google.protobuf.Descriptors.FieldDescriptor field, Object value) {
return super.setField(field, value);
}
@Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@Override
public Builder setRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, int index,
Object value) {
return super.setRepeatedField(field, index, value);
}
@Override
public Builder addRepeatedField(com.google.protobuf.Descriptors.FieldDescriptor field, Object value) {
return super.addRepeatedField(field, value);
}
@Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof Response) {
return mergeFrom((Response) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(Response other) {
if (other == Response.getDefaultInstance()) {
return this;
}
if (other.getData() != com.google.protobuf.ByteString.EMPTY) {
setData(other.getData());
}
if (!other.getErrMsg().isEmpty()) {
errMsg_ = other.errMsg_;
onChanged();
}
if (other.getSuccess() != false) {
setSuccess(other.getSuccess());
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@Override
public final boolean isInitialized() {
return true;
}
@Override
public Builder mergeFrom(com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException {
Response parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (Response) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
/**
* <code>bytes data = 1;</code>
*/
public com.google.protobuf.ByteString getData() {
return data_;
}
/**
* <code>bytes data = 1;</code>
*/
public Builder setData(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
data_ = value;
onChanged();
return this;
}
/**
* <code>bytes data = 1;</code>
*/
public Builder clearData() {
data_ = getDefaultInstance().getData();
onChanged();
return this;
}
/**
* <code>string errMsg = 2;</code>
*/
public String getErrMsg() {
Object ref = errMsg_;
if (!(ref instanceof String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
String s = bs.toStringUtf8();
errMsg_ = s;
return s;
} else {
return (String) ref;
}
}
/**
* <code>string errMsg = 2;</code>
*/
public Builder setErrMsg(String value) {
if (value == null) {
throw new NullPointerException();
}
errMsg_ = value;
onChanged();
return this;
}
/**
* <code>string errMsg = 2;</code>
*/
public com.google.protobuf.ByteString getErrMsgBytes() {
Object ref = errMsg_;
if (ref instanceof String) {
com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((String) ref);
errMsg_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
* <code>string errMsg = 2;</code>
*/
public Builder setErrMsgBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
errMsg_ = value;
onChanged();
return this;
}
/**
* <code>string errMsg = 2;</code>
*/
public Builder clearErrMsg() {
errMsg_ = getDefaultInstance().getErrMsg();
onChanged();
return this;
}
/**
* <code>bool success = 3;</code>
*/
public boolean getSuccess() {
return success_;
}
/**
* <code>bool success = 3;</code>
*/
public Builder setSuccess(boolean value) {
success_ = value;
onChanged();
return this;
}
/**
* <code>bool success = 3;</code>
*/
public Builder clearSuccess() {
success_ = false;
onChanged();
return this;
}
@Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@Override
public final Builder mergeUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:Response)
}
}

View File

@ -1,46 +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.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: Data.proto
package com.alibaba.nacos.consistency.entity;
@SuppressWarnings("all")
public interface ResponseOrBuilder extends
// @@protoc_insertion_point(interface_extends:Response)
com.google.protobuf.MessageOrBuilder {
/**
* <code>bytes data = 1;</code>
*/
com.google.protobuf.ByteString getData();
/**
* <code>string errMsg = 2;</code>
*/
String getErrMsg();
/**
* <code>string errMsg = 2;</code>
*/
com.google.protobuf.ByteString getErrMsgBytes();
/**
* <code>bool success = 3;</code>
*/
boolean getSuccess();
}

View File

@ -19,6 +19,7 @@ syntax = "proto3";
option java_multiple_files = true;
option java_package = "com.alibaba.nacos.consistency.entity";
//Deprecated
message Log {
string group = 1;
string key = 2;
@ -28,15 +29,10 @@ message Log {
map<string, string> extendInfo = 6;
}
//Deprecated
message GetRequest {
string group = 1;
bytes data = 2;
map<string, string> extendInfo = 3;
}
message Response {
bytes data = 1;
string errMsg = 2;
bool success = 3;
}

View File

@ -0,0 +1,42 @@
/*
* 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.
*/
syntax = "proto3";
option java_multiple_files = true;
option java_package = "com.alibaba.nacos.consistency.entity";
message WriteRequest {
string group = 1;
string key = 2;
bytes data = 3;
string type = 4;
string operation = 5;
map<string, string> extendInfo = 6;
}
message ReadRequest {
string group = 1;
bytes data = 2;
map<string, string> extendInfo = 3;
}
message Response {
bytes data = 1;
string errMsg = 2;
bool success = 3;
}

View File

@ -0,0 +1,37 @@
/*
* 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.consistency;
import com.alibaba.nacos.consistency.entity.Log;
import com.alibaba.nacos.consistency.entity.WriteRequest;
import org.junit.Assert;
import org.junit.Test;
public class ProtoMessageUtilTest {
@Test
public void testProto() throws Exception {
WriteRequest request = WriteRequest.newBuilder()
.setKey("test-proto-new")
.build();
byte[] bytes = request.toByteArray();
Log log = Log.parseFrom(bytes);
Assert.assertEquals(request.getKey(), log.getKey());
}
}

50
console-ui/README.md Normal file
View File

@ -0,0 +1,50 @@
# 开始项目
国内访问 npm 比较慢,我们可以使用阿里的镜像,
在 npm 或者 yarn 命令后面加参数:
> --registry=https://registry.npm.taobao.org
例:
```
npm install --registry=https://registry.npm.taobao.org
yarn --registry=https://registry.npm.taobao.org
```
[详情地址: http://npm.taobao.org/](http://npm.taobao.org/)
## 安装依赖
```sh
yarn
```
```
npm install
```
## 启动
```sh
yarn start
```
```
npm start
```
## 构建打包
```sh
yarn build
```
```
npm run build
```
##
# 代理配置
`build/webpack.dev.conf.js`
修改proxy属性
```
proxy: [{
context: ['/'],
changeOrigin: true,
secure: false,
target: 'http://ip:port',
}],
```

View File

@ -24,7 +24,7 @@ const styles = {
};
const distPath = path.join(__dirname, '../dist/');
const rootPath = path.join(__dirname, '../../');
const rootPath = path.join(__dirname, '../../console/src/main/resources/static/');
console.log('\n\n> Start copying the dist directory...\n');

View File

@ -19,7 +19,7 @@ const path = require('path');
// 默认打包存放地址
const srcDir = path.join(__dirname, '../dist');
// 打包后文件存放地址
const destDir = path.join(__dirname, '../../');
const destDir = path.join(__dirname, '../../console/src/main/resources/static/');
const mkdir = dir => {
if (!fs.existsSync(dir)) {

View File

@ -93,7 +93,7 @@ module.exports = {
}),
new CopyWebpackPlugin([
{
from: resolve('public'),
from: resolve('../console/src/main/resources/static/console-ui/public'),
to: './',
ignore: ['index.html'],
},

View File

@ -18,6 +18,16 @@ const path = require('path');
const webpack = require('webpack');
const base = require('./webpack.base.conf');
const [cssLoader] = base.module.rules;
cssLoader.use.push({
loader: '@alifd/next-theme-loader',
options: {
modifyVars: {
'$icon-font-path': '"/icons/icon-font"',
'$font-custom-path': '"/fonts/"'
}
}
})
module.exports = Object.assign({}, base, {
output: {
filename: './js/[name].js',

View File

@ -26,8 +26,8 @@ cssLoader.use.push({
loader: '@alifd/next-theme-loader',
options: {
modifyVars: {
'$icon-font-path': '"/nacos/console-fe/public/icons/icon-font"',
'$font-custom-path': '"/nacos/console-fe/public/fonts/"'
'$icon-font-path': '"/nacos/console-ui/public/icons/icon-font"',
'$font-custom-path': '"/nacos/console-ui/public/fonts/"'
}
}
})

View File

@ -1,7 +1,7 @@
{
"name": "console-fe",
"name": "console-ui",
"version": "1.0.0",
"description": "console fe",
"description": "console ui",
"main": "index.js",
"scripts": {
"start": "cross-env NODE_ENV=development webpack-dev-server --config build/webpack.dev.conf.js",

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