Java Code Examples for org.springframework.cloud.client.ServiceInstance#getPort()

The following examples show how to use org.springframework.cloud.client.ServiceInstance#getPort() . 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: DiscoveryClientNameResolver.java    From grpc-spring-boot-starter with MIT License 6 votes vote down vote up
/**
 * 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 2
Source File: DiscoveryClientNameResolver.java    From grpc-spring-boot-starter with MIT License 6 votes vote down vote up
/**
 * 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 3
Source File: PageRedirectionFilter.java    From api-layer with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Find matched url in specified service. For each service instance, the method first checks if the hostname and port
 * of the service instance are the same as the hostname and port in Location url. If they are the same, then try to
 * find the matched url.
 *
 * @param location  url in Location header
 * @param serviceId specified serviceId
 * @return return matched url if it can be found
 * return empty if matched url can not be found
 */
private Optional<String> foundMatchedUrlInService(String location, String serviceId) {
    List<ServiceInstance> serviceInstances = discovery.getInstances(serviceId);
    for (ServiceInstance instance : serviceInstances) {
        //Check if the host and port in location is registered in DS
        String host = instance.getHost() + ":" + instance.getPort();
        if (location.contains(host)) {
            try {
                String transformedUrl = transformService.transformURL(ServiceType.ALL, serviceId, location, routedServicesMap.get(serviceId));
                return Optional.of(transformedUrl);
            } catch (URLTransformationException e) {
                //do nothing if no matched url is found
            }
        }
    }

    return Optional.empty();
}
 
Example 4
Source File: DefaultDtsServerMessageSender.java    From dts with Apache License 2.0 6 votes vote down vote up
private <T> T clusterCycleSync(RequestMessage msg) throws DtsException {
    List<ServiceInstance> serviceInstanceList = discoveryClient.getInstances(RemoteConstant.DTS_SERVER_NAME);
    for (int i = 0; i < serviceInstanceList.size(); i++) {
        ServiceInstance instance = serviceInstanceList.get(i);
        if (NetWorkUtil.getLocalIp().equals(instance.getHost())
            && instance.getPort() == dtsServerContainer.getRemotingServer().localListenPort()) {
            continue;
        }
        String server = instance.getHost() + ":" + instance.getPort();
        try {
            return clusterMessageSender.invoke(server, msg);
        } catch (Throwable e) {
            logger.warn("cluster sync {} send {} failed! will try next server", server, msg);
        }
    }
    throw new DtsException("No available server for clusterCycleSync");
}
 
Example 5
Source File: DtsLoadbalance.java    From dts with 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 File: CatalogClient.java    From microservice with Apache License 2.0 5 votes vote down vote up
private String catalogURL() {
	if (useRibbon) {
		ServiceInstance instance = loadBalancer.choose("CATALOG");
		return "http://" + instance.getHost() + ":" + instance.getPort()
				+ "/catalog/";
	} else {
		return "http://" + catalogServiceHost + ":" + catalogServicePort
				+ "/catalog/";
	}
}
 
Example 7
Source File: JobCenterAutoConfiguration.java    From summerframework with Apache License 2.0 5 votes vote down vote up
private String discoveryAdminAddress() {
    String serviceId = jobCenterProperties.getServiceId();
    List<String> adminAddresList = new ArrayList<>();
    List<ServiceInstance> instanceList = discoveryClient.getInstances(serviceId);
    for (ServiceInstance serviceInstance : instanceList) {
        try {
            String host = serviceInstance.getHost();
            int port = serviceInstance.getPort();
            LOGGER.info("Connecting {} ({}:{})", serviceId, host, port);
            String httpAddress = "http://" + host + ":" + port + "/";
            if (isAdminReachable(httpAddress)) {
                adminAddresList.add(httpAddress);
            } else {
                LOGGER.error("Skip unreachable node {}", httpAddress);
            }
        } catch (Throwable e) {
            LOGGER.error("can not found node for admin!", e);
        }
    }
    if (adminAddresList.size() > 0) {
        adminAddresList.sort(Comparator.naturalOrder());
        return String.join(",", adminAddresList);
    } else {
        LOGGER.error("Jobcenter server is down,will try after 30s");
        return null;
    }
}
 
