本文整理匯總了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;
}
示例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;
}
示例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;
}
}
示例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));
}
示例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);
}
示例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);
}
示例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;
}
示例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);
}
}
示例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();
}
}
}
示例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;
}
示例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;
}
示例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();
}
示例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;
}
示例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);
}