org.springframework.cloud.client.ServiceInstance

Here are the examples of the java api org.springframework.cloud.client.ServiceInstance taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

308 Examples 7

19 Source : DiscoveryClientConfigServiceBootstrapConfiguration.java
with Apache License 2.0
from Xlinlin

private String getHomePage(ServiceInstance server) {
    return server.getUri().toString() + "/";
}

19 Source : NamingService.java
with Apache License 2.0
from WeBankFinTech

public static NamingService convert(ServiceInstance instance) {
    NamingService namingService = new NamingService();
    namingService.serviceId = instance.getServiceId();
    namingService.instanceId = instance.getInstanceId();
    namingService.host = instance.getHost();
    namingService.port = instance.getPort();
    namingService.uri = instance.getUri().toString();
    namingService.secure = instance.isSecure();
    return namingService;
}

19 Source : DiscoveryClientRegistrationInvoker.java
with Apache License 2.0
from SpringCloud

/**
 * 在外置 Tomcat 下,Spring Cloud Discovery Client 的注册
 * 依赖 ServletWebServerInitializedEvent 事件,官方暂时没有
 * 修复计划,只能手动修复。
 * 通过监听 Spring Applicaiton finished 的回调
 * <p>
 * 此外,在外置 Tomcat 下,ManagementContext 无法另起端口,只能
 * 复用默认端口。通过 MXBeanServer 应该可以开启另一个监听端口,既然
 * 官方暂时未支持,我们也暂时不去修复。
 */
public clreplaced DiscoveryClientRegistrationInvoker implements ApplicationContextCustomizer<ConfigurableApplicationContext>, Ordered {

    @Autowired
    ServiceInstance serviceInstance;

    @Override
    public void customize(ConfigurableApplicationContext context) {
        if (context instanceof EmbeddedWebApplicationContext && !AdminEndpointApplicationRunListener.isEmbeddedServletServer(context.getEnvironment())) {
            MetaDataProvider metaDataProvider = context.getBean(MetaDataProvider.clreplaced);
            EmbeddedServletContainer embeddedServletContainer = new EmbeddedServletContainer() {

                @Override
                public void start() throws EmbeddedServletContainerException {
                }

                @Override
                public void stop() throws EmbeddedServletContainerException {
                }

                @Override
                public int getPort() {
                    return metaDataProvider.getServerPort();
                }
            };
            context.publishEvent(new EmbeddedServletContainerInitializedEvent((EmbeddedWebApplicationContext) context, embeddedServletContainer));
        }
    }

    @Override
    public int getOrder() {
        // Priority of AbstractDiscoveryLifecycle
        return -1;
    }
}

19 Source : DefaultServiceInstanceConverter.java
with Apache License 2.0
from SpringCloud

protected URI getServiceUrl(ServiceInstance instance) {
    return UriComponentsBuilder.fromUri(instance.getUri()).path("/").build().toUri();
}

19 Source : DefaultServiceInstanceConverter.java
with Apache License 2.0
from SpringCloud

protected Map<String, String> getMetadata(ServiceInstance instance) {
    return instance.getMetadata() != null ? instance.getMetadata() : emptyMap();
}

19 Source : DefaultServiceInstanceConverter.java
with Apache License 2.0
from SpringCloud

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();
}

19 Source : DefaultServiceInstanceConverter.java
with Apache License 2.0
from SpringCloud

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();
}

19 Source : DefaultResponse.java
with Apache License 2.0
from spring-cloud-incubator

/**
 * @author Spencer Gibb
 */
clreplaced DefaultResponse implements LoadBalancer.Response<ServiceInstance> {

    private final ServiceInstance serviceInstance;

    public DefaultResponse(ServiceInstance serviceInstance) {
        this.serviceInstance = serviceInstance;
    }

    @Override
    public boolean hreplacederver() {
        return serviceInstance != null;
    }

    @Override
    public ServiceInstance getServer() {
        return this.serviceInstance;
    }

    @Override
    public void onComplete(OnComplete onComplete) {
    // TODO: implement
    }
}

