org.springframework.cloud.client.DefaultServiceInstance Java Examples

The following examples show how to use org.springframework.cloud.client.DefaultServiceInstance. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CloudFoundryNativeReactiveDiscoveryClient.java    From spring-cloud-cloudfoundry with Apache License 2.0 6 votes vote down vote up
protected ServiceInstance mapApplicationInstanceToServiceInstance(
		Tuple2<ApplicationDetail, InstanceDetail> tuple) {
	ApplicationDetail applicationDetail = tuple.getT1();
	InstanceDetail instanceDetail = tuple.getT2();

	String applicationId = applicationDetail.getId();
	String applicationIndex = instanceDetail.getIndex();
	String instanceId = applicationId + "." + applicationIndex;
	String name = applicationDetail.getName();
	String url = applicationDetail.getUrls().size() > 0
			? applicationDetail.getUrls().get(0) : null;
	boolean secure = (url + "").toLowerCase().startsWith("https");

	HashMap<String, String> metadata = new HashMap<>();
	metadata.put("applicationId", applicationId);
	metadata.put("instanceId", applicationIndex);

	return new DefaultServiceInstance(instanceId, name, url, secure ? 443 : 80,
			secure, metadata);
}
 
Example #2
Source File: KubernetesDiscoveryClient.java    From spring-cloud-kubernetes with Apache License 2.0 6 votes vote down vote up
@Override
public ServiceInstance getLocalServiceInstance() {
    String serviceName = properties.getServiceName();
    String podName = System.getenv(HOSTNAME);
    ServiceInstance defaultInstance = new DefaultServiceInstance(serviceName, "localhost", 8080, false);

    Endpoints endpoints = client.endpoints().withName(serviceName).get();
    if (Utils.isNullOrEmpty(podName) || endpoints == null) {
        return defaultInstance;
    }
    try {
        return endpoints.getSubsets()
                .stream()
                .filter(s -> s.getAddresses().get(0).getTargetRef().getName().equals(podName))
                .map(s -> (ServiceInstance) new KubernetesServiceInstance(serviceName,
                        s.getAddresses().stream().findFirst().orElseThrow(IllegalStateException::new),
                        s.getPorts().stream().findFirst().orElseThrow(IllegalStateException::new),
                        false))
                .findFirst().orElse(defaultInstance);
    } catch (Throwable t) {
        return defaultInstance;
    }
}
 
Example #3
Source File: LandscapeWatcherTest.java    From microservices-dashboard with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldSkipFilteredApplicationInstances() {
	this.applicationInstanceFilters.add(serviceInstance -> "a-1".equalsIgnoreCase(serviceInstance.getInstanceId()));
	when(this.discoveryClient.getServices()).thenReturn(Collections.singletonList("a"));
	when(this.discoveryClient.getInstances("a")).thenReturn(
			Arrays.asList(new DefaultServiceInstance("a-1", "a", "host", 8080, false),
					new DefaultServiceInstance("a-2", "a", "host", 8080, false)));
	when(this.catalog.getApplicationInstancesForApplication("a")).thenReturn(Collections.singletonList("a-1"));

	this.landscapeWatcher.discoverLandscape();

	verify(this.discoveryClient).getServices();
	verify(this.discoveryClient).getInstances("a");

	verify(this.publisher).publishEvent(this.applicationEventArgumentCaptor.capture());
	verifyZeroInteractions(this.publisher);
}
 
Example #4
Source File: MicroserviceHandlerTest.java    From spring-cloud-huawei with Apache License 2.0 6 votes vote down vote up
@Test
public void getInstances(@Injectable ServiceCombClient serviceCombClient)
    throws ServiceCombException {
  ServiceCombDiscoveryProperties serviceCombDiscoveryProperties = new ServiceCombDiscoveryProperties();
  serviceCombDiscoveryProperties.setAppName("test");
  serviceCombDiscoveryProperties.setServiceName("testservice");
  serviceCombDiscoveryProperties.setVersion("latest");
  List<ServiceInstance> serviceInstanceList = new ArrayList<>();
  serviceInstanceList.add(
      new DefaultServiceInstance("111", "127.0.0.1", 1000, false));
  Microservice microservice = new Microservice();
  microservice.setServiceName("testservice");
  new Expectations() {
    {
      serviceCombClient.getInstances(microservice, anyString);
      result = serviceInstanceList;
    }
  };
  MicroserviceHandler.getInstances(microservice, serviceCombClient);
}
 
