Java Code Examples for org.springframework.cloud.client.ServiceInstance

The following examples show how to use org.springframework.cloud.client.ServiceInstance. These examples are extracted from open source projects. 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
@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 2
Source Project: servicecomb-pack   Source File: OmegaSpringEurekaConfig.java    License: Apache License 2.0 6 votes vote down vote up
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 3
/**
 * 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 4
@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 5
Source Project: dts   Source File: DtsLoadbalance.java    License: Apache License 2.0 6 votes vote down vote up
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 Project: Moss   Source File: DefaultServiceInstanceConverter.java    License: Apache License 2.0 6 votes vote down vote up
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 7
@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 8
Source Project: eureka_lab   Source File: TimeClientApplication.java    License: MIT License 6 votes vote down vote up
@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 9
@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 10
@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 11
@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 12
Source Project: spring-cloud-commons   Source File: LoadBalancerUriTools.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Modifies the URI in order to redirect the request to a service instance of choice.
 * @param serviceInstance the {@link ServiceInstance} to redirect the request to.
 * @param original the {@link URI} from the original request
 * @return the modified {@link URI}
 */
public static URI reconstructURI(ServiceInstance serviceInstance, URI original) {
	if (serviceInstance == null) {
		throw new IllegalArgumentException("Service Instance cannot be null.");
	}
	return doReconstructURI(serviceInstance, original);
}
 
Example 13
@Override
public List<ServiceInstance> getInstances(String serviceId) {
  Microservice microService = MicroserviceHandler
      .createMicroservice(discoveryProperties, serviceId);
  //spring cloud serviceId equals servicecomb serviceName
  return MicroserviceHandler.getInstances(microService, serviceCombClient);
}
 
Example 14
protected URI resolveUri(ServiceInstance serviceInstance) {
    Map<String, Object> metadata = new HashMap<>();
    for (Map.Entry<String, String> entry : serviceInstance.getMetadata().entrySet()) {
        metadata.put(entry.getKey(), entry.getValue());
    }

    UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromUri(serviceInstance.getUri());
    RelaxedPropertyResolver propertyResolver = new RelaxedPropertyResolver(new MapPropertyResolver(metadata));
    String configPath = propertyResolver.getProperty("configPath");
    if (configPath != null) {
        uriBuilder.path(configPath);
    }

    return uriBuilder.build().toUri();
}
 
Example 15
@Override
protected URI getHealthUrl(ServiceInstance instance) {
	if (!(instance instanceof EurekaServiceInstance)) {
		return super.getHealthUrl(instance);
	}

	InstanceInfo instanceInfo = ((EurekaServiceInstance) instance).getInstanceInfo();
	String healthUrl = instanceInfo.getSecureHealthCheckUrl();
	if (StringUtils.isEmpty(healthUrl)) {
		healthUrl = instanceInfo.getHealthCheckUrl();
	}
	return URI.create(healthUrl);
}
 
Example 16
/**
 * @param serviceName The name of service that was changed
 * @param serviceInstances all {@link ServiceInstance service instances}
 * @throws IllegalArgumentException if source is null.
 */
public ServiceInstancesChangedEvent(String serviceName,
		Collection<ServiceInstance> serviceInstances) {
	super(serviceName);
	this.serviceName = serviceName;
	this.serviceInstances = unmodifiableCollection(serviceInstances);
}
 
Example 17
@Bean
public ZookeeperDiscoveryClient zookeeperDiscoveryClient(
		ZookeeperDiscoveryProperties properties) {
	ZookeeperDiscoveryClient client = mock(ZookeeperDiscoveryClient.class);
	ServiceInstance instance = new DefaultServiceInstance("configserver1",
			"configserver", properties.getInstanceHost(),
			properties.getInstancePort(), false);
	given(client.getInstances("configserver"))
			.willReturn(Arrays.asList(instance));
	return client;
}
 