19 Source : DefaultReactiveResponse.java
with Apache License 2.0
from spring-cloud-incubator

/**
 * @author Spencer Gibb
 */
clreplaced DefaultReactiveResponse implements ReactiveLoadBalancer.Response<ServiceInstance> {

    private final ServiceInstance serviceInstance;

    public DefaultReactiveResponse(ServiceInstance serviceInstance) {
        this.serviceInstance = serviceInstance;
    }

    @Override
    public Mono<ServiceInstance> getServer() {
        return Mono.just(this.serviceInstance);
    }

    @Override
    public Mono<Void> onComplete(OnComplete onComplete) {
        // TODO: implement
        return Mono.empty();
    }
}

19 Source : DelegatingServiceInstance.java
with Apache License 2.0
from spring-cloud

/**
 * A {@link ServiceInstance} implementation that uses a delegate instance under the hood.
 *
 * @author Spencer Gibb
 */
public clreplaced DelegatingServiceInstance implements ServiceInstance {

    final ServiceInstance delegate;

    private String overrideScheme;

    public DelegatingServiceInstance(ServiceInstance delegate, String overrideScheme) {
        this.delegate = delegate;
        this.overrideScheme = overrideScheme;
    }

    @Override
    public String getServiceId() {
        return delegate.getServiceId();
    }

    @Override
    public String getHost() {
        return delegate.getHost();
    }

    @Override
    public int getPort() {
        return delegate.getPort();
    }

    @Override
    public boolean isSecure() {
        // TODO: move to map
        if ("https".equals(this.overrideScheme) || "wss".equals(this.overrideScheme)) {
            return true;
        }
        return delegate.isSecure();
    }

    @Override
    public URI getUri() {
        return delegate.getUri();
    }

    @Override
    public Map<String, String> getMetadata() {
        return delegate.getMetadata();
    }

    @Override
    public String getScheme() {
        String scheme = delegate.getScheme();
        if (scheme != null) {
            return scheme;
        }
        return this.overrideScheme;
    }
}

19 Source : ReactiveLoadBalancerClientFilter.java
with Apache License 2.0
from spring-cloud

protected URI reconstructURI(ServiceInstance serviceInstance, URI original) {
    return LoadBalancerUriTools.reconstructURI(serviceInstance, original);
}

19 Source : DtsLoadbalance.java
with Apache License 2.0
from spring-avengers

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();
    }
}

19 Source : ServiceChangedEvent.java
with Apache License 2.0
from open-hand

/**
 * 服务改变事件
 * @author XCXCXCXCX
 */
public clreplaced ServiceChangedEvent extends ApplicationEvent {

    private String serviceName;

    private ServiceInstance serviceInstance;

    public ServiceChangedEvent(Object source, String serviceName, ServiceInstance serviceInstance) {
        super(source);
        this.serviceName = serviceName;
        this.serviceInstance = serviceInstance;
    }

    public ServiceInstance getServiceInstance() {
        return serviceInstance;
    }

    public void setServiceInstance(ServiceInstance serviceInstance) {
        this.serviceInstance = serviceInstance;
    }

    public String getServiceName() {
        return serviceName;
    }

    public void setServiceName(String serviceName) {
        this.serviceName = serviceName;
    }
}

19 Source : ServiceChangedEvent.java
with Apache License 2.0
from open-hand

public void setServiceInstance(ServiceInstance serviceInstance) {
    this.serviceInstance = serviceInstance;
}

19 Source : ServiceInstanceUtils.java
with Apache License 2.0
from open-hand