Example #5
Source File: DefaultServiceInstanceConverterTest.java    From Moss with Apache License 2.0 6 votes vote down vote up
@Test
public void test_convert_with_metadata() {
    ServiceInstance service = new DefaultServiceInstance("test-1", "test", "localhost", 80, false);
    Map<String, String> metadata = new HashMap<>();
    metadata.put("health.path", "ping");
    metadata.put("management.context-path", "mgmt");
    metadata.put("management.port", "1234");
    metadata.put("management.address", "127.0.0.1");
    service.getMetadata().putAll(metadata);

    Registration registration = new DefaultServiceInstanceConverter().convert(service);

    assertThat(registration.getName()).isEqualTo("test");
    assertThat(registration.getServiceUrl()).isEqualTo("http://localhost:80/");
    assertThat(registration.getManagementUrl()).isEqualTo("http://127.0.0.1:1234/mgmt");
    assertThat(registration.getHealthUrl()).isEqualTo("http://127.0.0.1:1234/mgmt/ping");
    assertThat(registration.getMetadata()).isEqualTo(metadata);
}
 
Example #6
Source File: InstanceDiscoveryListenerTest.java    From Moss with Apache License 2.0 6 votes vote down vote up
@Test
public void should_discover_instances_when_application_is_ready() {
    when(discovery.getServices()).thenReturn(Collections.singletonList("service"));
    when(discovery.getInstances("service")).thenReturn(Collections.singletonList(new DefaultServiceInstance("test-1",
        "service",
        "localhost",
        80,
        false
    )));

    listener.onApplicationReady(null);

    StepVerifier.create(registry.getInstances())
                .assertNext(a -> assertThat(a.getRegistration().getName()).isEqualTo("service"))
                .verifyComplete();
}
 
Example #7
Source File: InstanceDiscoveryListenerTest.java    From spring-boot-admin with Apache License 2.0 6 votes vote down vote up
@Test
public void should_register_instances_when_instanceMetadata_matches_wanted_metadata() {
	when(this.discovery.getServices()).thenReturn(asList("service", "rabbit-1", "rabbit-2"));
	when(this.discovery.getInstances("service")).thenReturn(singletonList(new DefaultServiceInstance("test-1",
			"service", "localhost", 80, false, Collections.singletonMap("monitoring", "true"))));
	when(this.discovery.getInstances("rabbit-1"))
			.thenReturn(singletonList(new DefaultServiceInstance("rabbit-test-1", "rabbit-1", "localhost", 80,
					false, Collections.singletonMap("monitoring", "false"))));
	when(this.discovery.getInstances("rabbit-2"))
			.thenReturn(singletonList(new DefaultServiceInstance("rabbit-test-1", "rabbit-2", "localhost", 80,
					false, Collections.singletonMap("monitoring", "false"))));

	this.listener.setInstancesMetadata(Collections.singletonMap("monitoring", "true"));
	this.listener.onInstanceRegistered(new InstanceRegisteredEvent<>(new Object(), null));

	StepVerifier.create(this.registry.getInstances())
			.assertNext((a) -> assertThat(a.getRegistration().getName()).isEqualTo("service")).verifyComplete();
}
 
