com.netflix.discovery.shared.Applications Java Examples

The following examples show how to use com.netflix.discovery.shared.Applications. 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: EurekaResource.java    From karyon with Apache License 2.0 6 votes vote down vote up
@GET
public Response getEurekaDetails() {
    List<EurekaInstanceInfo> instanceInfoList = new ArrayList<EurekaInstanceInfo>();

    DiscoveryClient discoveryClient = DiscoveryManager.getInstance().getDiscoveryClient();
    if (null != discoveryClient) {
        Applications apps = discoveryClient.getApplications();
        for (Application app : apps.getRegisteredApplications()) {
            for (InstanceInfo inst : app.getInstances()) {
                instanceInfoList.add(new EurekaInstanceInfo(inst.getAppName(), inst.getId(), inst.getStatus().name(), inst.getIPAddr(), inst.getHostName()));
            }
        }
    }

    GsonBuilder gsonBuilder = new GsonBuilder().serializeNulls();
    Gson gson = gsonBuilder.create();
    String response = gson.toJson(new KaryonAdminResponse(instanceInfoList));
    return Response.ok(response).build();
}
 
Example #2
Source File: InstanceRetrievalService.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Parse information from the response and extract the Applications object which contains all the registry information returned by eureka server
 *
 * @param requestInfo contains the pair of discovery URL and discovery credentials (for HTTP access)
 * @param response    the http response
 * @return Applications object that wraps all the registry information
 */
private Applications extractApplications(Pair<String, Pair<String, String>> requestInfo, ResponseEntity<String> response) {
    Applications applications = null;
    if (!HttpStatus.OK.equals(response.getStatusCode()) || response.getBody() == null) {
        apimlLog.log("org.zowe.apiml.apicatalog.serviceRetrievalRequestFailed", response.getStatusCode(), response.getStatusCode().getReasonPhrase(), requestInfo.getLeft());
    } else {
        ObjectMapper mapper = new EurekaJsonJacksonCodec().getObjectMapper(Applications.class);
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        try {
            applications = mapper.readValue(response.getBody(), Applications.class);
        } catch (IOException e) {
            apimlLog.log("org.zowe.apiml.apicatalog.serviceRetrievalParsingFailed", e.getMessage());
        }
    }
    return applications;
}
 
Example #3
Source File: InstanceRefreshService.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * @return a list of changed services
 */
@SuppressWarnings("deprecation")
private Set<String> compareServices() {
    // Updated containers
    Set<String> containersUpdated = new HashSet<>();
    Applications cachedServices = cachedServicesService.getAllCachedServices();
    Applications deltaFromDiscovery = instanceRetrievalService.getAllInstancesFromDiscovery(true);

    if (deltaFromDiscovery != null && !deltaFromDiscovery.getRegisteredApplications().isEmpty()) {
        // use the version to check if this delta has changed, it is deprecated and should be replaced as soon as a
        // newer identifier is provided by Netflix
        // if getVersion is removed then the process will be slightly more inefficient but will not need to change
        if (cachedServicesService.getVersionDelta() != deltaFromDiscovery.getVersion()) {
            containersUpdated = processServiceInstances(cachedServices, deltaFromDiscovery);
        }
        cachedServicesService.setVersionDelta(deltaFromDiscovery.getVersion());
    }
    return containersUpdated;
}
 
Example #4
Source File: MossInstanceDiscoveryListener.java    From Moss with Apache License 2.0 6 votes vote down vote up
public List<String> getServicesByEureka() {
    Applications applications = cloudEurekaClient.get().getApplications();
    if (applications == null) {
        return Collections.emptyList();
    }
    List<Application> registered = applications.getRegisteredApplications();
    List<String> names = new ArrayList<>();
    for (Application app : registered) {
        if (app.getInstances().isEmpty()) {
            continue;
        }
        names.add(app.getName().toLowerCase());

    }
    return names;
}
 
Example #5
Source File: InstanceRefreshService.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Get this instance service details and check if it should be processed
 *
 * @param containersUpdated  containers, which were updated
 * @param cachedServices     existing services
 * @param deltaFromDiscovery changed service instances
 * @param instance           this instance
 */
