68 lines
3.0 KiB
Java
68 lines
3.0 KiB
Java
package com.bocloud.gateway.restful;
|
|
|
|
import com.alibaba.fastjson.JSONObject;
|
|
import com.megatron.common.model.GeneralResult;
|
|
import com.megatron.common.utils.ListTool;
|
|
import com.megatron.framework.core.RegistryService;
|
|
import com.megatron.framework.core.domain.ExtendServiceInstance;
|
|
import lombok.RequiredArgsConstructor;
|
|
import lombok.extern.slf4j.Slf4j;
|
|
import org.springframework.cloud.client.ServiceInstance;
|
|
import org.springframework.cloud.client.discovery.DiscoveryClient;
|
|
import org.springframework.cloud.zookeeper.discovery.ZookeeperServiceInstance;
|
|
import org.springframework.web.bind.annotation.GetMapping;
|
|
import org.springframework.web.bind.annotation.PathVariable;
|
|
import org.springframework.web.bind.annotation.RequestMapping;
|
|
import org.springframework.web.bind.annotation.RestController;
|
|
|
|
import java.util.HashMap;
|
|
import java.util.List;
|
|
import java.util.Map;
|
|
import java.util.Optional;
|
|
import java.util.stream.Collectors;
|
|
|
|
/**
|
|
* @author dmw
|
|
*/
|
|
@Slf4j
|
|
@RestController
|
|
@RequiredArgsConstructor
|
|
@RequestMapping("/actuator/services")
|
|
public class ServiceController {
|
|
private final DiscoveryClient discoveryClient;
|
|
private final RegistryService registryService;
|
|
|
|
@GetMapping
|
|
public GeneralResult<Map<String, List<ExtendServiceInstance>>> services() {
|
|
Map<String, List<ExtendServiceInstance>> serviceInstanceMap = new HashMap<>(16);
|
|
List<String> services = discoveryClient.getServices();
|
|
if (ListTool.hasElement(services)) {
|
|
services.forEach(service -> {
|
|
List<ServiceInstance> instances = this.discoveryClient.getInstances(service);
|
|
List<ExtendServiceInstance> serviceInstances = instances.stream().map(instance -> {
|
|
ExtendServiceInstance serviceInstance = new ExtendServiceInstance(service, ((ZookeeperServiceInstance) instance).getServiceInstance());
|
|
String state = null;
|
|
try {
|
|
state = this.registryService.getServiceState(service, instance.getHost() + ":" + instance.getPort());
|
|
} catch (Exception e) {
|
|
log.error("Get {} [{}:{}] service state error: {}", service, instance.getHost(), instance.getPort(), e.getMessage(), e);
|
|
}
|
|
Optional.ofNullable(state).ifPresent(s -> {
|
|
Map<String, Object> stateMap = JSONObject.parseObject(s).getInnerMap();
|
|
serviceInstance.setMetrics(stateMap);
|
|
});
|
|
return serviceInstance;
|
|
}).collect(Collectors.toList());
|
|
serviceInstanceMap.put(service, serviceInstances);
|
|
});
|
|
}
|
|
return new GeneralResult<>(true, serviceInstanceMap, "success");
|
|
}
|
|
|
|
@GetMapping("/{route}")
|
|
public GeneralResult<List<ServiceInstance>> instances(@PathVariable String route) {
|
|
List<ServiceInstance> instances = discoveryClient.getInstances(route);
|
|
return new GeneralResult<>(true, instances, "success");
|
|
}
|
|
}
|