在本地环境中使用Spring DiscoveryClient的方法如下所示:
在pom.xml文件中添加Eureka客户端依赖:
org.springframework.cloud
spring-cloud-starter-netflix-eureka-client
2.0.2.RELEASE
在应用程序的配置文件中添加以下信息以连接Eureka服务器:
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
在您的代码中,使用@Autowired注解注入DiscoveryClient:
@Autowired
private DiscoveryClient discoveryClient;
这将使您的应用程序获得一个对DiscoveryClient的引用,以便在需要时使用它。例如,您可以使用以下方法获取已注册的服务列表:
List instances = discoveryClient.getInstances("myservice");
您还可以使用其他DiscoveryClient方法来检索有关服务的其他信息。
请注意,您需要在本地运行Eureka服务器才能使用DiscoveryClient。可以通过添加以下依赖来在应用程序中启动Eureka服务器:
org.springframework.cloud
spring-cloud-starter-netflix-eureka-server
2.0.2.RELEASE
然后,在您的代码中,使用@EnableEurekaServer注解启动Eureka服务器:
@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}