在Spring Cloud中,可以使用Spring Cloud Alibaba Nacos Discovery来从Nacos服务器获取所有微服务的地址。你需要在你的微服务中添加以下依赖:
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
然后在application.properties或application.yml中配置Nacos服务器的地址:
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
然后注入DiscoveryClient
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class ServiceController {
@Autowired
private DiscoveryClient discoveryClient;
@GetMapping("/services")
public List<String> getServices() {
return discoveryClient.getServices();
}
}
根据服务名称获得ip跟端口
List<ServiceInstance> instances = discoveryClient.getInstances("xxx");
for (ServiceInstance instance : instances) {
System.out.println(instance.getHost() + ":" + instance.getPort());
}
over~~