如何从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 :(得分:4)
非常简单:)
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);
}
}
答案 1 :(得分:0)
或者,如果您不想在spring-boot / Eureka库的整个世界中拖延,而更喜欢“干净的”瘦客户机,则只需执行简单的GET即可
(10,10)
如此处Using Eureka as a registry using REST APIs所述,或者,正如我们所做的那样,利用springboot admin的API(例如,此处https://codecentric.github.io/spring-boot-admin/1.5.7/所述),并且只需进行简单的GET即可
http://<eureka host>:<port>/eureka/apps
同时使用基本身份验证标头提供登录凭据,即
http://<springbootadmin host>:<port>/api/applications
然后您将获得一个不错的JSON响应,可以轻松地利用JSON属性将其解析为java对象的集合
"Basic", java.util.Base64.getEncoder().encodeToString(("<springboot admin user>" + ":" + "<pwd>").getBytes());
例如。添加适当的基于toString()的hashcode()和equals(),无论您是要“在任何实例上”还是在唯一的实例上使用正在运行的服务集,都可以使用。