当前位置: 首页>>代码示例>>Java>>正文


Java ServiceInstance类代码示例

本文整理汇总了Java中org.springframework.cloud.client.ServiceInstance的典型用法代码示例。如果您正苦于以下问题:Java ServiceInstance类的具体用法?Java ServiceInstance怎么用?Java ServiceInstance使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


ServiceInstance类属于org.springframework.cloud.client包,在下文中一共展示了ServiceInstance类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: receiveServiceStatus

import org.springframework.cloud.client.ServiceInstance; //导入依赖的package包/类
private Map<String, String> receiveServiceStatus(List<ServiceInstance> instances) {
    if (CollectionUtils.isEmpty(instances)) {
        return Collections.emptyMap();
    }
    Map<String, String> instancesStatus = new HashMap<>();

    instances.stream()
        .filter(serviceInstance -> serviceInstance.getUri() != null)
        .forEach(instance -> {
            String uri = instance.getUri().toString();
            String status;
            try {
                Map body = restTemplate.exchange(
                    String.format("%s/management/health", uri),
                    HttpMethod.GET, null, Map.class).getBody();
                status = (String) body.get(STATUS);
            } catch (RestClientException e) {
                log.error("Error occurred while getting status of the microservice by URI {}",
                    uri, e);
                status = "DOWN";
            }
            instancesStatus.put(uri, status);
        });
    return instancesStatus;
}
 
开发者ID:xm-online,项目名称:xm-gate,代码行数:26,代码来源:GatewayResource.java

示例2: getInstances

import org.springframework.cloud.client.ServiceInstance; //导入依赖的package包/类
@Override
public List<ServiceInstance> getInstances(final String serviceId) {
  DiscoveryContext context = new DiscoveryContext();
  context.setInputParameters(serviceId);
  DiscoveryTree discoveryTree = discoveryTrees.computeIfAbsent(serviceId, key -> {
    return new DiscoveryTree();
  });
  VersionedCache serversVersionedCache = discoveryTree.discovery(context,
      RegistryUtils.getAppId(),
      serviceId,
      DefinitionConst.VERSION_RULE_ALL);
  Map<String, MicroserviceInstance> servers = serversVersionedCache.data();
  List<ServiceInstance> instances = new ArrayList<>(servers.size());
  for (MicroserviceInstance s : servers.values()) {
    for (String endpoint : s.getEndpoints()) {
      URIEndpointObject uri = new URIEndpointObject(endpoint);
      instances.add(new DefaultServiceInstance(serviceId, uri.getHostOrIp(), uri.getPort(), uri.isSslEnabled()));
    }
  }
  return instances;
}
 
开发者ID:apache,项目名称:incubator-servicecomb-java-chassis,代码行数:22,代码来源:CseDiscoveryClient.java

示例3: refreshRoute

import org.springframework.cloud.client.ServiceInstance; //导入依赖的package包/类
@PostMapping("refreshRoute")
public String refreshRoute() {
    List<String> serList = discoveryClient.getServices();
    if (serList.contains(MS_GATEWAY)) {
        List<ServiceInstance> instances = discoveryClient.getInstances(MS_GATEWAY);
        List<String> failInstances = new ArrayList<>();
        List<String> successInstances = new ArrayList<>();
        instances.forEach(instance -> {
            try {
                String url = instance.getUri().toURL().toString() ;
                restTemplate.postForObject(url+"/refreshRoute", null, Void.class, "");
                successInstances.add(instance.getUri().toURL().toString());
            } catch (Exception e) {
                try {
                    log.error("[ERROR===>>>]更新路由失败!实例是:" + instance.getUri().toURL().toString() , e);
                    failInstances.add(instance.getUri().toURL().toString());
                } catch (MalformedURLException e1) {
                    log.error("[ERROR===>>>]更新路由失败!" , e1);
                }
            }
        });
        return "[ERROR===>>>]更新完毕。更新成功的实例有:"+ successInstances.toString() +";更新失败的实例有:" + failInstances.toString() + "。";
    } else {
        return "[ERROR===>>>]没有找到服务:" + MS_GATEWAY;
    }
}
 
开发者ID:Paleozoic,项目名称:spring_cloud_demo,代码行数:27,代码来源:RouteAdminRest.java

示例4: add