Example #8
Source File: InstanceDiscoveryListenerTest.java    From spring-boot-admin with Apache License 2.0 6 votes vote down vote up
@Test
public void should_not_register_instances_when_instanceMetadata_matches_wanted_metadata_and_ignored_metadata() {
	when(this.discovery.getServices()).thenReturn(asList("service", "service-1"));
	when(this.discovery.getInstances("service")).thenReturn(singletonList(
			new DefaultServiceInstance("test-1", "service", "localhost", 80, false, new HashMap<String, String>() {
				{
					put("monitoring", "true");
					put("management", "true");
				}
			})));
	when(this.discovery.getInstances("service-1")).thenReturn(singletonList(new DefaultServiceInstance("test-1",
			"service-1", "localhost", 80, false, new HashMap<String, String>() {
				{
					put("monitoring", "true");
					put("management", "false");
				}
			})));

	this.listener.setInstancesMetadata(Collections.singletonMap("monitoring", "true"));
	this.listener.setIgnoredInstancesMetadata(Collections.singletonMap("management", "true"));
	this.listener.onInstanceRegistered(new InstanceRegisteredEvent<>(new Object(), null));

	StepVerifier.create(this.registry.getInstances())
			.assertNext((a) -> assertThat(a.getRegistration().getName()).isEqualTo("service-1")).verifyComplete();
}
 
Example #9
Source File: InstanceDiscoveryListenerTest.java    From Moss with Apache License 2.0 6 votes vote down vote up
@Test
public void should_not_register_instance_when_serviceId_matches_ignored_pattern() {
    when(discovery.getServices()).thenReturn(asList("service", "rabbit-1", "rabbit-2"));
    when(discovery.getInstances("service")).thenReturn(singletonList(new DefaultServiceInstance("test-1", "service",
        "localhost",
        80,
        false
    )));

    listener.setIgnoredServices(singleton("rabbit-*"));
    listener.onInstanceRegistered(new InstanceRegisteredEvent<>(new Object(), null));

    StepVerifier.create(registry.getInstances())
                .assertNext(a -> assertThat(a.getRegistration().getName()).isEqualTo("service"))
                .verifyComplete();
}
 
Example #10
Source File: InstanceDiscoveryListenerTest.java    From Moss with Apache License 2.0 6 votes vote down vote up
@Test
public void should_register_instances_when_serviceId_matches_wanted_pattern() {
    when(discovery.getServices()).thenReturn(asList("service", "rabbit-1", "rabbit-2"));
    when(discovery.getInstances("service")).thenReturn(singletonList(new DefaultServiceInstance("test-1", "service",
        "localhost",
        80,
        false
    )));

    listener.setServices(singleton("ser*"));
    listener.onInstanceRegistered(new InstanceRegisteredEvent<>(new Object(), null));

    StepVerifier.create(registry.getInstances())
                .assertNext(a -> assertThat(a.getRegistration().getName()).isEqualTo("service"))
                .verifyComplete();
}
 
Example #11
Source File: InstanceDiscoveryListenerTest.java    From Moss with Apache License 2.0 6 votes vote down vote up
@Test
public void should_register_instance_when_new_service_instance_is_discovered() {
    when(discovery.getServices()).thenReturn(singletonList("service"));
    when(discovery.getInstances("service")).thenReturn(singletonList(new DefaultServiceInstance("test-1", "service",
        "localhost",
        80,
        false
    )));

    listener.onInstanceRegistered(new InstanceRegisteredEvent<>(new Object(), null));

    StepVerifier.create(registry.getInstances()).assertNext(application -> {
        Registration registration = application.getRegistration();
        assertThat(registration.getHealthUrl()).isEqualTo("http://localhost:80/actuator/health");
        assertThat(registration.getManagementUrl()).isEqualTo("http://localhost:80/actuator");
        assertThat(registration.getServiceUrl()).isEqualTo("http://localhost:80/");
        assertThat(registration.getName()).isEqualTo("service");
    }).verifyComplete();


}
 