private void processServiceInstance(Set<String> containersUpdated, Applications cachedServices,
                                    Applications deltaFromDiscovery, InstanceInfo instance) {
    Application application = null;
    // Get the application which this instance belongs to
    if (cachedServices != null && cachedServices.getRegisteredApplications() != null) {
        application = cachedServices.getRegisteredApplications().stream()
            .filter(service -> service.getName().equalsIgnoreCase(instance.getAppName())).findFirst().orElse(null);
    }
    // if its new then it will only be in the delta
    if (application == null || application.getInstances().isEmpty()) {
        application = deltaFromDiscovery.getRegisteredApplications().stream()
            .filter(service -> service.getName().equalsIgnoreCase(instance.getAppName())).findFirst().orElse(null);
    }

    // there's no chance which this case is not called. It's just double check
    if (application == null || application.getInstances().isEmpty()) {
        log.debug("Instance {} couldn't get details from cache and delta", instance.getAppName());
        return;
    }

    processInstance(containersUpdated, instance, application);
}
 
Example #6
Source File: InstanceRefreshService.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Compare cached instances against eureka delta to send back a change-list
 *
 * @param delta retrieved from Eureka
 * @return changed instances
 */
private Set<InstanceInfo> updateDelta(Applications delta) {
    int deltaCount = 0;
    Set<InstanceInfo> updatedInstances = new HashSet<>();
    for (Application app : delta.getRegisteredApplications()) {
        for (InstanceInfo instance : app.getInstances()) {
            ++deltaCount;
            if (InstanceInfo.ActionType.ADDED.equals(instance.getActionType())) {
                log.debug("Added instance {} to the list of changed instances ", instance.getId());
                updatedInstances.add(instance);
            } else if (InstanceInfo.ActionType.MODIFIED.equals(instance.getActionType())) {
                log.debug("Modified instance {} added to the list of changed instances ", instance.getId());
                updatedInstances.add(instance);
            } else if (InstanceInfo.ActionType.DELETED.equals(instance.getActionType())) {
                log.debug("Deleted instance {} added to the list of changed instances ", instance.getId());
                instance.setStatus(InstanceInfo.InstanceStatus.DOWN);
                updatedInstances.add(instance);
            }
        }
    }

    log.debug("The total number of changed instances fetched by the delta processor : {}", deltaCount);
    return updatedInstances;
}
 
Example #7
Source File: InstanceRetrievalServiceTest.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testGetAllInstancesFromDiscovery_whenNeedApplicationsWithoutFilter() throws JsonProcessingException {
    Map<String, InstanceInfo> instanceInfoMap = createInstances();


    Applications expectedApplications = new Applications();
    instanceInfoMap.forEach((key, value) -> expectedApplications.addApplication(new Application(value.getAppName(), Collections.singletonList(value))));

    ObjectMapper mapper = new ObjectMapper();
    String bodyAll = mapper.writeValueAsString(new ApplicationsWrapper(expectedApplications));
    mockRetrieveApplicationService(discoveryServiceAllAppsUrl, bodyAll);

    Applications actualApplications = instanceRetrievalService.getAllInstancesFromDiscovery(false);

    assertEquals(expectedApplications.size(), actualApplications.size());

    List<Application> actualApplicationList =
        new ArrayList<>(actualApplications.getRegisteredApplications());


    expectedApplications
        .getRegisteredApplications()
        .forEach(expectedApplication ->
            assertThat(actualApplicationList, hasItem(hasProperty("name", equalTo(expectedApplication.getName()))))
        );
}
 
Example #8
Source File: CachedServicesServiceTest.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testGetAService() {
    CachedServicesService cachedServicesService = new CachedServicesService();
    cachedServicesService.clearAllServices();
    Applications applications = cachedServicesService.getAllCachedServices();
    Assert.assertNull(applications);

    InstanceInfo instance = getStandardInstance("service", InstanceInfo.InstanceStatus.DOWN, null);
    Application application = new Application("service");
    application.addInstance(instance);
    cachedServicesService.updateService("service", application);

    Application service = cachedServicesService.getService("service");
    Assert.assertNotNull(service);
    Assert.assertEquals("service", service.getName());
}
 