Example 8
Source File: TroubleService.java    From khs-trouble-maker with Apache License 2.0 5 votes vote down vote up
public String serviceInstanceURL(String serviceName, String instanceId) {
	// FORM LIST OF INSTANCES FOR SERVICENAME
	List<ServiceInstance> instances = discoveryClient.getInstances(serviceName);

	String returnHostAndPort = "";

	// IF AN "INSTANCEID" VALUE WAS PASSED IN, THEN FIND THAT PARTICULAR ONE
	// ELSE JUST PICK A RANDOM INSTANCE FOR THE SERVICENAME
	if(!instanceId.equals("")) { 
		// LOOP THROUGH SERVICEINSTANCES OF SERVICE, ATTEMPING TO MATCH ON INSTANCEID
		for (Iterator<ServiceInstance> iterator = instances.iterator(); iterator.hasNext();) {
			EurekaDiscoveryClient.EurekaServiceInstance serviceInstance = (EurekaDiscoveryClient.EurekaServiceInstance) iterator.next();

			String tmpInstanceId = serviceInstance.getInstanceInfo().getInstanceId();
			//System.out.println(tmpInstanceId);
			
			if(tmpInstanceId.equals(instanceId)) {
				returnHostAndPort = serviceInstance.getHost() + ":" + serviceInstance.getPort() + "/";
				break;
			}
		}
	} else {
		Random rn = new Random();
		int range = instances.size();
		int randomNum = rn.nextInt(range);
		ServiceInstance rndm = instances.get(randomNum);
		returnHostAndPort = rndm.getHost() + ":" + rndm.getPort() + "/";
	}

	return returnHostAndPort;
}
 
Example 9
Source File: DefaultServiceLoadBalancer.java    From camel-spring-boot with Apache License 2.0 5 votes vote down vote up
protected ServiceDefinition convertServiceInstanceToServiceDefinition(ServiceInstance instance) {
    return new DefaultServiceDefinition(
        instance.getServiceId(),
        instance.getHost(),
        instance.getPort(),
        instance.getMetadata()
    );
}
 
Example 10
Source File: ComputeController.java    From micro-service with Apache License 2.0 5 votes vote down vote up
@RequestMapping(value = "/**" ,method = RequestMethod.GET)
public String add(@RequestParam Integer a, @RequestParam Integer b,HttpServletRequest request) {
	System.out.println(request.getRequestURL());
    ServiceInstance instance = client.getLocalServiceInstance();
    Integer r = a + b;
    logger.info("/add, host:" + instance.getHost() + ", service_id:" + instance.getServiceId() + ", result:" + r);
    return "From Service-B, Result is " + r+"\nPort:"+instance.getPort();
}
 
Example 11
Source File: AbstractMicroserviceClient.java    From jhipster-ribbon-hystrix with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Constructs a url for rest template
 *
 * @param path resource path on the service
 * @return a url String for use in RestTemplate
 */
protected String getUrl(String path) {
    String url;
    ServiceInstance instance = loadBalancerClient.choose(serviceName);
    String prefix = instance.isSecure() ? "https://" : "http://";

    url = prefix + instance.getHost() + ":" + instance.getPort() + "/api/" + path;


    return url;
}
 
Example 12
Source File: ClientController.java    From MI-S with MIT License 5 votes vote down vote up
@ResponseBody
@RequestMapping(value = "/hi", method = RequestMethod.GET)
public String hello1(@RequestParam String name){
    System.err.println("-----------------------------");
    ServiceInstance instance = discoveryClient.getInstances("mi-eureka-client").get(0);

    log.info("Method:---->"+this.getClass().getSimpleName()+"---->Hello");
    log.info("Url:---->"+instance.getUri());
    log.info("Host:---->"+instance.getHost());
    log.info("Port:---->"+instance.getPort());

    return "Hello !!   "+name + " ,I here in port  "+instance.getPort();
}
 
