SpringCloud获取注册中心上服务列表

@DiscoveryClient注解

使用 @DiscoveryClient 获取服务列表

基于 SpringCloud整合Consul 我们修改一下 MemberApiController.java:

package com.baba.wlb.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
 * @Author wulongbo
 * @Date 2021/1/9 15:20
 * @Version 1.0
 */@RestController
public class MemberApiController {
    @Value("${server.port}")
    private String serverPort;
 @Autowired
 private DiscoveryClient discoveryClient;
 @RequestMapping("/getMember")
    public String getMember() {
        return "我是会员服务!端口号:" + serverPort;
 }
    @RequestMapping("/discoveryServer")
    public String discoveryServer() {
        List serviceInstances = discoveryClient.getInstances("consul-member");
 return serviceInstances.get(0).getHost() + serviceInstances.get(0).getPort();
 }
}

启动项目

启动 AppMember.java

浏览器访问 http://localhost:8501/discoveryServer

image.png

你可能感兴趣的:(javaspringboot)