Example #12
Source File: InstanceDiscoveryListenerTest.java    From Moss with Apache License 2.0 6 votes vote down vote up
@Test
public void should_register_instances_when_serviceId_matches_wanted_pattern_and_igonred_pattern() {
    when(discovery.getServices()).thenReturn(asList("service-1", "service", "rabbit-1", "rabbit-2"));
    when(discovery.getInstances("service")).thenReturn(singletonList(new DefaultServiceInstance("test-1", "service",
        "localhost",
        80,
        false
    )));
    when(discovery.getInstances("service-1")).thenReturn(singletonList(new DefaultServiceInstance("test-1",
        "service-1",
        "localhost",
        80,
        false
    )));

    listener.setServices(singleton("ser*"));
    listener.setIgnoredServices(singleton("service-*"));
    listener.onInstanceRegistered(new InstanceRegisteredEvent<>(new Object(), null));

    StepVerifier.create(registry.getInstances())
                .assertNext(a -> assertThat(a.getRegistration().getName()).isEqualTo("service"))
                .verifyComplete();
}
 
Example #13
Source File: InstanceDiscoveryListenerTest.java    From Moss with Apache License 2.0 6 votes vote down vote up
@Test
public void should_only_discover_new_instances_when_new_heartbeat_is_emitted() {
    Object heartbeat = new Object();
    listener.onParentHeartbeat(new ParentHeartbeatEvent(new Object(), heartbeat));

    when(discovery.getServices()).thenReturn(singletonList("service"));
    when(discovery.getInstances("service")).thenReturn(singletonList(new DefaultServiceInstance("test-1", "service",
        "localhost",
        80,
        false
    )));

    listener.onApplicationEvent(new HeartbeatEvent(new Object(), heartbeat));
    StepVerifier.create(registry.getInstances()).verifyComplete();

    listener.onApplicationEvent(new HeartbeatEvent(new Object(), new Object()));
    StepVerifier.create(registry.getInstances())
                .assertNext(a -> assertThat(a.getRegistration().getName()).isEqualTo("service"))
                .verifyComplete();
}
 
Example #14
Source File: InstanceDiscoveryListenerTest.java    From Moss with Apache License 2.0 6 votes vote down vote up
@Test
public void should_not_throw_error_when_conversion_fails_and_proceed_with_next_instance() {
    when(discovery.getServices()).thenReturn(singletonList("service"));
    when(discovery.getInstances("service")).thenReturn(asList(new DefaultServiceInstance("test-1", "service",
        "localhost",
        80,
        false
    ), new DefaultServiceInstance("error-1", "error", "localhost", 80, false)));
    listener.setConverter(instance -> {
        if (instance.getServiceId().equals("error")) {
            throw new IllegalStateException("Test-Error");
        } else {
            return new DefaultServiceInstanceConverter().convert(instance);
        }
    });

    listener.onInstanceRegistered(new InstanceRegisteredEvent<>(new Object(), null));

    StepVerifier.create(registry.getInstances())
                .assertNext(a -> assertThat(a.getRegistration().getName()).isEqualTo("service"))
                .verifyComplete();
}
 
Example #15
Source File: LandscapeWatcherTest.java    From microservices-dashboard with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldDispatchEventWhenServiceInstanceDisappeared() {
	when(this.discoveryClient.getServices()).thenReturn(Collections.singletonList("a"));
	when(this.catalog.getApplications()).thenReturn(Collections.singletonList("a"));
	ServiceInstance serviceInstance = new DefaultServiceInstance("a-1", "a", "host", 8080, false);
	when(this.discoveryClient.getInstances("a")).thenReturn(Collections.singletonList(serviceInstance));
	when(this.catalog.getApplicationInstancesForApplication("a")).thenReturn(Arrays.asList("a-1", "a-2"));

	this.landscapeWatcher.discoverLandscape();

	verify(this.catalogService, times(2)).getCatalog();
	verifyNoMoreInteractions(this.catalogService);

	verify(this.discoveryClient).getServices();
	verify(this.discoveryClient).getInstances("a");
	verifyNoMoreInteractions(this.discoveryClient);

	verify(this.publisher).publishEvent(this.applicationEventArgumentCaptor.capture());
	verifyNoMoreInteractions(this.publisher);
	ApplicationEvent event = this.applicationEventArgumentCaptor.getValue();
	assertThat(event).isInstanceOfSatisfying(ServiceInstanceDisappeared.class,
			e -> assertThat(e.getSource()).isEqualTo("a-2"));
}
 
