2017-06-21 72 views
1

如何從eureka獲取已經註冊的服務?Eureka獲取服務列表

以下代碼給出了有關特定服務的詳細信息。但我想要註冊服務的列表。

代碼:

import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.boot.SpringApplication; 
import org.springframework.boot.autoconfigure.SpringBootApplication; 
import org.springframework.cloud.client.ServiceInstance; 
import org.springframework.cloud.client.discovery.DiscoveryClient; 
import org.springframework.cloud.client.discovery.EnableDiscoveryClient; 
import org.springframework.web.bind.annotation.PathVariable; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RestController; 

import java.util.List; 

@EnableDiscoveryClient 
@SpringBootApplication 
public class EurekaClientApplication { 

    public static void main(String[] args) { 
     SpringApplication.run(EurekaClientApplication.class, args); 
    } 
} 

@RestController 
class ServiceInstanceRestController { 

    @Autowired 
    private DiscoveryClient discoveryClient; 

    @RequestMapping("/service-instances/{applicationName}") 
    public List<ServiceInstance> serviceInstancesByApplicationName(
      @PathVariable String applicationName) { 
     return this.discoveryClient.getInstances(applicationName); 
    } 
} 
+0

https://stackoverflow.com/questions/42427492/eureka-server-list-all-registered-instances – StanislavL

回答

0

漂亮其實很簡單:)

 List<Application> applications = discoveryClient.getApplications().getRegisteredApplications(); 

    for (Application application : applications) { 
     List<InstanceInfo> applicationsInstances = application.getInstances(); 
     for (InstanceInfo applicationsInstance : applicationsInstances) { 

      String name = applicationsInstance.getAppName(); 
      String url = applicationsInstance.getHomePageUrl(); 
      System.out.println(name + ": " + url); 
     } 
    }