Example 13
Source File: ApiController.java    From MI-S with MIT License 5 votes vote down vote up
@RequestMapping("/hi")
public String hello(@RequestParam String name){
    System.err.println("-----------------------------");
    //监听指定的服务提供者
    ServiceInstance instance = discoveryClient.getInstances("mi-eureka-client").get(0);

    log.info("Method:---->"+this.getClass().getSimpleName()+"---->Hello");
    log.info("Url:---->"+instance.getUri());
    log.info("Host:---->"+instance.getHost());
    log.info("Port:---->"+instance.getPort());

    return "Hello Api "+name + " ,i here in port :" +instance.getPort();
}
 
Example 14
Source File: DeliveryServiceImpl.java    From sds with Apache License 2.0 5 votes vote down vote up
private ServiceInstance getInstance(String ipPort) {
    List<ServiceInstance> instances = discoveryClient.getInstances(DeliveryServerService.SOCKET_SERVER_KEY);
    for (ServiceInstance instance : instances) {
        String ip = instance.getHost();
        int port = instance.getPort();
        String instancesIpPort = String.format("%s:%d", ip, port);
        if (instancesIpPort.equals(ipPort)) {
            return instance;
        }
    }
    return null;
}
 
Example 15
Source File: CatalogClient.java    From microservice-consul with Apache License 2.0 5 votes vote down vote up
private String catalogURL() {
	if (useRibbon) {
		ServiceInstance instance = loadBalancer.choose("CATALOG");
		return "http://" + instance.getHost() + ":" + instance.getPort()
				+ "/catalog/";
	} else {
		return "http://" + catalogServiceHost + ":" + catalogServicePort
				+ "/catalog/";
	}
}
 
Example 16
Source File: CustomerClient.java    From microservice-consul with Apache License 2.0 5 votes vote down vote up
private String customerURL() {
	if (useRibbon) {
		ServiceInstance instance = loadBalancer.choose("CUSTOMER");
		return "http://" + instance.getHost() + ":" + instance.getPort()
				+ "/customer/";
	} else {
		return "http://" + customerServiceHost + ":" + customerServicePort
				+ "/customer/";
	}

}
 
Example 17
Source File: ServiceBController.java    From spring-cloud-consul-example with MIT License 4 votes vote down vote up
@RequestMapping(value = "/", method = RequestMethod.GET)
public String printServiceB() {
    ServiceInstance serviceInstance = discoveryClient.getLocalServiceInstance();
    return serviceInstance.getServiceId() + " (" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + ")" + "===>Say " + msg;
}
 
Example 18
Source File: AServiceController.java    From spring-cloud-consul-example with MIT License 4 votes vote down vote up
@RequestMapping(value = "/", method = RequestMethod.GET)
public String printServiceA() {
    ServiceInstance serviceInstance = discoveryClient.getLocalServiceInstance();
    return serviceInstance.getServiceId() + " (" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + ")" + "===>name:" + name + "<br/>" + serviceBClient.printServiceB();
}
 
Example 19
Source File: ReservationClientApplication.java    From bootiful-reactive-microservices with Apache License 2.0 4 votes vote down vote up
private String uri(ServiceInstance si) {
	return "http://" + si.getHost() + ':' + si.getPort() + "/reservations";
}
 
Example 20
Source File: AbstractMicroserviceClient.java    From jhipster-ribbon-hystrix with GNU General Public License v3.0 3 votes vote down vote up
protected String getUrl(String path) {
    String url;
    ServiceInstance instance = loadBalancerClient.choose(serviceName);

    url = "http://" + instance.getHost() + ":" + instance.getPort() + "/api/" + path;


    return url;
}