org.springframework.cloud.client.ServiceInstance Java Examples
The following examples show how to use
org.springframework.cloud.client.ServiceInstance.
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: DiscoveryClientConfigServiceBootstrapConfigurationTests.java From spring-cloud-config with Apache License 2.0 | 6 votes |
@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 #2
Source File: KubernetesReactiveDiscoveryClientTests.java From spring-cloud-kubernetes with Apache License 2.0 | 6 votes |
@Test public void shouldReturnEmptyFluxWhenServiceHasNoSubsets( @Client KubernetesClient kubernetesClient, @Server KubernetesServer kubernetesServer) { kubernetesServer.expect().get().withPath("/api/v1/namespaces/test/services") .andReturn(200, new ServiceListBuilder().addNewItem().withNewMetadata() .withName("existing-service") .withLabels(new HashMap<String, String>() { { put("label", "value"); } }).endMetadata().endItem().build()) .once(); KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties(); ReactiveDiscoveryClient client = new KubernetesReactiveDiscoveryClient( kubernetesClient, properties, KubernetesClient::services); Flux<ServiceInstance> instances = client.getInstances("existing-service"); StepVerifier.create(instances).expectNextCount(0).expectComplete().verify(); }
Example #3
Source File: SimpleDnsBasedDiscoveryClient.java From spring-cloud-cloudfoundry with Apache License 2.0 | 6 votes |
@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 #4
Source File: DefaultServiceInstanceConverter.java From Moss with Apache License 2.0 | 6 votes |
protected URI getManagementUrl(ServiceInstance instance) { String managementPath = instance.getMetadata().get(KEY_MANAGEMENT_PATH); if (isEmpty(managementPath)) { managementPath = managementContextPath; } URI serviceUrl = getServiceUrl(instance); String managementServerAddress = instance.getMetadata().get(KEY_MANAGEMENT_ADDRESS); if (isEmpty(managementServerAddress)) { managementServerAddress = serviceUrl.getHost(); } String managementPort = instance.getMetadata().get(KEY_MANAGEMENT_PORT); if (isEmpty(managementPort)) { managementPort = String.valueOf(serviceUrl.getPort()); } return UriComponentsBuilder.fromUri(serviceUrl) .host(managementServerAddress) .port(managementPort) .path("/") .path(managementPath) .build() .toUri(); }
Example #5
Source File: DtsLoadbalance.java From dts with Apache License 2.0 | 6 votes |
public String chooseServer() { if (size == 0) { throw new NoSuchElementException("there is no dts server node discoveryed"); } synchronized (this) { ServiceInstance instance = null; while(instance == null && serviceInstanceList.size() > 0) { index = index % serviceInstanceList.size(); try { instance = serviceInstanceList.get(index); }catch (IndexOutOfBoundsException e){ //ignore } index++; } return instance.getHost() + ":" + instance.getPort(); } }
Example #6
Source File: FeignBlockingLoadBalancerClient.java From spring-cloud-openfeign with Apache License 2.0 | 6 votes |
@Override public Response execute(Request request, Request.Options options) throws IOException { final URI originalUri = URI.create(request.url()); String serviceId = originalUri.getHost(); Assert.state(serviceId != null, "Request URI does not contain a valid hostname: " + originalUri); ServiceInstance instance = loadBalancerClient.choose(serviceId); if (instance == null) { String message = "Load balancer does not contain an instance for the service " + serviceId; if (LOG.isWarnEnabled()) { LOG.warn(message); } return Response.builder().request(request) .status(HttpStatus.SERVICE_UNAVAILABLE.value()) .body(message, StandardCharsets.UTF_8).build(); } String reconstructedUrl = loadBalancerClient.reconstructURI(instance, originalUri) .toString(); Request newRequest = Request.create(request.httpMethod(), reconstructedUrl, request.headers(), request.body(), request.charset(), request.requestTemplate()); return delegate.execute(newRequest, options); }
Example #7
Source File: CustomerClient.java From microservice with Apache License 2.0 | 6 votes |
private String customerURL() { if (useRibbon) { ServiceInstance instance = loadBalancer.choose("CUSTOMER"); return "http://" + instance.getHost() + ":" + instance.getPort() + "/customer/"; } else { return "http://" + customerServiceHost + ":" + customerServicePort + "/customer/"; } }
Example #8
Source File: OmegaSpringEurekaConfig.java From servicecomb-pack with Apache License 2.0 | 6 votes |
private String[] getAlphaAddress(String serviceId) { List<String> alphaAddresses = new ArrayList<>(); List<ServiceInstance> serviceInstances = discoveryClient.getInstances(serviceId); boolean foundAlphaServer = Boolean.FALSE; for (ServiceInstance serviceInstance : serviceInstances) { foundAlphaServer = Boolean.TRUE; if (serviceInstance.getMetadata().containsKey(serviceId)) { String alphaAddress = serviceInstance.getMetadata().get(serviceId); alphaAddresses.add(alphaAddress); } } if (foundAlphaServer) { if (alphaAddresses.size() == 0) { LOG.warn("Alpha has been found in Eureka, " + "but Alpha's registered address information is not found in Eureka instance metadata. " + "Please check Alpha is configured spring.profiles.active=spring-cloud"); } } else { LOG.warn("No Alpha Server {} found in the Eureka", serviceId); } return alphaAddresses.toArray(new String[alphaAddresses.size()]); }
Example #9
Source File: TimeClientApplication.java From eureka_lab with MIT License | 6 votes |
@GetMapping("/getTimeViaEurekaClient") public String getTimeViaEurekaClient() { List<ServiceInstance> instances = discoveryClient.getInstances("time-service"); String result = "no instance available"; if (instances != null && instances.size() > 0) { ServiceInstance instance = instances.get(0); // Invoke server based on host and port. // Example using RestTemplate. URI productUri = URI.create(String .format("http://%s:%s", instance.getHost(), instance.getPort())); result = restTemplate.getForObject(productUri, String.class); } return result; }
Example #10
Source File: ServiceDescriptionUpdater.java From microservice-patterns with Apache License 2.0 | 6 votes |
@Scheduled(fixedDelayString= "${swagger.config.refreshrate}") public void refreshSwaggerConfigurations(){ logger.debug("Starting Service Definition Context refresh"); discoveryClient.getServices().stream().forEach(serviceId -> { logger.debug("Attempting service definition refresh for Service : {} ", serviceId); List<ServiceInstance> serviceInstances = discoveryClient.getInstances(serviceId); if(serviceInstances == null || serviceInstances.isEmpty()){ //Should not be the case kept for failsafe logger.info("No instances available for service : {} ",serviceId); }else{ ServiceInstance instance = serviceInstances.get(0); String swaggerURL = getSwaggerURL( instance); Optional<Object> jsonData = getSwaggerDefinitionForAPI(serviceId, swaggerURL); if(jsonData.isPresent()){ String content = getJSON(serviceId, jsonData.get()); definitionContext.addServiceDefinition(serviceId, content); }else{ logger.error("Skipping service id : {} Error : Could not get Swagegr definition from API ",serviceId); } logger.info("Service Definition Context Refreshed at : {}",LocalDate.now()); } }); }
Example #11
Source File: DiscoveryClientNameResolver.java From grpc-spring-boot-starter with MIT License | 6 votes |
/** * Extracts the gRPC server port from the given service instance. * * @param instance The instance to extract the port from. * @return The gRPC server port. * @throws IllegalArgumentException If the specified port definition couldn't be parsed. */ private int getGRPCPort(final ServiceInstance instance) { final Map<String, String> metadata = instance.getMetadata(); if (metadata == null) { return instance.getPort(); } final String portString = metadata.get(GrpcUtils.CLOUD_DISCOVERY_METADATA_PORT); if (portString == null) { return instance.getPort(); } try { return Integer.parseInt(portString); } catch (final NumberFormatException e) { // TODO: How to handle this case? throw new IllegalArgumentException("Failed to parse gRPC port information from: " + instance, e); } }
Example #12
Source File: DefaultServiceInstanceConverterTest.java From spring-boot-admin with Apache License 2.0 | 6 votes |
@Test public void should_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 #13
Source File: EncodedCharactersFilterTest.java From api-layer with Eclipse Public License 2.0 | 5 votes |
@Test public void givenSingleInstance_WhenConfigured_ShouldNotFilter() { List<ServiceInstance> instanceList = new ArrayList<>(); instanceList.add(serviceInstanceWithConfiguration); when(discoveryClient.getInstances(SERVICE_ID)).thenReturn(instanceList); assertThat(filter.shouldFilter(), is(equalTo(false))); }
Example #14
Source File: CompositeDiscoveryClientTestsConfig.java From spring-cloud-commons with Apache License 2.0 | 5 votes |
private DiscoveryClient aDiscoveryClient(Integer order, String description) { return new DiscoveryClient() { @Override public String description() { return description; } @Override public List<ServiceInstance> getInstances(String serviceId) { if (serviceId.equals(CUSTOM_SERVICE_ID)) { ServiceInstance s1 = new DefaultServiceInstance("customInstance", CUSTOM_SERVICE_ID, "host", 123, false); return singletonList(s1); } return Collections.emptyList(); } @Override public List<String> getServices() { return singletonList(CUSTOM_SERVICE_ID); } @Override public int getOrder() { return order != null ? order : DiscoveryClient.super.getOrder(); } }; }
Example #15
Source File: DiscoveryLightminServerLocatorService.java From spring-batch-lightmin with Apache License 2.0 | 5 votes |
private List<String> getServerUrls(final String serviceId) { final List<ServiceInstance> instances = this.discoveryClient.getInstances(serviceId); final List<String> urls = new ArrayList<>(); for (final ServiceInstance instance : instances) { final String url = instance.getUri().toString(); final String finalUrl; if (StringUtils.hasText(url)) { if (StringUtils.hasText(this.lightminClientDiscoveryProperties.getServerContextPath())) { final String contextPath = this.lightminClientDiscoveryProperties.getServerContextPath(); final String cp; if (contextPath.startsWith("/")) { cp = contextPath; } else { cp = "/" + contextPath; } finalUrl = url + cp; } else { finalUrl = url; } } else { log.debug("No service instance found, skipping contextPath avaulation"); finalUrl = url; } urls.add(finalUrl); } return urls; }
Example #16
Source File: DiscoveryClientService.java From springcloudsamples-ggj with Apache License 2.0 | 5 votes |
public List<String> discoveryClient() { ArrayList<String> list = new ArrayList<>(); discoveryClient.getInstances(FeignService.CLIENT_SERVICE_A).forEach((ServiceInstance s) -> { String name = s.getServiceId() + " - " + s.getUri().toString(); log.info("客户端名称:"+name); list.add(name); }); return list; }
Example #17
Source File: MossInstanceDiscoveryListener.java From Moss with Apache License 2.0 | 5 votes |
protected Mono<InstanceId> registerInstance(ServiceInstance instance) { try { Registration registration = converter.convert(instance).toBuilder().source(SOURCE).build(); log.debug("Registering discovered instance {}", registration); return registry.register(registration); } catch (Exception ex) { log.error("Couldn't register instance for service {}", instance, ex); } return Mono.empty(); }
Example #18
Source File: ServiceHelper.java From Mastering-Microservices-with-Java with MIT License | 5 votes |
/** * * @param serviceId * @param fallbackUri * @return */ protected URI getServiceUrl(String serviceId, String fallbackUri) { URI uri = null; try { ServiceInstance instance = loadBalancer.choose(serviceId); if (instance == null) { throw new RuntimeException("Can't find a service with serviceId = " + serviceId); } uri = instance.getUri(); LOG.info("Resolved serviceId '{}' to URL '{}'.", serviceId, uri); } catch (RuntimeException e) { e.printStackTrace(); // Eureka not available, use fallback if specified otherwise rethrow the error Integer.parseInt(""); if (fallbackUri == null) { throw e; } else { uri = URI.create(fallbackUri); LOG.warn("Failed to resolve serviceId '{}'. Fallback to URL '{}'.", serviceId, uri); } } return uri; }
Example #19
Source File: ZonePreferenceServiceInstanceListSupplierTests.java From spring-cloud-commons with Apache License 2.0 | 5 votes |
@Test void shouldReturnAllInstancesIfNoZoneInstances() { zoneConfig.setZone("zone1"); when(delegate.get()).thenReturn(Flux.just(Arrays.asList(third, fourth))); List<ServiceInstance> filtered = supplier.get().blockFirst(); assertThat(filtered).hasSize(2); assertThat(filtered).contains(third, fourth); }
Example #20
Source File: CustomRemoteTokenServices.java From microservice-integration with MIT License | 5 votes |
public void loadAuthentication(String accessToken) { MultiValueMap<String, String> formData = new LinkedMultiValueMap<>(); formData.add(tokenName, accessToken); HttpHeaders headers = new HttpHeaders(); headers.set("Authorization", getAuthorizationHeader(clientId, clientSecret)); ServiceInstance serviceInstance = loadBalancerClient.choose("auth"); if (serviceInstance == null) { throw new RuntimeException("Failed to choose an auth instance."); } Map<String, Object> map = postForMap(serviceInstance.getUri().toString() + checkTokenEndpointUrl, formData, headers); if (map.containsKey(ERROR)) { logger.debug("check_token returned error: " + map.get(ERROR)); Object status = map.get("status"); if (status != null && status.equals(HttpStatus.BAD_REQUEST.value())) { throw new ServerException(HttpStatus.BAD_REQUEST, new ErrorCode(400, "bad request!", "pls check your params!")); } HttpStatus code = (HttpStatus) map.get(ERROR); if (code == HttpStatus.UNAUTHORIZED) { //TODO:sendErrorFilter findZuulException会查看FilterRuntimeException中zuulException的code和message throw new ServerException(HttpStatus.BAD_REQUEST, new ErrorCode(401, "UNAUTHORIZED", "your identity id illegal!")); } else { throw new ServerException(HttpStatus.BAD_REQUEST, new ErrorCode(403, "not permitted!", "you do not have permission to operate!")); } } Assert.state(map.containsKey("client_id"), "Client id must be present in response from auth server"); return; }
Example #21
Source File: AdminRest.java From WeEvent with Apache License 2.0 | 5 votes |
@RequestMapping(path = "/listSubscription") public BaseResponse<Map<String, List<SubscriptionInfo>>> listSubscription(@RequestParam(name = "nodeInstances") String nodeInstances, @RequestParam(name = "groupId", required = false) String groupId) { log.info("groupId:{}, nodeInstances:{}", groupId, nodeInstances); if (StringUtils.isBlank(nodeInstances)) { log.error("nodeInstances is empty."); return BaseResponse.buildFail(ErrorCode.CGI_INVALID_INPUT); } List<ServiceInstance> instances = this.discoveryClient.getInstances(this.appName); Map<String, List<SubscriptionInfo>> subscriptions = new HashMap<>(); String[] instanceList = nodeInstances.split(","); for (String instanceId : instanceList) { Optional<ServiceInstance> instance = instances.stream().filter(item -> item.getInstanceId().equals(instanceId)).findFirst(); if (instance.isPresent()) { String url = String.format("%s/%s/admin/innerListSubscription", instance.get().getUri(), this.appName); if (!StringUtils.isBlank(groupId)) { url += "?groupId=" + groupId; } log.info("url: {}", url); SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); RestTemplate rest = new RestTemplate(requestFactory); ResponseEntity<BaseResponse<Map<String, SubscriptionInfo>>> rsp = rest.exchange(url, HttpMethod.GET, null, new ParameterizedTypeReference<BaseResponse<Map<String, SubscriptionInfo>>>() { }); if (rsp.getStatusCode() == HttpStatus.OK && rsp.getBody() != null) { log.debug("innerListSubscription: {}", rsp); subscriptions.put(instanceId, new ArrayList<>(rsp.getBody().getData().values())); continue; } } subscriptions.put(instanceId, Collections.emptyList()); } return BaseResponse.buildSuccess(subscriptions); }
Example #22
Source File: NacosServiceDiscovery.java From spring-cloud-alibaba with Apache License 2.0 | 5 votes |
public static List<ServiceInstance> hostToServiceInstanceList( List<Instance> instances, String serviceId) { List<ServiceInstance> result = new ArrayList<>(instances.size()); for (Instance instance : instances) { ServiceInstance serviceInstance = hostToServiceInstance(instance, serviceId); if (serviceInstance != null) { result.add(serviceInstance); } } return result; }
Example #23
Source File: DiscoveryClientRouteDefinitionLocator.java From spring-cloud-gateway with Apache License 2.0 | 5 votes |
protected RouteDefinition buildRouteDefinition(Expression urlExpr, ServiceInstance serviceInstance) { String serviceId = serviceInstance.getServiceId(); RouteDefinition routeDefinition = new RouteDefinition(); routeDefinition.setId(this.routeIdPrefix + serviceId); String uri = urlExpr.getValue(this.evalCtxt, serviceInstance, String.class); routeDefinition.setUri(URI.create(uri)); // add instance metadata routeDefinition.setMetadata(new LinkedHashMap<>(serviceInstance.getMetadata())); return routeDefinition; }
Example #24
Source File: CatalogClient.java From microservice with Apache License 2.0 | 5 votes |
private String catalogURL() { if (useRibbon) { ServiceInstance instance = loadBalancer.choose("CATALOG"); return "http://" + instance.getHost() + ":" + instance.getPort() + "/catalog/"; } else { return "http://" + catalogServiceHost + ":" + catalogServicePort + "/catalog/"; } }
Example #25
Source File: ConsulReactiveDiscoveryClientTests.java From spring-cloud-consul with Apache License 2.0 | 5 votes |
@Test public void shouldReturnEmptyFluxWhenConsulFails() { configureCommonProperties(); when(consulClient.getHealthServices(eq("existing-service"), any(HealthServicesRequest.class))) .thenThrow(new RuntimeException("Possible runtime exception")); Flux<ServiceInstance> instances = client.getInstances("existing-service"); StepVerifier.create(instances).expectNextCount(0).expectComplete().verify(); verify(consulClient).getHealthServices(eq("existing-service"), any()); }
Example #26
Source File: AdminApp.java From myfeed with Apache License 2.0 | 5 votes |
private Map<String, String> getUrl(String serviceId, String key) { String url = null; ServiceInstance instance = loadBalancerClient.choose(serviceId); if (instance != null) { url = instance.getUri().toString(); } return Collections.singletonMap(key, url); }
Example #27
Source File: DefaultServiceInstanceConverter.java From Moss with Apache License 2.0 | 5 votes |
@Override public Registration convert(ServiceInstance instance) { LOGGER.debug( "Converting service '{}' running at '{}' with metadata {}", instance.getServiceId(), instance.getUri(), instance.getMetadata() ); return Registration.create(instance.getServiceId(), getHealthUrl(instance).toString()) .managementUrl(getManagementUrl(instance).toString()) .serviceUrl(getServiceUrl(instance).toString()) .metadata(getMetadata(instance)) .build(); }
Example #28
Source File: DefaultServiceInstanceConverter.java From spring-boot-admin with Apache License 2.0 | 5 votes |
protected String getManagementHost(ServiceInstance instance) { String managementServerHost = instance.getMetadata().get(KEY_MANAGEMENT_ADDRESS); if (!isEmpty(managementServerHost)) { return managementServerHost; } return getServiceUrl(instance).getHost(); }
Example #29
Source File: DefaultServiceInstanceConverter.java From Moss with Apache License 2.0 | 5 votes |
protected URI getHealthUrl(ServiceInstance instance) { String healthPath = instance.getMetadata().get(KEY_HEALTH_PATH); if (isEmpty(healthPath)) { healthPath = healthEndpointPath; } return UriComponentsBuilder.fromUri(getManagementUrl(instance)).path("/").path(healthPath).build().toUri(); }
Example #30
Source File: SimpleDnsBasedReactiveDiscoveryClient.java From spring-cloud-cloudfoundry with Apache License 2.0 | 5 votes |
@Override public Flux<ServiceInstance> getInstances(String serviceId) { return Mono.justOrEmpty(serviceIdToHostnameConverter.toHostname(serviceId)) .flatMapMany(getInetAddresses()) .map(address -> new DefaultServiceInstance(serviceId, address.getHostAddress(), 8080, false)); }