Returns empty list when zookeeper throws NoNodeException.

This will allow apps that use DiscoveryClient to continue to function as services register.

This is a common occurrence in testing situations.

Fixes https://github.com/spring-cloud/spring-cloud-netflix/issues/2269
This commit is contained in:
Spencer Gibb
2018-03-19 11:52:50 -04:00
parent 6be07a3ad9
commit be1cd9302e
2 changed files with 23 additions and 0 deletions

View File

@@ -25,6 +25,8 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.curator.x.discovery.ServiceDiscovery;
import org.apache.curator.x.discovery.ServiceInstance;
import org.apache.zookeeper.KeeperException;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.zookeeper.discovery.dependency.ZookeeperDependencies;
import org.springframework.util.ReflectionUtils;
@@ -106,6 +108,13 @@ public class ZookeeperDiscoveryClient implements DiscoveryClient {
}
services = new ArrayList<>(names);
}
catch (KeeperException.NoNodeException e) {
if (log.isDebugEnabled()) {
log.debug("Error getting services from zookeeper. Possibly, no service has registered.", e);
}
// this means that nothing has registered as a service yes
return Collections.emptyList();
}
catch (Exception e) {
rethrowRuntimeException(e);
}

View File

@@ -3,10 +3,12 @@ package org.springframework.cloud.zookeeper.discovery;
import java.util.List;
import org.apache.curator.x.discovery.ServiceDiscovery;
import org.apache.zookeeper.KeeperException.NoNodeException;
import org.junit.Test;
import static org.assertj.core.api.BDDAssertions.then;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
/**
* @author Marcin Grzejszczak
@@ -22,4 +24,16 @@ public class ZookeeperDiscoveryClientTests {
// then:
then(services).isEmpty();
}
@Test
public void shouldReturnEmptyWhenNoNodeException() throws Exception {
// given:
ServiceDiscovery<ZookeeperInstance> serviceDiscovery = mock(ServiceDiscovery.class);
when(serviceDiscovery.queryForNames()).thenThrow(new NoNodeException());
ZookeeperDiscoveryClient discoveryClient = new ZookeeperDiscoveryClient(serviceDiscovery, null);
// when:
List<String> services = discoveryClient.getServices();
// then:
then(services).isEmpty();
}
}