import org.springframework.cloud.client.ServiceInstance; //导入依赖的package包/类
@RequestMapping(value = "/add" ,method = RequestMethod.GET)
@HystrixCommand
public String add(@RequestParam String name) {
    ServiceInstance instance = client.getLocalServiceInstance();
    if(cache.containsKey(name)){
        logger.info("/add, host:" + instance.getHost() + ", service_id:" + instance.getServiceId() + ", from cache");
        return getJSON(cache.get(name));
    }
    logger.info("/add, host:" + instance.getHost() + ", service_id:" + instance.getServiceId() + ", from insert");
    Map<String,Object> o=Maps.newConcurrentMap();
    o.put("订单发生时间",System.currentTimeMillis());
    o.put("订单发生人",name);
    o.put("订单号",orderNo.getAndIncrement());
    cache.put(name,o);
    return getJSON(cache.get(name));
}
 
开发者ID:DemoHubs,项目名称:hlxy-docker,代码行数:17,代码来源:OrderController.java

示例5: discoveryClientWithOneServiceInstanceWithoutMetadataShouldUseServiceInstanceIdAndUri

import org.springframework.cloud.client.ServiceInstance; //导入依赖的package包/类
@Test
public void discoveryClientWithOneServiceInstanceWithoutMetadataShouldUseServiceInstanceIdAndUri() {
    String serviceId = "serviceId";
    URI uri = URI.create("http://service-instance-uri");
    Mockito.when(discoveryClient.getServices()).thenReturn(Lists.newArrayList(serviceId));
    ServiceInstance serviceInstanceMock = Mockito.mock(ServiceInstance.class);
    Mockito.when(serviceInstanceMock.getUri()).thenReturn(uri);
    Mockito.when(serviceInstanceMock.getServiceId()).thenReturn(serviceId);
    Mockito.when(discoveryClient.getInstances(serviceId)).thenReturn(Lists.newArrayList(serviceInstanceMock));
    DiscoveryClientSnitchRegistry registry = new DiscoveryClientSnitchRegistry(discoveryClient, objectMapper);
    Assertions.assertThat(registry.getAll()).hasSize(1);
    Snitch snitch = registry.getAll().get(0);
    Assertions.assertThat(snitch).isInstanceOf(ServiceInstanceSnitch.class);
    Assertions.assertThat(snitch.getUri()).isEqualTo(uri);
    Component component = Component.of(serviceId, ComponentType.HTTP_APPLICATION);
    SystemFragment expected = SystemFragment.of(ComponentRelationships.of(component, new HashSet<>()));
    Assertions.assertThat(snitch.snitch()).isEqualTo(expected);
}
 
开发者ID:cereebro,项目名称:cereebro,代码行数:19,代码来源:EurekaSnitchRegistryTest.java

示例6: activeRoutes

import org.springframework.cloud.client.ServiceInstance; //导入依赖的package包/类
/**
 * GET  /routes : get the active routes.
 *
 * @return the ResponseEntity with status 200 (OK) and with body the list of routes
 */
@GetMapping("/routes")
@Timed
public ResponseEntity<List<RouteVM>> activeRoutes() {
    List<Route> routes = routeLocator.getRoutes();
    List<RouteVM> routeVMs = new ArrayList<>();
    routes.forEach(route -> {
        RouteVM routeVM = new RouteVM();
        routeVM.setPath(route.getFullPath());
        routeVM.setServiceId(route.getId());
        List<ServiceInstance> serviceInstances = discoveryClient.getInstances(route.getId());
        routeVM.setServiceInstances(serviceInstances);
        routeVM.setServiceInstancesStatus(receiveServiceStatus(serviceInstances));
        routeVM.setServiceMetadata(extractServiceMetaData(routeVM));
        routeVMs.add(routeVM);
    });
    return new ResponseEntity<>(routeVMs, HttpStatus.OK);
}
 
开发者ID:xm-online,项目名称:xm-gate,代码行数:23,代码来源:GatewayResource.java

示例7: extractServiceMetaData

import org.springframework.cloud.client.ServiceInstance; //导入依赖的package包/类
private Map<String, Object> extractServiceMetaData(RouteVM routeVM) {
    Objects.requireNonNull(routeVM,
        "Can't extract service metadata because routeVM is not pass");

    Map<String, String> serviceInstancesStatus = routeVM.getServiceInstancesStatus();
    if (MapUtils.isEmpty(serviceInstancesStatus)) {
        log.error("Microservice instances has no statuses");
        return null;
    }
    Map<String, Object> result = null;
    for (ServiceInstance instance : routeVM.getServiceInstances()) {
        if (instance.getUri() == null || StringUtils.isBlank(instance.getUri().toString())) {
            continue;
        }
        String uri = instance.getUri().toString();
        if ("UP".equals(serviceInstancesStatus.get(uri))) {
            if (result == null) {
                result = new HashMap<>();
            }
            result.put(uri, getInstanceInfo(uri));
        }
    }
    return result;
}
 