Example #16
Source File: FeignBlockingLoadBalancerClientTests.java    From spring-cloud-openfeign with Apache License 2.0 6 votes vote down vote up
@Test
void shouldPassCorrectRequestToDelegate() throws IOException {
	Request request = testRequest();
	Request.Options options = new Request.Options();
	String url = "http://127.0.0.1/path";
	ServiceInstance serviceInstance = new DefaultServiceInstance("test-1", "test",
			"test-host", 8888, false);
	when(loadBalancerClient.choose("test")).thenReturn(serviceInstance);
	when(loadBalancerClient.reconstructURI(serviceInstance,
			URI.create("http://test/path"))).thenReturn(URI.create(url));

	feignBlockingLoadBalancerClient.execute(request, options);

	ArgumentCaptor<Request> captor = ArgumentCaptor.forClass(Request.class);
	verify(delegate, times(1)).execute(captor.capture(), eq(options));
	Request actualRequest = captor.getValue();
	assertThat(actualRequest.httpMethod()).isEqualTo(Request.HttpMethod.GET);
	assertThat(actualRequest.url()).isEqualTo(url);
	assertThat(actualRequest.headers()).hasSize(1);
	assertThat(actualRequest.headers()).containsEntry(HttpHeaders.CONTENT_TYPE,
			Collections.singletonList(MediaType.APPLICATION_JSON_VALUE));
	assertThat(new String(actualRequest.body())).isEqualTo("hello");
}
 
Example #17
Source File: InstanceDiscoveryListenerTest.java    From spring-boot-admin with Apache License 2.0 6 votes vote down vote up
@Test
public void should_register_instance_when_new_service_instance_is_discovered() {
	when(this.discovery.getServices()).thenReturn(singletonList("service"));
	when(this.discovery.getInstances("service"))
			.thenReturn(singletonList(new DefaultServiceInstance("test-1", "service", "localhost", 80, false)));

	this.listener.onInstanceRegistered(new InstanceRegisteredEvent<>(new Object(), null));

	StepVerifier.create(this.registry.getInstances()).assertNext((application) -> {
		Registration registration = application.getRegistration();
		assertThat(registration.getHealthUrl()).isEqualTo("http://localhost:80/actuator/health");
		assertThat(registration.getManagementUrl()).isEqualTo("http://localhost:80/actuator");
		assertThat(registration.getServiceUrl()).isEqualTo("http://localhost:80");
		assertThat(registration.getName()).isEqualTo("service");
	}).verifyComplete();
}
 
Example #18
Source File: DiscoveryClientConfigServiceBootstrapConfigurationTests.java    From spring-cloud-config with Apache License 2.0 6 votes vote down vote up
@Test
public void multipleInstancesReturnedFromDiscovery() {
	ServiceInstance info1 = new DefaultServiceInstance("app1:8888", "app",
			"localhost", 8888, true);
	ServiceInstance info2 = new DefaultServiceInstance("app2:8888", "app",
			"localhost1", 8888, false);
	givenDiscoveryClientReturnsInfoForMultipleInstances(info1, info2);

	setup("spring.cloud.config.discovery.enabled=true");

	expectDiscoveryClientConfigServiceBootstrapConfigurationIsSetup();

	verifyDiscoveryClientCalledOnce();
	expectConfigClientPropertiesHasMultipleUris("https://localhost:8888/",
			"http://localhost1:8888/");

}
 
Example #19
Source File: SimpleDnsBasedDiscoveryClient.java    From spring-cloud-cloudfoundry with Apache License 2.0 6 votes vote down vote up
@Override
public List<ServiceInstance> getInstances(String serviceId) {
	String hostname = this.serviceIdToHostnameConverter.toHostname(serviceId);
	try {
		List<ServiceInstance> serviceInstances = new ArrayList<>();
		InetAddress[] addresses = InetAddress.getAllByName(hostname);
		if (addresses != null) {
			for (InetAddress address : addresses) {
				DefaultServiceInstance serviceInstance = new DefaultServiceInstance(
						serviceId, address.getHostAddress(), 8080, false);
				serviceInstances.add(serviceInstance);
			}
		}
		return serviceInstances;
	}
	catch (UnknownHostException e) {
		log.warn("{}", e.getMessage());
		return Collections.emptyList();
	}
}
 