Example #9
Source File: ServiceControllerTest.java    From eureka-consul-adapter with MIT License 6 votes vote down vote up
@Test(timeout = 10000)
public void services_asyncChangesToMs1_interruptOnChange() throws Exception {

    Applications applications = mock2Applications();
    Mockito.when(registry.getApplications()).thenReturn(applications);

    startThread(() -> {
        sleepFor(1000);
        serviceChangeDetector.publish("ms1", 2);
        sleepFor(1000);
        serviceChangeDetector.publish("ms1", 3);
    });

    performAsync("/v1/catalog/services?wait=30s")
            .andExpect(content().contentType("application/json;charset=UTF-8"))
            .andExpect(header().string("X-Consul-Index", "1"))
            .andExpect(jsonPath("$.ms1", Matchers.is(new JSONArray())))
            .andExpect(jsonPath("$.ms2", Matchers.is(new JSONArray())));

    performAsync("/v1/catalog/services?wait=30s&index=1")
            .andExpect(content().contentType("application/json;charset=UTF-8"))
            .andExpect(header().string("X-Consul-Index", "2"))
            .andExpect(jsonPath("$.ms1", Matchers.is(new JSONArray())))
            .andExpect(jsonPath("$.ms2", Matchers.is(new JSONArray())));

}
 
Example #10
Source File: ServiceControllerTest.java    From eureka-consul-adapter with MIT License 6 votes vote down vote up
@Test
public void service_sampleService_jsonObject_preferHostName() throws Exception {

    Applications applications = mock2Applications();
    Mockito.when(registry.getApplications()).thenReturn(applications);
    Application ms1 = applications.getRegisteredApplications().get(0);

    InstanceInfo instance1 = mock1Instance();
    ms1.addInstance(instance1);

    InstanceInfo instance2 = mock1Instance("2","1.2.3.5", "2.ms1.com", 81, true);
    ms1.addInstance(instance2);

    Mockito.when(registry.getApplication("ms1")).thenReturn(ms1);

    instanceInfoMapper.setPreferHostName(true);

    performAsync("/v1/catalog/service/ms1?wait=1ms")
            .andExpect(content().contentType("application/json;charset=UTF-8"))
            .andExpect(jsonPath("$[0].Address", Matchers.is("ms1.com")))
            .andExpect(jsonPath("$[0].ServiceAddress", Matchers.is("ms1.com")))

            .andExpect(jsonPath("$[1].Address", Matchers.is("2.ms1.com")))
            .andExpect(jsonPath("$[1].ServiceAddress", Matchers.is("2.ms1.com")));
}
 
Example #11
Source File: EurekaEndpointGroupTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Override
protected void configure(ServerBuilder sb) throws Exception {
    final AtomicInteger requestCounter = new AtomicInteger();
    sb.service("/apps", (ctx, req) -> {
        final int count = requestCounter.getAndIncrement();
        if (count == 0) {
            // This is for the test that EurekaUpdatingListener automatically retries when
            // RetryingClient is not used.
            return HttpResponse.of(HttpStatus.INTERNAL_SERVER_ERROR);
        }
        final Applications apps = InstanceInfoGenerator.newBuilder(6, 2).build().toApplications();
        apps.getRegisteredApplications().get(0).getInstances().get(0).setStatus(InstanceStatus.DOWN);
        final ByteArrayOutputStream bos = new ByteArrayOutputStream();
        encoder.encode(apps, bos);
        return HttpResponse.of(HttpStatus.OK, MediaType.JSON_UTF_8, bos.toByteArray());
    });
}
 
Example #12
Source File: WebClientEurekaHttpClient.java    From spring-cloud-netflix with Apache License 2.0 6 votes vote down vote up
private EurekaHttpResponse<Applications> getApplicationsInternal(String urlPath,
		String[] regions) {
	String url = urlPath;

	if (regions != null && regions.length > 0) {
		url = url + (urlPath.contains("?") ? "&" : "?") + "regions="
				+ StringUtil.join(regions);
	}

	ClientResponse response = webClient.get().uri(url, Applications.class)
			.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
			.header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE).exchange()
			.block();

	int statusCode = statusCodeValueOf(response);

	Applications body = response.toEntity(Applications.class).block().getBody();

	return anEurekaHttpResponse(statusCode,
			statusCode == HttpStatus.OK.value() && body != null ? body : null)
					.headers(headersOf(response)).build();
}
 
