Skip to content

Commit

Permalink
[3.0] Add unit test for dubbo-registry-nacos (apache#9035)
Browse files Browse the repository at this point in the history
* add unit test for nacos registry

* add NacosRegistryFactoryTest

* add NacosServiceDiscoveryFactoryTest

* NacosRegistry code format

* add NacosServiceDiscoveryTest

* add NacosRegistryTest

* add unit test for dubbo-registry-nacos
  • Loading branch information
wangchengming666 authored Oct 14, 2021
1 parent 0429e8e commit 54b2096
Show file tree
Hide file tree
Showing 9 changed files with 813 additions and 48 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
*/
package org.apache.dubbo.registry.nacos;

import org.apache.dubbo.common.utils.StringUtils;

import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.listener.EventListener;
Expand All @@ -30,7 +32,7 @@ public class NacosNamingServiceWrapper {

private static final String INNERCLASS_COMPATIBLE_SYMBOL = "___";

private NamingService namingService;
private final NamingService namingService;

public NacosNamingServiceWrapper(NamingService namingService) {
this.namingService = namingService;
Expand Down Expand Up @@ -87,7 +89,7 @@ public void shutdown() throws NacosException {
* nacos service name just support `0-9a-zA-Z-._:`, grpc interface is inner interface, need compatible.
*/
private String handleInnerSymbol(String serviceName) {
if (serviceName == null) {
if (StringUtils.isEmpty(serviceName)) {
return null;
}
return serviceName.replace(INNERCLASS_SYMBOL, INNERCLASS_COMPATIBLE_SYMBOL);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,6 @@
package org.apache.dubbo.registry.nacos;


import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.listener.Event;
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.ListView;
import com.google.common.collect.Lists;
import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.URLBuilder;
import org.apache.dubbo.common.logger.Logger;
Expand All @@ -40,6 +32,15 @@
import org.apache.dubbo.registry.support.FailbackRegistry;
import org.apache.dubbo.rpc.RpcException;

import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.listener.Event;
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.ListView;
import com.google.common.collect.Lists;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
Expand Down Expand Up @@ -86,10 +87,10 @@ public class NacosRegistry extends FailbackRegistry {
* All supported categories
*/
private static final List<String> ALL_SUPPORTED_CATEGORIES = Arrays.asList(
PROVIDERS_CATEGORY,
CONSUMERS_CATEGORY,
ROUTERS_CATEGORY,
CONFIGURATORS_CATEGORY
PROVIDERS_CATEGORY,
CONSUMERS_CATEGORY,
ROUTERS_CATEGORY,
CONFIGURATORS_CATEGORY
);

private static final int CATEGORY_INDEX = 0;
Expand All @@ -102,6 +103,8 @@ public class NacosRegistry extends FailbackRegistry {

private static final String WILDCARD = "*";

private static final String UP = "UP";

/**
* The separator for service name
* Change a constant to be configurable, it's designed for Windows file name that is compatible with old
Expand All @@ -118,32 +121,29 @@ public class NacosRegistry extends FailbackRegistry {
* The interval in second of lookup Nacos service names(only for Dubbo-OPS)
*/
private static final long LOOKUP_INTERVAL = Long.getLong("nacos.service.names.lookup.interval", 30);

private static final Logger logger = LoggerFactory.getLogger(NacosRegistry.class);
private final NacosNamingServiceWrapper namingService;
/**
* {@link ScheduledExecutorService} lookup Nacos service names(only for Dubbo-OPS)
*/
private volatile ScheduledExecutorService scheduledExecutorService;

private static final Logger logger = LoggerFactory.getLogger(NacosRegistry.class);

private final NacosNamingServiceWrapper namingService;

public NacosRegistry(URL url, NacosNamingServiceWrapper namingService) {
super(url);
this.namingService = namingService;
}

@Override
public boolean isAvailable() {
return "UP".equals(namingService.getServerStatus());
return UP.equals(namingService.getServerStatus());
}

@Override
public List<URL> lookup(final URL url) {
if(url == null){
if (url == null) {
throw new IllegalArgumentException("lookup url == null");
}
try{
try {
List<URL> urls = new LinkedList<>();
Set<String> serviceNames = getServiceNames(url, null);
for (String serviceName : serviceNames) {
Expand All @@ -152,14 +152,14 @@ public List<URL> lookup(final URL url) {
urls.addAll(buildURLs(url, instances));
}
return urls;
}catch (Throwable cause){
} catch (Throwable cause) {
throw new RpcException("Failed to lookup " + url + " from nacos " + getUrl() + ", cause: " + cause.getMessage(), cause);
}
}

@Override
public void doRegister(URL url) {
try{
try {
String serviceName = getServiceName(url);
Instance instance = createInstance(url);
/**
Expand All @@ -170,21 +170,21 @@ public void doRegister(URL url) {
*/
namingService.registerInstance(serviceName,
getUrl().getGroup(Constants.DEFAULT_GROUP), instance);
}catch (Throwable cause){
} catch (Throwable cause) {
throw new RpcException("Failed to register " + url + " to nacos " + getUrl() + ", cause: " + cause.getMessage(), cause);
}
}

@Override
public void doUnregister(final URL url) {
try{
try {
String serviceName = getServiceName(url);
Instance instance = createInstance(url);
namingService.deregisterInstance(serviceName,
getUrl().getGroup(Constants.DEFAULT_GROUP),
instance.getIp()
, instance.getPort());
}catch (Throwable cause){
} catch (Throwable cause) {
throw new RpcException("Failed to unregister " + url + " to nacos " + getUrl() + ", cause: " + cause.getMessage(), cause);
}
}
Expand All @@ -204,7 +204,7 @@ public void doSubscribe(final URL url, final NotifyListener listener) {
}

private void doSubscribe(final URL url, final NotifyListener listener, final Set<String> serviceNames) {
try{
try {
if (isServiceNamesWithCompatibleMode(url)) {
List<Instance> allCorrespondingInstanceList = Lists.newArrayList();

Expand Down Expand Up @@ -243,7 +243,7 @@ private void doSubscribe(final URL url, final NotifyListener listener, final Set
subscribeEventListener(serviceName, subscriberURL, listener);
}
}
}catch (Throwable cause){
} catch (Throwable cause) {
throw new RpcException("Failed to subscribe " + url + " to nacos " + getUrl() + ", cause: " + cause.getMessage(), cause);
}
}
Expand Down Expand Up @@ -310,19 +310,19 @@ private Set<String> getServiceNames0(URL url) {
}

private Set<String> filterServiceNames(NacosServiceName serviceName) {
try{
try {
Set<String> serviceNames = new LinkedHashSet<>();
serviceNames.addAll(namingService.getServicesOfServer(1, Integer.MAX_VALUE,
getUrl().getGroup(Constants.DEFAULT_GROUP)).getData()
getUrl().getGroup(Constants.DEFAULT_GROUP)).getData()
.stream()
.filter(this::isConformRules)
.map(NacosServiceName::new)
.filter(serviceName::isCompatible)
.map(NacosServiceName::toString)
.collect(Collectors.toList()));
return serviceNames;
}catch (Throwable cause){
throw new RpcException("Failed to filter serviceName from nacos, url: " + getUrl() + ", serviceName: "+serviceName+", cause: " + cause.getMessage(), cause);
} catch (Throwable cause) {
throw new RpcException("Failed to filter serviceName from nacos, url: " + getUrl() + ", serviceName: " + serviceName + ", cause: " + cause.getMessage(), cause);
}
}

Expand Down Expand Up @@ -399,7 +399,7 @@ private Set<String> getServiceNamesForOps(URL url) {
}

private Set<String> getAllServiceNames() {
try{
try {
final Set<String> serviceNames = new LinkedHashSet<>();
int pageIndex = 1;
ListView<String> listView = namingService.getServicesOfServer(pageIndex, PAGINATION_SIZE,
Expand All @@ -424,7 +424,7 @@ private Set<String> getAllServiceNames() {
serviceNames.addAll(listView.getData());
}
return serviceNames;
}catch (Throwable cause){
} catch (Throwable cause) {
throw new RpcException("Failed to get all serviceName from nacos, url: " + getUrl() + ", cause: " + cause.getMessage(), cause);
}
}
Expand Down Expand Up @@ -459,7 +459,7 @@ private void filterServiceNames(Set<String> serviceNames, URL url) {
String serviceInterface = segments[SERVICE_INTERFACE_INDEX];
// no match service interface
if (!WILDCARD.equals(targetServiceInterface) &&
!StringUtils.isEquals(targetServiceInterface, serviceInterface)) {
!StringUtils.isEquals(targetServiceInterface, serviceInterface)) {
return false;
}

Expand Down Expand Up @@ -494,9 +494,9 @@ private List<URL> toUrlWithEmpty(URL consumerURL, Collection<Instance> instances
List<URL> urls = buildURLs(consumerURL, instances);
if (urls.size() == 0) {
URL empty = URLBuilder.from(consumerURL)
.setProtocol(EMPTY_PROTOCOL)
.addParameter(CATEGORY_KEY, DEFAULT_CATEGORY)
.build();
.setProtocol(EMPTY_PROTOCOL)
.addParameter(CATEGORY_KEY, DEFAULT_CATEGORY)
.build();
urls.add(empty);
}
return urls;
Expand All @@ -516,11 +516,11 @@ private List<URL> buildURLs(URL consumerURL, Collection<Instance> instances) {
}

private void subscribeEventListener(String serviceName, final URL url, final NotifyListener listener)
throws NacosException {
throws NacosException {
EventListener eventListener = new RegistryChildListenerImpl(serviceName, url, listener);
namingService.subscribe(serviceName,
getUrl().getGroup(Constants.DEFAULT_GROUP),
eventListener);
getUrl().getGroup(Constants.DEFAULT_GROUP),
eventListener);
}

/**
Expand Down Expand Up @@ -548,18 +548,18 @@ private void notifySubscriber(URL url, NotifyListener listener, Collection<Insta
*/
private List<String> getCategories(URL url) {
return ANY_VALUE.equals(url.getServiceInterface()) ?
ALL_SUPPORTED_CATEGORIES : Arrays.asList(DEFAULT_CATEGORY);
ALL_SUPPORTED_CATEGORIES : Arrays.asList(DEFAULT_CATEGORY);
}

private URL buildURL(URL consumerURL, Instance instance) {
Map<String, String> metadata = instance.getMetadata();
String protocol = metadata.get(PROTOCOL_KEY);
String path = metadata.get(PATH_KEY);
URL url = new ServiceConfigURL(protocol,
instance.getIp(),
instance.getPort(),
path,
instance.getMetadata());
instance.getIp(),
instance.getPort(),
path,
instance.getMetadata());
return new DubboServiceAddressURL(url.getUrlAddress(), url.getUrlParam(), consumerURL, null);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,8 @@ public static List<Instance> getAllCorrespondingServiceInstanceList(String servi
}
List<Instance> allInstances = Lists.newArrayList();
for (String correspondingServiceName : CORRESPONDING_SERVICE_NAMES_MAP.get(serviceName)) {
if (SERVICE_INSTANCE_LIST_MAP.containsKey(correspondingServiceName) && CollectionUtils.isNotEmpty(SERVICE_INSTANCE_LIST_MAP.get(correspondingServiceName))) {
if (SERVICE_INSTANCE_LIST_MAP.containsKey(correspondingServiceName)
&& CollectionUtils.isNotEmpty(SERVICE_INSTANCE_LIST_MAP.get(correspondingServiceName))) {
allInstances.addAll(SERVICE_INSTANCE_LIST_MAP.get(correspondingServiceName));
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.dubbo.registry.nacos;

import org.apache.dubbo.common.URL;
import org.apache.dubbo.common.utils.NetUtils;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

/**
* Test for NacosRegistryFactory
*/
public class NacosRegistryFactoryTest {

private NacosRegistryFactory nacosRegistryFactory;

@BeforeEach
public void setup() {
nacosRegistryFactory = new NacosRegistryFactory();
}

@AfterEach
public void teardown() {
}

@Test
public void testCreateRegistryCacheKey() {
URL url = URL.valueOf("dubbo://" + NetUtils.getLocalAddress().getHostAddress() + ":8080");
String registryCacheKey1 = nacosRegistryFactory.createRegistryCacheKey(url);
String registryCacheKey2 = nacosRegistryFactory.createRegistryCacheKey(url);
Assertions.assertEquals(registryCacheKey1, registryCacheKey2);
}

@Test
public void testCreateRegistryCacheKeyWithNamespace() {
URL url = URL.valueOf("dubbo://" + NetUtils.getLocalAddress().getHostAddress() + ":8080?namespace=test");
String registryCacheKey1 = nacosRegistryFactory.createRegistryCacheKey(url);
String registryCacheKey2 = nacosRegistryFactory.createRegistryCacheKey(url);
Assertions.assertEquals(registryCacheKey1, registryCacheKey2);
}

}
Loading

0 comments on commit 54b2096

Please sign in to comment.