Example #20
Source File: ConsulDiscoveryClient.java    From spring-cloud-consul with Apache License 2.0 6 votes vote down vote up
private void addInstancesToList(List<ServiceInstance> instances, String serviceId,
		QueryParams queryParams) {

	HealthServicesRequest request = HealthServicesRequest.newBuilder()
			.setTag(this.properties.getDefaultQueryTag())
			.setPassing(this.properties.isQueryPassing()).setQueryParams(queryParams)
			.setToken(this.properties.getAclToken()).build();
	Response<List<HealthService>> services = this.client.getHealthServices(serviceId,
			request);

	for (HealthService service : services.getValue()) {
		String host = findHost(service);

		Map<String, String> metadata = service.getService().getMeta();
		if (metadata == null) {
			metadata = new LinkedHashMap<>();
		}
		boolean secure = false;
		if (metadata.containsKey("secure")) {
			secure = Boolean.parseBoolean(metadata.get("secure"));
		}
		instances.add(new DefaultServiceInstance(service.getService().getId(),
				serviceId, host, service.getService().getPort(), secure, metadata));
	}
}
 
Example #21
Source File: GatewayHomepageControllerTest.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void givenZOSMFProviderWithOneInstance_whenHomePageCalled_thenHomePageModelShouldContain() {
    ServiceInstance serviceInstance = new DefaultServiceInstance("instanceId", "serviceId",
        "host", 10000, true);
    when(discoveryClient.getInstances("zosmf")).thenReturn(
        Arrays.asList(serviceInstance)
    );

    authConfigurationProperties.setProvider("zosmf");
    authConfigurationProperties.setZosmfServiceId("zosmf");

    Model model = new ConcurrentModel();
    gatewayHomepageController.home(model);

    Map<String, Object> actualModelMap = model.asMap();

    assertThat(actualModelMap, IsMapContaining.hasEntry("authIconName", "success"));
    assertThat(actualModelMap, IsMapContaining.hasEntry("authStatusText", "The Authentication service is running"));
}
 
Example #22
Source File: CloudFoundryDiscoveryClient.java    From spring-cloud-cloudfoundry with Apache License 2.0 6 votes vote down vote up
@Override
public List<ServiceInstance> getInstances(String serviceId) {
	return this.cloudFoundryService.getApplicationInstances(serviceId).map(tuple -> {
		ApplicationDetail applicationDetail = tuple.getT1();
		InstanceDetail instanceDetail = tuple.getT2();

		String applicationId = applicationDetail.getId();
		String applicationIndex = instanceDetail.getIndex();
		String instanceId = applicationId + "." + applicationIndex;
		String name = applicationDetail.getName();
		String url = applicationDetail.getUrls().size() > 0
				? applicationDetail.getUrls().get(0) : null;
		boolean secure = (url + "").toLowerCase().startsWith("https");

		HashMap<String, String> metadata = new HashMap<>();
		metadata.put("applicationId", applicationId);
		metadata.put("instanceId", applicationIndex);

		return (ServiceInstance) new DefaultServiceInstance(instanceId, name, url,
				secure ? 443 : 80, secure, metadata);
	}).collectList().blockOptional().orElse(new ArrayList<>());
}
 