Example #13
Source File: RestTemplateEurekaHttpClient.java    From spring-cloud-netflix with Apache License 2.0 6 votes vote down vote up
private EurekaHttpResponse<Applications> getApplicationsInternal(String urlPath,
		String[] regions) {
	String url = serviceUrl + urlPath;

	if (regions != null && regions.length > 0) {
		url = url + (urlPath.contains("?") ? "&" : "?") + "regions="
				+ StringUtil.join(regions);
	}

	ResponseEntity<EurekaApplications> response = restTemplate.exchange(url,
			HttpMethod.GET, null, EurekaApplications.class);

	return anEurekaHttpResponse(response.getStatusCodeValue(),
			response.getStatusCode().value() == HttpStatus.OK.value()
					&& response.hasBody() ? (Applications) response.getBody() : null)
							.headers(headersOf(response)).build();
}
 
Example #14
Source File: EurekaDiscoveryClient.java    From spring-cloud-netflix with Apache License 2.0 6 votes vote down vote up
@Override
public List<String> getServices() {
	Applications applications = this.eurekaClient.getApplications();
	if (applications == null) {
		return Collections.emptyList();
	}
	List<Application> registered = applications.getRegisteredApplications();
	List<String> names = new ArrayList<>();
	for (Application app : registered) {
		if (app.getInstances().isEmpty()) {
			continue;
		}
		names.add(app.getName().toLowerCase());

	}
	return names;
}
 
Example #15
Source File: EurekaConfigServerBootstrapConfigurationTests.java    From spring-cloud-netflix with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Bean
public EurekaHttpClient mockEurekaHttpClient() {
	InstanceInfo instanceInfo = InstanceInfo.Builder.newBuilder()
			.setAppName("configserver").build();
	List<InstanceInfo> instanceInfos = Collections.singletonList(instanceInfo);

	Applications applications = mock(Applications.class);
	when(applications.getInstancesByVirtualHostName("configserver"))
			.thenReturn(instanceInfos);

	EurekaHttpResponse<Applications> response = mock(EurekaHttpResponse.class);
	when(response.getStatusCode()).thenReturn(200);
	when(response.getEntity()).thenReturn(applications);

	EurekaHttpClient client = mock(EurekaHttpClient.class);
	when(client.getApplications("us-east-1")).thenReturn(response);
	return client;
}
 
Example #16
Source File: EurekaReactiveDiscoveryClientTests.java    From spring-cloud-netflix with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReturnFluxOfServices() {
	Applications applications = new Applications();
	Application app = new Application("my-service");
	app.addInstance(new InstanceInfo("instance", "my-service", "", "127.0.0.1", "",
			null, null, "", "", "", "", "", "", 0, null, "", null, null, null, null,
			null, null, null, null, null, null));
	applications.addApplication(app);
	when(eurekaClient.getApplications()).thenReturn(applications);
	Flux<String> services = this.client.getServices();
	StepVerifier.create(services).expectNext("my-service").expectComplete().verify();
}
 
Example #17
Source File: EurekaReactiveDiscoveryClientTests.java    From spring-cloud-netflix with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReturnEmptyFluxOfServicesWhenNoInstancesFound() {
	Applications applications = new Applications();
	applications.addApplication(new Application("my-service"));
	when(eurekaClient.getApplications()).thenReturn(applications);
	Flux<String> services = this.client.getServices();
	StepVerifier.create(services).expectNextCount(0).expectComplete().verify();
}
 
Example #18
Source File: EurekaServiceDiscovery.java    From spring-cloud-gray with Apache License 2.0 5 votes vote down vote up
@Override
public List<ServiceInfo> listAllSerivceInfos() {
    Applications applications = eurekaClient.getApplications();
    if (applications == null) {
        return Collections.emptyList();
    }
    List<Application> applicationList = applications.getRegisteredApplications();
    return applicationList.stream().map(this::ofApplication).collect(Collectors.toList());
}
 
Example #19
Source File: ArmeriaEurekaClientTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
private static List<Endpoint> endpointsFromApplications(Applications applications, boolean secureVip) {
    final Builder<Endpoint> builder = ImmutableList.builder();
    for (Application application : applications.getRegisteredApplications()) {
        builder.addAll(endpointsFromApplication(application, secureVip));
    }
    return builder.build();
}
 