public static String getValueFromMetadata(ServiceInstance serviceInstance, String key) {
    if (serviceInstance.getMetadata() == null) {
        throw new IllegalArgumentException("The serviceInstance object has no metadata!");
    }
    if (serviceInstance.getMetadata().get(key) == null) {
        throw new IllegalArgumentException("The serviceInstance's metadata has no the value {key = " + key + "}!");
    }
    return serviceInstance.getMetadata().get(key);
}

19 Source : ServiceInstanceUtils.java
with Apache License 2.0
from open-hand

public static String getManagementPortFromMetadata(ServiceInstance serviceInstance) {
    return getValueFromMetadata(serviceInstance, METADATA_MANAGEMENT_PORT, null);
}

19 Source : ServiceInstanceUtils.java
with Apache License 2.0
from open-hand

public static String getContextFromMetadata(ServiceInstance serviceInstance) {
    return getValueFromMetadata(serviceInstance, METADATA_CONTEXT, "");
}

19 Source : ServiceInstanceUtils.java
with Apache License 2.0
from open-hand

public static String getVersionFromMetadata(ServiceInstance serviceInstance) {
    return getValueFromMetadata(serviceInstance, METADATA_VERSION, NULL_VERSION);
}

19 Source : ServiceInstanceUtils.java
with Apache License 2.0
from open-hand

public static String getValueFromMetadata(ServiceInstance serviceInstance, String key, String defaultValue) {
    return serviceInstance.getMetadata() == null ? defaultValue : (serviceInstance.getMetadata().get(key) == null ? defaultValue : serviceInstance.getMetadata().get(key));
}

19 Source : ServiceInstanceUtils.java
with Apache License 2.0
from open-hand

public static boolean containTag(ServiceInstance instance, String tagKey) {
    if (StringUtils.isEmpty(tagKey)) {
        return true;
    }
    return instance.getMetadata().containsKey(tagKey);
}

19 Source : IntegrationConfiguration.java
with Apache License 2.0
from odrotbohm

@Bean
RemoteResource productResource() {
    ServiceInstance service = new DefaultServiceInstance("catalog", "localhost", 7071, false);
    return new DiscoveredResource(() -> service, traverson -> traverson.follow("events"));
}

19 Source : IntegrationConfiguration.java
with Apache License 2.0
from odrotbohm

@Bean
RemoteResource productResource() {
    ServiceInstance service = new DefaultServiceInstance("catalog", "localhost", 7070, false);
    return new DiscoveredResource(() -> service, traverson -> traverson.follow("events"));
}

19 Source : OrderApplication.java
with Apache License 2.0
from odrotbohm

@Bean
RemoteResource productResource() {
    ServiceInstance service = new DefaultServiceInstance("stores", "localhost", 6060, false);
    return new DiscoveredResource(() -> service, traverson -> traverson.follow("product"));
}

19 Source : ReservationClientApplication.java
with Apache License 2.0
from joshlong

private Flux<Reservation> call(ServiceInstance si) {
    return this.webClient.get().uri(uri(si)).retrieve().bodyToFlux(Reservation.clreplaced).doOnSubscribe((s) -> log.info("gonna send a request to " + si.getHost() + ':' + si.getPort())).doOnComplete(() -> log.info("finished processing request to " + si.getHost() + ':' + si.getPort()));
}

19 Source : ReservationClientApplication.java
with Apache License 2.0
from joshlong

private String uri(ServiceInstance si) {
    return "http://" + si.getHost() + ':' + si.getPort() + "/reservations";
}

19 Source : RemoteAppEventController.java
with Apache License 2.0
from huifer

/**
 * 给具体的服务发消息
 * http://localhost:9010/send/remote/event/cloud-bus/192.168.1.215/9010?data=1
 */
@PostMapping("/send/remote/event/{appName}/{ip}/{port}")
public String sendAppInterceptors(@PathVariable("appName") String appName, @PathVariable("ip") String ip, @PathVariable("port") int port, @RequestParam String data) {
    ServiceInstance instances = new DefaultServiceInstance(appName, ip, port, false);
    RemoteAppEvent remoteAppEvent = new RemoteAppEvent(data, currentAppName, appName, Arrays.asList(instances));
    publisher.publishEvent(remoteAppEvent);
    return "sendAppInterceptors  ok";
}

