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>> services() { Map> serviceInstanceMap = new HashMap<>(16); List services = discoveryClient.getServices(); if (ListTool.hasElement(services)) { services.forEach(service -> { List instances = this.discoveryClient.getInstances(service); List 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 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> instances(@PathVariable String route) { List instances = discoveryClient.getInstances(route); return new GeneralResult<>(true, instances, "success"); } }