Example #23
Source File: CloudFoundryAppServiceDiscoveryClient.java    From spring-cloud-cloudfoundry with Apache License 2.0 6 votes vote down vote up
@Override
public List<ServiceInstance> getInstances(String serviceId) {
	return getCloudFoundryService()
			.getApplicationInstances(serviceId).filter(tuple -> tuple.getT1()
					.getUrls().stream().anyMatch(this::isInternalDomain))
			.map(tuple -> {
				ApplicationDetail applicationDetail = tuple.getT1();
				InstanceDetail instanceDetail = tuple.getT2();
				String applicationId = applicationDetail.getId();
				String applicationIndex = instanceDetail.getIndex();
				String name = applicationDetail.getName();
				String url = applicationDetail.getUrls().stream()
						.filter(this::isInternalDomain).findFirst()
						.map(x -> instanceDetail.getIndex() + "." + x).get();
				HashMap<String, String> metadata = new HashMap<>();
				metadata.put("applicationId", applicationId);
				metadata.put("instanceId", applicationIndex);
				return (ServiceInstance) new DefaultServiceInstance(name, url, 8080,
						false, metadata);
			}).collectList().block();
}
 
Example #24
Source File: InstanceDiscoveryListenerTest.java    From spring-boot-admin with Apache License 2.0 6 votes vote down vote up
@Test
public void should_only_discover_new_instances_when_new_heartbeat_is_emitted() {
	Object heartbeat = new Object();
	this.listener.onParentHeartbeat(new ParentHeartbeatEvent(new Object(), heartbeat));

	when(this.discovery.getServices()).thenReturn(singletonList("service"));
	when(this.discovery.getInstances("service"))
			.thenReturn(singletonList(new DefaultServiceInstance("test-1", "service", "localhost", 80, false)));

	this.listener.onApplicationEvent(new HeartbeatEvent(new Object(), heartbeat));
	StepVerifier.create(this.registry.getInstances()).verifyComplete();

	this.listener.onApplicationEvent(new HeartbeatEvent(new Object(), new Object()));
	StepVerifier.create(this.registry.getInstances())
			.assertNext((a) -> assertThat(a.getRegistration().getName()).isEqualTo("service")).verifyComplete();
}
 
Example #25
Source File: LandscapeWatcherTest.java    From microservices-dashboard with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldDispatchDiscoveredEventsOnFirstHeartbeatEvent() {
	when(this.discoveryClient.getServices()).thenReturn(Collections.singletonList("a"));
	ServiceInstance serviceInstance = new DefaultServiceInstance("a-1", "a", "host", 8080, false);
	when(this.discoveryClient.getInstances("a")).thenReturn(Collections.singletonList(serviceInstance));

	this.landscapeWatcher.discoverLandscape();

	verify(this.catalogService, times(2)).getCatalog();
	verifyNoMoreInteractions(this.catalogService);

	verify(this.discoveryClient).getServices();
	verify(this.discoveryClient).getInstances("a");
	verifyNoMoreInteractions(this.discoveryClient);

	verify(this.publisher, times(2)).publishEvent(this.applicationEventArgumentCaptor.capture());
	verifyNoMoreInteractions(this.publisher);
	List<ApplicationEvent> applicationEvents = this.applicationEventArgumentCaptor.getAllValues();

	ApplicationEvent event = applicationEvents.get(0);
	assertThat(event).isInstanceOfSatisfying(ServiceDiscovered.class,
			e -> assertThat(e.getSource()).isEqualTo("a"));

	event = applicationEvents.get(1);
	assertThat(event).isInstanceOfSatisfying(ServiceInstanceDiscovered.class,
			e -> assertThat(e.getSource()).isEqualTo(serviceInstance));
}
 
Example #26
Source File: ReactiveLoadBalancerClientFilterTests.java    From spring-cloud-gateway with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void shouldFilter() {
	URI url = UriComponentsBuilder.fromUriString("lb://myservice").build().toUri();
	exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, url);

	ServiceInstance serviceInstance = new DefaultServiceInstance("myservice1",
			"myservice", "localhost", 8080, true);

	RoundRobinLoadBalancer loadBalancer = new RoundRobinLoadBalancer(
			ServiceInstanceListSuppliers.toProvider("myservice", serviceInstance),
			"myservice", -1);
	when(clientFactory.getInstance("myservice", ReactorLoadBalancer.class,
			ServiceInstance.class)).thenReturn(loadBalancer);

	when(chain.filter(exchange)).thenReturn(Mono.empty());

	filter.filter(exchange, chain).block();

	assertThat((LinkedHashSet<URI>) exchange
			.getAttribute(GATEWAY_ORIGINAL_REQUEST_URL_ATTR)).contains(url);

	verify(clientFactory).getInstance("myservice", ReactorLoadBalancer.class,
			ServiceInstance.class);

	verifyNoMoreInteractions(clientFactory);

	assertThat((URI) exchange.getAttribute(GATEWAY_REQUEST_URL_ATTR))
			.isEqualTo(URI.create("https://localhost:8080/mypath"));

	verify(chain).filter(exchange);
	verifyNoMoreInteractions(chain);
}
 