Example 18
protected ServiceDefinition convertServiceInstanceToServiceDefinition(ServiceInstance instance) {
    return new DefaultServiceDefinition(
        instance.getServiceId(),
        instance.getHost(),
        instance.getPort(),
        instance.getMetadata()
    );
}
 
Example 19
String getValueFromExpr(SimpleEvaluationContext evalCtxt, SpelExpressionParser parser,
		ServiceInstance instance, Map.Entry<String, String> entry) {
	try {
		Expression valueExpr = parser.parseExpression(entry.getValue());
		return valueExpr.getValue(evalCtxt, instance, String.class);
	}
	catch (ParseException | EvaluationException e) {
		if (log.isDebugEnabled()) {
			log.debug("Unable to parse " + entry.getValue(), e);
		}
		throw e;
	}
}
 
Example 20
@RequestMapping("/hi")
public String hi() {
	ServiceInstance instance = discoveryClient.getLocalServiceInstance();
	String msg = instance.getServiceId() + ":" + instance.getHost() + ":"
			+ instance.getPort();
	log.info("/hi called: " + msg);
	return msg;
}
 
Example 21
Source Project: SpringCloud-Shop   Source File: CategoryController.java    License: Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = "application/json")
public Category get(@PathVariable Long id) {
    ServiceInstance instance = client.getLocalServiceInstance();
    Category category = categoryService.findOne(id);
    logger.info("/category, host:" + instance.getHost() + ", serviceId: " + instance.getServiceId() + ",category id: " + category.getId() + ",category name: " + category.getName());
    return category;
}
 
Example 22
@Test
public void getInstancesShouldBeAbleToHandleEndpointsSingleAddress() {
	mockServer.expect().get().withPath("/api/v1/namespaces/test/endpoints/endpoint")
			.andReturn(200, new EndpointsBuilder().withNewMetadata()
					.withName("endpoint").endMetadata().addNewSubset().addNewAddress()
					.withIp("ip1").withNewTargetRef().withUid("uid1").endTargetRef()
					.endAddress().addNewPort("http", 80, "TCP").endSubset().build())
			.once();

	mockServer.expect().get().withPath("/api/v1/services/endpoint")
			.andReturn(200, new ServiceBuilder().withNewMetadata()
					.withName("endpoint").withLabels(new HashMap<String, String>() {
						{
							put("l", "v");
						}
					}).endMetadata().build())
			.always();

	final KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties();

	final DiscoveryClient discoveryClient = new KubernetesDiscoveryClient(mockClient,
			properties, KubernetesClient::services,
			new DefaultIsServicePortSecureResolver(properties));

	final List<ServiceInstance> instances = discoveryClient.getInstances("endpoint");

	assertThat(instances).hasSize(1)
			.filteredOn(s -> s.getHost().equals("ip1") && !s.isSecure()).hasSize(1)
			.filteredOn(s -> s.getInstanceId().equals("uid1")).hasSize(1);
}
 
Example 23
@Test
void shouldReturnAllInstancesIfNoZone() {
	zoneConfig.setZone(null);
	when(delegate.get())
			.thenReturn(Flux.just(Arrays.asList(first, second, third, fourth)));

	List<ServiceInstance> filtered = supplier.get().blockFirst();

	assertThat(filtered).hasSize(4);
	assertThat(filtered).contains(first, second, third, fourth);
}
 