Example #20
Source File: ArmeriaEurekaClientTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
public EurekaHttpResponse<Applications> getSecureVip(String secureVipAddress, String... regions) {
    final EurekaHttpResponse<Applications> eurekaResponse = convertResponse(
            delegate.getSecureVip(secureVipAddress, ImmutableList.copyOf(
                    requireNonNull(regions, "regions"))), Applications.class);
    final EurekaEndpointGroupBuilder builder = EurekaEndpointGroup.builder(eurekaUri)
                                                                  .secureVipAddress(secureVipAddress);
    setRegions(builder, regions);
    final List<Endpoint> endpoints = endpoints(builder.build());
    final Applications applications = eurekaResponse.getEntity();
    assertThat(endpoints).containsExactlyInAnyOrderElementsOf(
            endpointsFromApplications(applications, true));
    return eurekaResponse;
}
 
Example #21
Source File: EurekaServerMockApplication.java    From spring-cloud-netflix with Apache License 2.0 5 votes vote down vote up
@GetMapping({ "/apps", "/apps/delta", "/vips/{address}", "/svips/{address}" })
public Applications getApplications(@PathVariable(required = false) String address,
		@RequestParam(required = false) String regions) {
	Applications applications = new Applications();
	applications
			.addApplication(new Application("app1", Collections.singletonList(INFO)));
	return applications;
}
 
Example #22
Source File: ArmeriaEurekaClientTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
public EurekaHttpResponse<Applications> getVip(String vipAddress, String... regions) {
    final EurekaHttpResponse<Applications> eurekaResponse = convertResponse(delegate.getVip(
            vipAddress, ImmutableList.copyOf(requireNonNull(regions, "regions"))), Applications.class);

    final EurekaEndpointGroupBuilder builder = EurekaEndpointGroup.builder(eurekaUri)
                                                                  .vipAddress(vipAddress);
    setRegions(builder, regions);
    final List<Endpoint> endpoints = endpoints(builder.build());
    final Applications applications = eurekaResponse.getEntity();
    assertThat(endpoints).containsExactlyInAnyOrderElementsOf(
            endpointsFromApplications(applications, false));
    return eurekaResponse;
}
 
Example #23
Source File: ArmeriaEurekaClientTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
public EurekaHttpResponse<Applications> getApplications(String... regions) {
    final EurekaHttpResponse<Applications> eurekaResponse = convertResponse(delegate.getApplications(
            ImmutableList.copyOf(requireNonNull(regions, "regions"))), Applications.class);

    final EurekaEndpointGroupBuilder builder = EurekaEndpointGroup.builder(eurekaUri);
    setRegions(builder, regions);
    final List<Endpoint> endpoints = endpoints(builder.build());
    final Applications applications = eurekaResponse.getEntity();
    assertThat(endpoints).containsExactlyInAnyOrderElementsOf(endpointsFromApplications(applications,
                                                                                        false));
    return eurekaResponse;
}
 
Example #24
Source File: ApimlDiscoveryClientStub.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Applications getApplications() {
    if (applicationRegistry != null) {
        return applicationRegistry.getApplications();
    } else {
        return new Applications();
    }
}
 
Example #25
Source File: DubboServiceDiscoveryAutoConfiguration.java    From spring-cloud-alibaba with Apache License 2.0 5 votes vote down vote up
/**
 * Compare {@link Applications#getAppsHashCode() apps hash code} between last
 * {@link Applications} and current.
 *
 * @see Applications#getAppsHashCode()
 * @return HeartbeatEvent Predicate
 */
@Bean
public Predicate<HeartbeatEvent> heartbeatEventChangedPredicate() {
	return event -> {
		String oldAppsHashCode = appsHashCodeCache.get();
		CloudEurekaClient cloudEurekaClient = (CloudEurekaClient) event
				.getSource();
		Applications applications = cloudEurekaClient.getApplications();
		String appsHashCode = applications.getAppsHashCode();
		return appsHashCodeCache.compareAndSet(oldAppsHashCode, appsHashCode)
				&& !Objects.equals(oldAppsHashCode, appsHashCode);
	};
}
 
Example #26
Source File: EurekaUtil.java    From redis-manager with Apache License 2.0 5 votes vote down vote up
/**
 * 获取eureka注册节点
 * 
 * @return List<AnalyzeInstance>
 */
