尽管说通过Eureka提供的管理界面和HTTP端点可以获取服务的详细信息,但是这还远远不够。在现实应用中,很多时候我们希望通过代码在运行时能够实时获取注册中心的服务列表。
在Eureka的客户端,我们通过Eureka提供的DiscoveryClient工具类就可以获取Eureka中注册的服务信息。
EurekaController
package com.lyc.goodsProduct.controller;
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.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
* @author: zhangzhenyi
* @date: 2019/3/15 20:39
* @description: Eureka Controller
@RestController
@RequestMapping("/eurekaCentre")
public class EurekaController {
@Autowired
private DiscoveryClient discoveryClient;
* 获取注册在Eureka中的服务名称
* @return
@GetMapping("/getEurekaServices")
public List<String> getEurekaServices(){
List<String> services = new ArrayList<>();
List<String> serviceNames = discoveryClient.getServices();
for(String serviceName : serviceNames){
List<ServiceInstance> serviceInstances = discoveryClient.getInstances(serviceName);
for(ServiceInstance serviceInstance : serviceInstances){
services.add(String.format("%s:%s",serviceName,serviceInstance.getUri()));
return services;
application.yml
# 服务名称
spring:
application:
name: product-service
# spring连接数据库驱动
datasource:
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/spring_data?useUnicode=true&characterEncoding=UTF-8&useSSL=false
username: root
password: zhangzhenyi
# jpa自动创建不存在的数据表
show-sql: true
hibernate:
ddl-auto: update
use-new-id-generator-mappings: true
jackson:
serialization:
indent_output: false
# 服务端口号
server:
port: 8081
eureka:
instance:
# 指明使用IP而不是服务名称来注册自身服务。因为Eureka默认是使用域名进行服务注册和解析
prefer-ip-address: true
client:
register-with-eureka: true
fetch-registry: true
service-url:
defaultZone: http://localhost:8761/eureka/,http://localhost:8762/eureka/
在浏览器中输入下列地址:
http://127.0.0.1:8081/eurekaCentre/getEurekaServices
其返回的服务列表如下:
"eureka-server:http://peer1:8761",
"eureka-server:http://peer2:8762",
"product-service:http://192.168.23.1:8081",
"product-service:http://192.168.23.1:8082",
"account-service:http://192.168.23.1:8084",
"order-service:http://192.168.23.1:8083"
从上面的代码中我们可以看到,在客户端想要获取Eureka中注册的服务信息时,其方法一共有两种,其一是通过HTTP直接调用Eureka注册中心,从中获取注册的服务信息;其二是通过DiscoveryClient,以Java代码的方式在客户端获取Eureka中注册的服务信息。