Example 24
@Test
public void getInstancesShouldBeAbleToHandleEndpointsSingleAddressAndMultiplePorts() {
	mockServer.expect().get().withPath("/api/v1/namespaces/test/endpoints/endpoint")
			.andReturn(200, new EndpointsBuilder().withNewMetadata()
					.withName("endpoint").endMetadata().addNewSubset().addNewAddress()
					.withIp("ip1").withNewTargetRef().withUid("uid").endTargetRef()
					.endAddress().addNewPort("mgmt", 9000, "TCP")
					.addNewPort("http", 80, "TCP").endSubset().build())
			.once();

	mockServer.expect().get().withPath("/api/v1/namespaces/test/services/endpoint")
			.andReturn(200, new ServiceBuilder().withNewMetadata()
					.withName("endpoint").withLabels(new HashMap<String, String>() {
						{
							put("l", "v");
						}
					}).endMetadata().build())
			.always();

	final KubernetesDiscoveryProperties properties = new KubernetesDiscoveryProperties();
	properties.setPrimaryPortName("http");
	final DiscoveryClient discoveryClient = new KubernetesDiscoveryClient(mockClient,
			properties, KubernetesClient::services,
			new DefaultIsServicePortSecureResolver(properties));

	final List<ServiceInstance> instances = discoveryClient.getInstances("endpoint");

	assertThat(instances).hasSize(1)
			.filteredOn(s -> s.getHost().equals("ip1") && !s.isSecure()).hasSize(1)
			.filteredOn(s -> s.getInstanceId().equals("uid")).hasSize(1)
			.filteredOn(s -> 80 == s.getPort()).hasSize(1);
}
 
Example 25
Source Project: Moss   Source File: InstanceDiscoveryListener.java    License: Apache License 2.0 5 votes vote down vote up
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 ({})", toString(instance), ex);
    }
    return Mono.empty();
}
 
Example 26
@SuppressWarnings("ConstantConditions")
@Test
void shouldReturnFalseIfEndpointNotFound() {
	healthCheck.getPath().put("ignored-service", "/test");
	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).isFalse();
}
 
Example 27
/**
 *
 * @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 28
Source Project: Microservices-Building-Scalable-Software   Source File: EdgeApp.java    License: MIT License 5 votes vote down vote up
@Override
public void run(String... strings) throws Exception {
    System.out.println(discoveryClient.description());
    discoveryClient.getInstances("restaurant-service").forEach((ServiceInstance serviceInstance) -> {
        System.out.println("Instance --> " + serviceInstance.getServiceId()
                + "\nServer: " + serviceInstance.getHost() + ":" + serviceInstance.getPort()
                + "\nURI: " + serviceInstance.getUri() + "\n\n\n");
    });
}
 
Example 29
Source Project: BootNettyRpc   Source File: ClientDiscoveryImpl.java    License: Apache License 2.0 5 votes vote down vote up
private List<NettyClient> convertNettyClients(List<ServiceInstance> serviceInstances) {
    if (CollectionUtils.isEmpty( serviceInstances )) {
        return null;
    }
    List<NettyClient> nettyClients = new CopyOnWriteArrayList<>();
    for (ServiceInstance serviceInstance : serviceInstances) {
        NettyClient nettyClient = new NettyClient();
        Map<String, String> metadata = serviceInstance.getMetadata();
        String host = metadata.get( NettyRpcConstants.NETTY_SERVER_HOST );
        if (StringUtils.isEmpty( host )) {
            host = serviceInstance.getHost();
        }
        nettyClient.setHost( host );

        String name = metadata.get( NettyRpcConstants.NETTY_SERVER_NAME );
        if (StringUtils.isEmpty( name )) {
            name = serviceInstance.getServiceId();
        }
        nettyClient.setName( name );

        String port = metadata.get( NettyRpcConstants.NETTY_SERVER_PORT );
        if (StringUtils.isEmpty( port )) {
            throw new CommonException( "netty server " + name + " 's port connot be null" );
        }
        nettyClient.setPort( Integer.valueOf( port ) );
        nettyClients.add( nettyClient );
    }
    return nettyClients;


}
 
Example 30
@Test
@Ignore // FIXME: 3.0.0
public void chooseWorks() {
	ServiceInstance instance = this.client.choose("testConsulLoadBalancer");
	assertThat(instance).isNotNull();

	assertThat(instance.isSecure()).isFalse();
	assertIpAddress(instance);
	assertThat(instance.getMetadata()).containsEntry("foo", "bar");
}