19 Source : InstanceServer.java
with Apache License 2.0
from HongZhaoHua

/**
 * 实例服务
 *
 * <pre>
 * 用于将ServiceInstance适配到Ribbon
 * </pre>
 *
 * @author Birdy
 */
public clreplaced InstanceServer extends Server {

    protected ServiceInstance instance;

    public InstanceServer(ServiceInstance instance) {
        super(instance.getScheme(), instance.getHost(), instance.getPort());
        this.instance = instance;
    }

    public Map<String, String> getMetadata() {
        return instance.getMetadata();
    }
}

19 Source : ServiceDescriptionUpdater.java
with Apache License 2.0
from hellosatish

private String getSwaggerURL(ServiceInstance instance) {
    String swaggerURL = instance.getMetadata().get(KEY_SWAGGER_URL);
    return swaggerURL != null ? instance.getUri() + swaggerURL : instance.getUri() + DEFAULT_SWAGGER_URL;
}

19 Source : RandomLoadBalancer.java
with Apache License 2.0
from fangjian0423

private Response<ServiceInstance> getInstanceResponse(List<ServiceInstance> instances) {
    if (instances.isEmpty()) {
        return new EmptyResponse();
    }
    int randomNum = random.nextInt(instances.size());
    System.out.println("random: " + randomNum);
    ServiceInstance instance = instances.get(randomNum);
    return new DefaultResponse(instance);
}

19 Source : ServiceInstanceSnitch.java
with Apache License 2.0
from cereebro

/**
 * Determine if a service instance contains enough Cereebro metadata.
 *
 * @param instance
 *            Service instance.
 * @return {@code true} if the {@link ServiceInstance} contains Cereebro
 *         metadata, {@code false} otherwise.
 */
public static boolean hasCereebroMetadata(ServiceInstance instance) {
    return extractSnitchURI(instance).isPresent();
}

19 Source : AcceptAllCommandsDiscoveryModeTest.java
with Apache License 2.0
from AxonFramework

@Test
void testCapabilitiesIsDelegated() {
    ServiceInstance testServiceInstance = mock(ServiceInstance.clreplaced);
    testSubject.capabilities(testServiceInstance);
    verify(delegate).capabilities(testServiceInstance);
}

19 Source : SpringCloudCommandRouter.java
with Apache License 2.0
from AxonFramework

/**
 * Instantiate a {@link Member} of type {@link java.net.URI} based on the provided {@code serviceInstance}. This
 * {@code Member} is later used to send, for example, {@link CommandMessage}s to.
 * <p>
 * A deviation is made between a local and a remote member, since if a local node is selected to handle the command,
 * the local command bus may be leveraged. The check if a {@link ServiceInstance} is local is based on two potential
 * situations:
 * <ol>
 *     <li>The given {@code serviceInstance} is identical to the {@code localServiceInstance} thus making it local.</li>
 *     <li>The URI of the given {@code serviceInstance} is identical to the URI of the {@code localServiceInstance}.</li>
 * </ol>
 * <p>
 * We take this route because we've identified that several Spring Cloud implementations do not contain any URI
 * information during the start up phase and as a side effect will throw exception if the URI is requested from it.
 * We thus return a simplified {@link Member} for the {@code localServiceInstance} to not trigger this exception.
 *
 * @param serviceInstance a {@link ServiceInstance} to build a {@link Member} for
 * @return a {@link Member} based on the contents of the provided {@code serviceInstance}
 */
protected Member buildMember(ServiceInstance serviceInstance) {
    return isLocalServiceInstance(serviceInstance) ? buildLocalMember(serviceInstance) : buildRemoteMember(serviceInstance);
}