public static List<AnalyzeInstance> getRegisterNodes() {
	PeerAwareInstanceRegistry registry = EurekaServerContextHolder.getInstance().getServerContext().getRegistry();
	Applications applications = registry.getApplications();
	List<AnalyzeInstance> analyzes = new ArrayList<>();
	applications.getRegisteredApplications().forEach((registeredApplication) -> {
		registeredApplication.getInstances().forEach((instance) -> {
			AnalyzeInstance analyzeInstance = new AnalyzeInstance(instance.getIPAddr(), instance.getPort());
			analyzes.add(analyzeInstance);
		});
	});

	return analyzes;
}
 
Example #27
Source File: ServiceControllerTest.java    From eureka-consul-adapter with MIT License 5 votes vote down vote up
private Applications mock2Applications() {
    Applications applications = new Applications();
    Application app1 = new Application();
    app1.setName("ms1");
    applications.addApplication(app1);
    Application app2 = new Application();
    app2.setName("ms2");
    applications.addApplication(app2);

    return applications;
}
 
Example #28
Source File: ServiceControllerTest.java    From eureka-consul-adapter with MIT License 5 votes vote down vote up
@Test(timeout = 3000)
public void service_eventInterruptsRequestError_isResolved() throws Exception {

    Applications applications = mock2Applications();
    Mockito.when(registry.getApplications()).thenReturn(applications);

    Application ms1 = applications.getRegisteredApplications().get(0);
    InstanceInfo instance1 = mock1Instance();
    ms1.addInstance(instance1);
    Mockito.when(registry.getApplication("ms1")).thenReturn(ms1);

    startThread(() -> {
        sleepFor(500);
        serviceChangeDetector.publish("ms2", 1);
        sleepFor(500);
        serviceChangeDetector.publish("ms2", 2);
        sleepFor(500);
        serviceChangeDetector.publish("ms2", 3);
        sleepFor(500);
        serviceChangeDetector.publish("ms2", 4);
        sleepFor(500);
        serviceChangeDetector.publish("ms2", 5);
    });

    long t1 = System.currentTimeMillis();
    performAsync("/v1/catalog/service/ms1?wait=2s&index=1")
            .andExpect(content().contentType("application/json;charset=UTF-8"))
            .andExpect(header().string("X-Consul-Index", "1"))
            .andExpect(content().contentType("application/json;charset=UTF-8"))
            .andExpect(jsonPath("$[0].Address", Matchers.is("1.2.3.4")));

    Assert.assertThat(System.currentTimeMillis() - t1, Matchers.is(Matchers.greaterThan(2000L)));

}
 
Example #29
Source File: EurekaUtil.java    From RCT with Apache License 2.0 5 votes vote down vote up
/**
 * 获取eureka注册节点
 * 
 * @return List<AnalyzeInstance>
 */
public static List<AnalyzeInstance> getRegisterNodes() {
	PeerAwareInstanceRegistry registry = EurekaServerContextHolder.getInstance().getServerContext().getRegistry();
	Applications applications = registry.getApplications();
	List<AnalyzeInstance> analyzes = new ArrayList<>();
	applications.getRegisteredApplications().forEach((registeredApplication) -> {
		registeredApplication.getInstances().forEach((instance) -> {
			AnalyzeInstance analyzeInstance = new AnalyzeInstance(instance.getIPAddr(), instance.getPort());
			analyzes.add(analyzeInstance);
		});
	});

	return analyzes;
}
 
Example #30
Source File: EurekaApplicationsTest.java    From api-layer with Eclipse Public License 2.0 5 votes vote down vote up
@Test
void givenEurekaClient_whenRetrieveRegisteredApps_thenReturnApps() {
    EurekaApplications retrieval = new EurekaApplications(eurekaClient);
    Applications applications = mock(Applications.class);
    List<Application> applicationList = new ArrayList<>();
    applicationList.add(mock(Application.class));

    Mockito.when(eurekaClient.getApplications()).thenReturn(applications);
    Mockito.when(eurekaClient.getApplications().getRegisteredApplications()).thenReturn(applicationList);

    List<Application> registeredApps = retrieval.getRegistered();

    assertFalse(registeredApps.isEmpty());
}