diff --git a/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/discovery/ConsulDiscoveryClient.java b/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/discovery/ConsulDiscoveryClient.java index bfd542ee0..006ae7c0d 100644 --- a/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/discovery/ConsulDiscoveryClient.java +++ b/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/discovery/ConsulDiscoveryClient.java @@ -32,6 +32,7 @@ import org.springframework.cloud.client.DefaultServiceInstance; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.discovery.DiscoveryClient; +import org.springframework.util.CollectionUtils; import static org.springframework.cloud.consul.discovery.ConsulServerUtils.findHost; import static org.springframework.cloud.consul.discovery.ConsulServerUtils.getMetadata; @@ -62,8 +63,17 @@ public String description() { @Override public List getInstances(final String serviceId) { - return getInstances(serviceId, - new QueryParams(this.properties.getConsistencyMode())); + + List instances = getInstances(serviceId, + new QueryParams(this.properties.getConsistencyMode())); + + if (CollectionUtils.isEmpty(instances) && !CollectionUtils.isEmpty(this.properties.getFailoverDataCenters())) { + for (String dc : this.properties.getFailoverDataCenters()) { + instances.addAll(getInstances(serviceId, new QueryParams(dc, this.properties.getConsistencyMode()))); + } + } + + return instances; } public List getInstances(final String serviceId, diff --git a/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/discovery/ConsulDiscoveryProperties.java b/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/discovery/ConsulDiscoveryProperties.java index e650370d3..5de16b537 100644 --- a/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/discovery/ConsulDiscoveryProperties.java +++ b/spring-cloud-consul-discovery/src/main/java/org/springframework/cloud/consul/discovery/ConsulDiscoveryProperties.java @@ -204,6 +204,12 @@ public class ConsulDiscoveryProperties { */ private int order = 0; + /** + * List of data centers to look for service instances in, if there are + * no instances of wanted service in local data center. + */ + private List failoverDataCenters; + @SuppressWarnings("unused") private ConsulDiscoveryProperties() { this.managementTags.add(MANAGEMENT); @@ -589,6 +595,14 @@ public void setManagementEnableTagOverride(Boolean managementEnableTagOverride) this.managementEnableTagOverride = managementEnableTagOverride; } + public List getFailoverDataCenters() { + return this.failoverDataCenters; + } + + public void setFailoverDataCenters(List failoverDataCenters) { + this.failoverDataCenters = failoverDataCenters; + } + @Override public String toString() { return new ToStringCreator(this).append("hostInfo", this.hostInfo) @@ -626,6 +640,7 @@ public String toString() { .append("register", this.register).append("deregister", this.deregister) .append("registerHealthCheck", this.registerHealthCheck) .append("failFast", this.failFast) + .append("failoverDataCenters", this.failoverDataCenters) .append("healthCheckTlsSkipVerify", this.healthCheckTlsSkipVerify) .append("order", this.order).append("tagsAsMetadata", this.tagsAsMetadata) .append("enableTagOverride", this.enableTagOverride) diff --git a/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/ConsulDiscoveryClientMultipleDataCentersTests.java b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/ConsulDiscoveryClientMultipleDataCentersTests.java new file mode 100644 index 000000000..3e4d3e02b --- /dev/null +++ b/spring-cloud-consul-discovery/src/test/java/org/springframework/cloud/consul/discovery/ConsulDiscoveryClientMultipleDataCentersTests.java @@ -0,0 +1,113 @@ +/* + * Copyright 2013-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.cloud.consul.discovery; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +import com.ecwid.consul.v1.ConsulClient; +import com.ecwid.consul.v1.Response; +import com.ecwid.consul.v1.health.model.HealthService; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.util.StringUtils; + +import static java.util.Collections.singletonList; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.argThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; + +/** + * @author Vojislav Cuk + */ +@RunWith(SpringRunner.class) +@SpringBootTest( + properties = { "spring.application.name=testConsulDiscovery", + "spring.cloud.consul.discovery.prefer-ip-address=true", + "spring.cloud.consul.discovery.metadata[foo]=bar", + "spring.cloud.consul.discovery.failoverDataCenters[0]=dc2" }, + webEnvironment = RANDOM_PORT) +public class ConsulDiscoveryClientMultipleDataCentersTests { + + @Autowired + private ConsulDiscoveryClient discoveryClient; + + @MockBean + private ConsulClient consulClient; + + @Test + public void getInstancesShouldReturnEmptyListWhenThereAreNoInstancesInLocalNorFailoverDataCenters() { + + Mockito.when(consulClient.getHealthServices(eq("testService"), any())).thenReturn( + new Response<>(new ArrayList<>(), 0L, true, System.currentTimeMillis())); + + assertThat(discoveryClient.getInstances("testService")).isEmpty(); + } + + @Test + public void getInstancesShouldReturnInstancesFromFailoverDataCentersWhenNoInstanceInLocalDataCenterIsAvailable() { + + Mockito.when(consulClient.getHealthServices(eq("testService"), + argThat(r -> !StringUtils.hasLength(r.getDatacenter())))) + .thenReturn(new Response<>(new ArrayList<>(), 0L, true, + System.currentTimeMillis())); + + Response> response = consulInstancesResponse(); + Mockito.when(consulClient.getHealthServices(eq("testService"), + argThat(r -> Objects.equals(r.getQueryParams().getDatacenter(), "dc2")))) + .thenReturn(response); + + assertThat(discoveryClient.getInstances("testService")).isNotEmpty(); + } + + private Response> consulInstancesResponse() { + + HealthService healthService = mock(HealthService.class); + HealthService.Service service = mock(HealthService.Service.class); + + when(healthService.getService()).thenReturn(service); + when(service.getAddress()).thenReturn("localhost"); + when(service.getPort()).thenReturn(443); + lenient().when(service.getTags()).thenReturn(singletonList("secure=true")); + + return new Response<>(singletonList(healthService), 0L, true, + System.currentTimeMillis()); + } + + @Configuration(proxyBeanMethods = false) + @EnableAutoConfiguration + @EnableDiscoveryClient + public static class MyTestConfig { + + } + +}