SpringCloud之网关获取注册中心的服务实例

Spring Cloud 获取注册中心所有服务以及服务下的所有实例

待用

/**
 * import org.springframework.cloud.client.ServiceInstance;
 * import org.springframework.cloud.client.discovery.DiscoveryClient;
 *
 * 获取每一个服务下面实例
 * 测试时,可以使用多个端口启动服务实例
 */

//感觉 DiscoveryClient 挺关键的保存了服务实例的详细信息
@Autowired
private DiscoveryClient discoveryClient;

@GetMapping("/serviceurl")
public Map<String, List<ServiceInstance>> serviceUrl() {
    Map<String, List<ServiceInstance>> msl = new HashMap<>();
    List<String> services = discoveryClient.getServices();
    for (String service : services) {
        List<ServiceInstance> sis = discoveryClient.getInstances(service);
        msl.put(service, sis);
    }
    return msl;
}

研究

DiscoveryClient.java

package org.springframework.cloud.client.discovery;

import java.util.List;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.core.Ordered;

public interface DiscoveryClient extends Ordered {
    int DEFAULT_ORDER = 0;

    String description();

    //获取服务的详细信息
    List<ServiceInstance> getInstances(String serviceId);

    //获取服务的名称,即 serviceId
    List<String> getServices();

    default int getOrder() {
        return 0;
    }
}

通过继承关系图发现有 NacosDiscoveryClient, 表明对 Nacos 注册中心有支持

SpringCloud之网关获取注册中心的服务实例_第1张图片

ServiceInstance.java

public interface ServiceInstance {
    default String getInstanceId() {
        return null;
    }

    String getServiceId();

    String getHost();

    int getPort();

    boolean isSecure();

    URI getUri();

    Map<String, String> getMetadata();

    default String getScheme() {
        return null;
    }
}

结果

{
    "code": 200,
    "count": null,
    "data": {
        "platform-sso": [
            {
                "host": "x.x.x.x",
                "instanceId": null,
                //注册中心的信息
                "metadata": {
                    "nacos.instanceId": "10.x.x.144#8777#DEFAULT#DEFAULT_GROUP@@platform-sso",
                    "nacos.weight": "1.0",
                    "nacos.cluster": "DEFAULT",
                    "nacos.healthy": "true",
                    "preserved.register.source": "SPRING_CLOUD"
                },
                "port": 8777,
                "scheme": null,
                "secure": false,
                "serviceId": "platform-sso",
                "uri": "http://10.x.x.144:8777"
            }
        ],
        "platform-gateway": [],
        "platform-apihub": []
    },
    "message": "操作成功"
}

你可能感兴趣的:(SpringCloud)