19 Source : SpringCloudCommandRouter.java
with Apache License 2.0
from AxonFramework

private boolean isLocalServiceInstance(ServiceInstance serviceInstance) {
    return serviceInstance.equals(localServiceInstance) || Objects.equals(serviceInstance.getUri(), localServiceInstance.getUri());
}

19 Source : RestCapabilityDiscoveryMode.java
with Apache License 2.0
from AxonFramework

private boolean isLocalServiceInstance(ServiceInstance serviceInstance) {
    return Objects.equals(serviceInstance, localInstance.get()) || Objects.equals(serviceInstance.getUri(), localInstance.get().getUri());
}

19 Source : IgnoreListingDiscoveryMode.java
with Apache License 2.0
from AxonFramework

/**
 * Implementation of the {@link org.springframework.cloud.client.ServiceInstance} in some cases do no have an {@code
 * equals()} implementation. Thus we provide our own {@code equals()} function to match a given {@code
 * ignoredInstance} with another given {@code serviceInstance}. The match is done on the service id, host and port.
 *
 * @param serviceInstance A {@link org.springframework.cloud.client.ServiceInstance} to compare with the given
 *                        {@code ignoredInstance}
 * @param ignoredInstance A {@link org.springframework.cloud.client.ServiceInstance} to compare with the given
 *                        {@code serviceInstance}
 * @return True if both instances match on the service id, host and port, and false if they do not
 */
@SuppressWarnings("SimplifiableIfStatement")
private boolean equals(ServiceInstance serviceInstance, ServiceInstance ignoredInstance) {
    if (serviceInstance == ignoredInstance) {
        return true;
    }
    if (ignoredInstance == null) {
        return false;
    }
    return Objects.equals(serviceInstance.getServiceId(), ignoredInstance.getServiceId()) && Objects.equals(serviceInstance.getHost(), ignoredInstance.getHost()) && Objects.equals(serviceInstance.getPort(), ignoredInstance.getPort());
}

19 Source : DefaultServiceLoadBalancer.java
with Apache License 2.0
from apache

protected ServiceDefinition convertServiceInstanceToServiceDefinition(ServiceInstance instance) {
    return new DefaultServiceDefinition(instance.getServiceId(), instance.getHost(), instance.getPort(), instance.getMetadata());
}

19 Source : DelegatingRegistration.java
with Apache License 2.0
from alibaba

/**
 * The {@link Registration} of Dubbo uses an external of {@link ServiceInstance} instance
 * as the delegate.
 *
 * @author <a href="mailto:[email protected]">Mercy</a>
 */
clreplaced DelegatingRegistration implements Registration {

    private final ServiceInstance delegate;

    DelegatingRegistration(ServiceInstance delegate) {
        this.delegate = delegate;
    }

    @Override
    public String getServiceId() {
        return delegate.getServiceId();
    }

    @Override
    public String getHost() {
        return delegate.getHost();
    }

    @Override
    public int getPort() {
        return delegate.getPort();
    }

    @Override
    public boolean isSecure() {
        return delegate.isSecure();
    }

    @Override
    public URI getUri() {
        return delegate.getUri();
    }

    @Override
    public Map<String, String> getMetadata() {
        return delegate.getMetadata();
    }

    @Override
    public String getScheme() {
        return delegate.getScheme();
    }
}

18 Source : TestController.java
with MIT License
from xiuhuai

@GetMapping("/test")
public void test() {
    ServiceInstance serviceInstance = loadBalancerClient.choose("provider");
    System.out.println(serviceInstance.getHost() + serviceInstance.getPort() + " " + sdf.format(date));
}

18 Source : TestController.java
with MIT License
from xiuhuai

@GetMapping("/test")
public void LoadInstance() {
    /*
        * restTemplate.getForObject()与loadBalancerClient.choose不能放在一个方法中,因为restTemplate.getForObject()包含了choose方法
        *
        * */
    ServiceInstance serviceInstance = loadBalancerClient.choose("producer");
    System.out.println(serviceInstance.getHost() + serviceInstance.getPort());
}