Example #27
Source File: DiscoveryClientChannelLocatorTests.java    From spring-bus with Apache License 2.0 5 votes vote down vote up
@Before
public void init() {
	this.locator.setRestTemplate(this.restTemplate);
	this.metadata.setModule(new MessageBusProperties());
	this.metadata.setInputChannels(new HashSet<InputChannelBinding>());
	this.metadata.setOutputChannels(new HashSet<OutputChannelBinding>());
	Mockito.when(
			this.restTemplate.getForObject(Mockito.any(URI.class), anyChannels()))
			.thenReturn(this.metadata);
	Mockito.when(this.client.getInstances(Mockito.anyString())).thenReturn(
			Arrays.asList(new DefaultServiceInstance("service", "example.com", 888, false)));
}
 
Example #28
Source File: InstanceDiscoveryListenerTest.java    From spring-boot-admin with Apache License 2.0 5 votes vote down vote up
@Test
public void should_not_register_instance_when_instanceMetadata_is_ignored() {
	when(this.discovery.getServices()).thenReturn(singletonList("service"));
	when(this.discovery.getInstances("service")).thenReturn(singletonList(new DefaultServiceInstance("test-1",
			"service", "localhost", 80, false, Collections.singletonMap("monitoring", "false"))));

	this.listener.setIgnoredInstancesMetadata(Collections.singletonMap("monitoring", "false"));
	this.listener.onInstanceRegistered(new InstanceRegisteredEvent<>(new Object(), null));

	StepVerifier.create(this.registry.getInstances()).verifyComplete();
}
 
Example #29
Source File: HealthCheckServiceInstanceListSupplierTests.java    From spring-cloud-commons with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("ConstantConditions")
@Test
void shouldCheckInstanceWithProvidedHealthCheckPath() {
	healthCheck.getPath().put("ignored-service", "/health");
	listSupplier = new HealthCheckServiceInstanceListSupplier(
			ServiceInstanceListSupplier.fixed("ignored-service").build(), healthCheck,
			webClient);
	ServiceInstance serviceInstance = new DefaultServiceInstance("ignored-service-1",
			"ignored-service", "127.0.0.1", port, false);

	boolean alive = listSupplier.isAlive(serviceInstance).block();

	assertThat(alive).isTrue();
}
 
Example #30
Source File: MarathonDiscoveryClient.java    From spring-cloud-marathon with MIT License 5 votes vote down vote up
/**
 * Extract instances of a service for a specific marathon application
 *
 * @param app
 * @return
 */
public List<ServiceInstance> extractServiceInstances(App app) {
    log.debug("Discovered service [{}]", app.getId());

    if (app.getTasks().isEmpty()) {
        return Collections.emptyList();
    }

    return app.getTasks()
            .parallelStream()
            .filter(task -> null == task.getHealthCheckResults() ||
                    task.getHealthCheckResults()
                            .stream()
                            .allMatch(HealthCheckResults::getAlive)
            )
            .map(task -> new DefaultServiceInstance(
                    ServiceIdConverter.convertToServiceId(task.getAppId()),
                    task.getHost(),
                    task.getPorts().stream().findFirst().orElse(0),
                    false
            )).map(serviceInstance -> {
                if (app.getLabels() != null && !app.getLabels().isEmpty())
                    serviceInstance.getMetadata().putAll(app.getLabels());
                return serviceInstance;
            })
            .collect(Collectors.toList());
}