我们可以根据eurekaServer提供的请求路径获取注册实例的详细信息。
系统自身携带的参数信息我们称之为元数据。
- 获取当前注册的所有实例信息
http://{ip}:{port}/{context-path}/eureka/apps
- 根据实例名称获取实例信息
http://{ip}:{port}/{context-path}/eureka/apps/applicationName
上述是我们请求eurekaServer的对应路径获的,我们也可以通过代码在client中实现。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
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;
/**
* Created by py
* 2020/3/4
*/
@RestController
public class QueryServerInstanceController {
//注意该接口引用的包,netflix中也有一个,此处引用cloud的
@Autowired
private DiscoveryClient discoveryClient;
@RequestMapping("/getInstanceByApplicationName/{applicationName}")
public List<ServiceInstance> getInstance(@PathVariable String applicationName){
List<ServiceInstance> serveices = discoveryClient.getInstances(applicationName);
return serveices;
}
}
运行获得以下信息
我们也可以在注册的实例信息中添加自己的自定义参数,在客户端获取相关信息时就可以拿到对应的自定义数据了
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8701/eurekaServer2/eureka/
instance:
hostname: eurekaClient
#设置自定义参数信息
metadata-map:
TName: jack
TAge: 25
TSex: boy
查看获取信息
代码中获取自定义信息
@RequestMapping("/getInstanceByApplicationName/{applicationName}")
public List<ServiceInstance> getInstance(@PathVariable String applicationName){
//获取从注册中心拉取到的服务名称
List<String> list =discoveryClient.getServices();
//根据名称获取服务实例
List<ServiceInstance> serveices = discoveryClient.getInstances(applicationName);
for(ServiceInstance o : serveices){
//获取自定义数据的map
Map<String, String> map =o.getMetadata();
System.out.println(o.getMetadata().toString());
//todo 根据获取的自定义信息做自己需要的逻辑处理
}
return serveices;
}