18 Source : HelloController.java
with MIT License
from xiuhuai

/**
 * 调用服务提供者接口
 */
@GetMapping("/hello")
public String hello() {
    ServiceInstance serviceInstance = loadBalancer.choose("service-producer");
    URI uri = serviceInstance.getUri();
    String callService = new RestTemplate().getForObject(uri + "/hello", String.clreplaced);
    System.out.println(callService);
    return callService;
}

18 Source : HelloController.java
with MIT License
from xiuhuai

/**
 * 调用服务提供者接口
 */
@GetMapping("/hello")
public String hello() {
    ServiceInstance serviceInstance = loadBalancer.choose("service-provider");
    URI uri = serviceInstance.getUri();
    String callService = new RestTemplate().getForObject(uri + "/hello", String.clreplaced);
    System.out.println(callService);
    return callService;
}

18 Source : HelloController.java
with MIT License
from teruiV

@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String index() throws InterruptedException {
    ServiceInstance instance = client.getLocalServiceInstance();
    // 测试超时
    int sleepTime = new Random().nextInt(3000);
    logger.info("sleepTime:" + sleepTime);
    Thread.sleep(sleepTime);
    logger.info("/hello,host:" + instance.getHost() + " ,service_id " + instance.getServiceId());
    return "Hello World!";
}

18 Source : TestController.java
with Apache License 2.0
from SpringCloud

@GetMapping("/add1")
public void add1(Integer a, Integer b) {
    ServiceInstance instance = this.lbClient.choose("client-a");
    System.out.println(instance.getHost() + ":" + instance.getPort());
}

18 Source : TestController.java
with Apache License 2.0
from SpringCloud

@GetMapping("/add2")
public void add2(Integer a, Integer b) {
    ServiceInstance instance = this.lbClient.choose("client-b");
    System.out.println(instance.getHost() + ":" + instance.getPort());
}

18 Source : NacosAdapter.java
with Apache License 2.0
from Nepxion

@Override
public String getInstanceServiceId(ServiceInstance instance) {
    String instanceServiceId = super.getInstanceServiceId(instance);
    return filterServiceId(instanceServiceId);
}

18 Source : AbstractPluginAdapter.java
with Apache License 2.0
from Nepxion

@Override
public String getInstanceZone(ServiceInstance instance) {
    String instanceZone = getInstanceMetadata(instance).get(DiscoveryConstant.ZONE);
    if (StringUtils.isEmpty(instanceZone)) {
        instanceZone = DiscoveryConstant.DEFAULT;
    }
    return instanceZone;
}

18 Source : AbstractPluginAdapter.java
with Apache License 2.0
from Nepxion

@Override
public Map<String, String> getInstanceMetadata(ServiceInstance instance) {
    return instance.getMetadata();
}

18 Source : AbstractPluginAdapter.java
with Apache License 2.0
from Nepxion

@Override
public String getInstanceGroup(ServiceInstance instance) {
    String instanceGroupKey = getInstanceGroupKey(instance);
    String instanceGroup = getInstanceMetadata(instance).get(instanceGroupKey);
    if (StringUtils.isEmpty(instanceGroup)) {
        instanceGroup = DiscoveryConstant.DEFAULT;
    }
    return instanceGroup;
}

18 Source : VersionUpdateRestInvoker.java
with Apache License 2.0
from Nepxion

@Override
protected void checkPermission(ServiceInstance instance) throws Exception {
    checkDiscoveryControlPermission(instance);
    checkConfigRestControlPermission(instance);
}

18 Source : SentinelUpdateRestInvoker.java
with Apache License 2.0
from Nepxion

@Override
protected void checkPermission(ServiceInstance instance) throws Exception {
    checkConfigRestControlPermission(instance);
}

See More Examples