开发者ID:xm-online,项目名称:xm-gate,代码行数:25,代码来源:GatewayResource.java

示例8: getInstances

import org.springframework.cloud.client.ServiceInstance; //导入依赖的package包/类
@Override
public List<ServiceInstance> getInstances(String serviceId) {
  String prefix = properties.getPrefix() + "/" + serviceId;
  GetOption option = GetOption.newBuilder()
          .withPrefix(fromString(prefix))
          .withKeysOnly(true)
          .build();

  try {
    GetResponse response = etcdClient.getKVClient().get(fromString(prefix), option)
            .get();

    return response.getKvs().stream()
            .map(KeyValue::getKey)
            .map(ByteSequence::toStringUtf8)
            .map(key -> {
              String address = key.replace(prefix, "").substring(1);
              String[] ipAndPort = address.split(":");
              return new DefaultServiceInstance(serviceId, ipAndPort[0], Integer.parseInt(ipAndPort[1]), false);
            })
            .collect(Collectors.toList());
  } catch (InterruptedException | ExecutionException e) {
    throw new EtcdOperationException(e);
  }
}
 
开发者ID:ScienJus,项目名称:spring-cloud-etcd,代码行数:26,代码来源:EtcdDiscoveryClient.java

示例9: greet

import org.springframework.cloud.client.ServiceInstance; //导入依赖的package包/类
public void greet(String name, String message) {

        if (discoveryClient == null) {
            logger.info("Discovery client is null");
        } else {
            logger.info("Discovery client is not null");
            try {
                List<ServiceInstance> servers = discoveryClient.getInstances("service-account");

                for (ServiceInstance server : servers) {
                    String hostName = server.getHost();
                    int gRpcPort = Integer.parseInt(server.getMetadata().get("grpc.port"));
                    logger.info("=====>> " + hostName + " ---- " + gRpcPort);

                    final ManagedChannel channel = ManagedChannelBuilder.forAddress(hostName, gRpcPort)
                            .usePlaintext(true)
                            .build();
                    final GreetingGrpc.GreetingFutureStub stub = GreetingGrpc.newFutureStub(channel);

                    stub.sayHi(HelloRequest.newBuilder().setName(name).setMessage(message).build());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
 
开发者ID:imrenagi,项目名称:microservice-skeleton,代码行数:27,代码来源:GreeterServiceConsumer.java

示例10: getOkServer

import org.springframework.cloud.client.ServiceInstance; //导入依赖的package包/类
@Override
public Server getOkServer() {

    List<ServiceInstance> serviceInstances =  discoveryClient.getInstances(SOCKET_SERVER_KEY);

    //选取socket服务
    if (serviceInstances != null && serviceInstances.size() > 0 ) {
        for(ServiceInstance instance : serviceInstances){
            URI uri = instance.getUri();
            if (uri !=null ) {
                Server server =  restTemplate.getForObject(uri+"/socket/getServer",Server.class);
                if(server.getNowCount()<=server.getMaxCount()){
                    return server;
                }
            }
        }
    }

    return null;
}
 
开发者ID:1991wangliang,项目名称:sds,代码行数:21,代码来源:DeliveryServerServiceImpl.java

示例11: serverList

import org.springframework.cloud.client.ServiceInstance; //导入依赖的package包/类
@Override
public List<Server> serverList() {
    List<ServiceInstance> serviceInstances =  discoveryClient.getInstances(SOCKET_SERVER_KEY);

    List<Server> servers = new ArrayList<>();

    //选取socket服务
    if (serviceInstances != null && serviceInstances.size() > 0 ) {
        for(ServiceInstance instance : serviceInstances){
            URI uri = instance.getUri();
            if (uri !=null ) {
                Server server =  restTemplate.getForObject(uri+"/socket/getServer",Server.class);
                servers.add(server);
            }
        }
    }

    return servers;
}
 
开发者ID:1991wangliang,项目名称:sds,代码行数:20,代码来源:DeliveryServerServiceImpl.java

示例12: tryToFindInstances

import org.springframework.cloud.client.ServiceInstance; //导入依赖的package包/类
private Optional<List<ServiceInstance>> tryToFindInstances () {
    for (int i = 0; i < 5; i++) {
        List<ServiceInstance> instances = discoveryClient.getInstances(haselcastNodeServiceId);
        if (instances != null && !instances.isEmpty()) {
            return Optional.of(instances);
        }

        // retry
        try {
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException almostIgnore) {
            Thread.currentThread().interrupt();
        }
    }
    return Optional.empty();
}
 
开发者ID:xxlabaza,项目名称:hazelcast_eureka,代码行数:17,代码来源:EurekaDiscoveryStrategy.java

示例13: shouldAggregateAllValidNodesOnSingleServiceWithoutInstances

import org.springframework.cloud.client.ServiceInstance; //导入依赖的package包/类
@Test
public void shouldAggregateAllValidNodesOnSingleServiceWithoutInstances() {
    aggregator = spy(new HealthIndicatorsAggregator(discoveryClient, uriResolver, properties, caller, errorHandler, converter, securityStrategyFactory));

    Observable observable = Observable.from(asList("svc1", "error", "svc3"))
            .subscribeOn(Schedulers.io()).publish().autoConnect();
    doReturn(observable).when(aggregator).getServiceIdsFromDiscoveryClient();
    when(discoveryClient.getInstances(startsWith("svc"))).then(i -> {
        ServiceInstance serviceInstance = mock(ServiceInstance.class);
        when(serviceInstance.getServiceId()).thenReturn(i.getArgumentAt(0, String.class));
        return asList(serviceInstance);
    });
    when(discoveryClient.getInstances(startsWith("error"))).thenReturn(new ArrayList<>());
    when(uriResolver.resolveHealthCheckUrl(any(ServiceInstance.class)))
            .then(i -> i.getArgumentAt(0, ServiceInstance.class).getServiceId());
    doAnswer(i -> Observable.from(asList(new Node(i.getArgumentAt(0, String.class)))))
            .when(aggregator).getHealthNodesFromService(anyString(), anyString(), any());

    TestSubscriber<Node> testSubscriber = new TestSubscriber<>();
    aggregator.aggregateNodes().toBlocking().subscribe(testSubscriber);
    List<Node> nodes = testSubscriber.getOnNextEvents();
    assertThat(nodes).extracting("id").containsExactly("svc1", "svc3");
    testSubscriber.assertNoErrors();
    verify(errorHandler, times(1)).handleSystemError(anyString(), any(Throwable.class));
}
 
开发者ID:ordina-jworks,项目名称:microservices-dashboard-server,代码行数:26,代码来源:HealthIndicatorsAggregatorTest.java

示例14: getInstances

import org.springframework.cloud.client.ServiceInstance; //导入依赖的package包/类
private List<ServiceInstance> getInstances(Map<String, String> queryMap) throws MarathonException {
    List<ServiceInstance> instances = new ArrayList<>();

    GetAppsResponse appsResponse = queryMap == null ? client.getApps() : client.getApps(queryMap);

    if (appsResponse != null && appsResponse.getApps() != null) {
        List<App> apps = appsResponse.getApps();

        log.debug("Discovered {} service{}{}", apps.size(), apps.size() == 1 ? "" : "s", queryMap == null ? "" : String.format(" with ids that contain [%s]", queryMap.get("id")));

        for (App app : apps) {
            // Fetch data for this specific service id, to collect task information
            GetAppResponse response = client.getApp(app.getId());

            if (response != null && response.getApp() != null) {
                instances.addAll(extractServiceInstances(response.getApp()));
            }
        }
    }

    return instances;
}
 
开发者ID:aatarasoff,项目名称:spring-cloud-marathon,代码行数:23,代码来源:MarathonDiscoveryClient.java

示例15: filter

import org.springframework.cloud.client.ServiceInstance; //导入依赖的package包/类
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
	URI url = exchange.getAttribute(GATEWAY_REQUEST_URL_ATTR);
	if (url == null || !url.getScheme().equals("lb")) {
		return chain.filter(exchange);
	}
	//preserve the original url
	addOriginalRequestUrl(exchange, url);

	log.trace("LoadBalancerClientFilter url before: " + url);

	final ServiceInstance instance = loadBalancer.choose(url.getHost());

	if (instance == null) {
		throw new NotFoundException("Unable to find instance for " + url.getHost());
	}

	URI uri = exchange.getRequest().getURI();
	URI requestUrl = loadBalancer.reconstructURI(instance, uri);

	log.trace("LoadBalancerClientFilter url chosen: " + requestUrl);
	exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, requestUrl);
	return chain.filter(exchange);
}
 
开发者ID:spring-cloud,项目名称:spring-cloud-gateway,代码行数:25,代码来源:LoadBalancerClientFilter.java


注:本文中的org.springframework.cloud.client.ServiceInstance类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。