上QQ阅读APP看书,第一时间看更新
Using discovery client programmatically
After client application startup, the list of registered services is fetched from the Eureka Server automatically. However, it might turn out to be necessary to use Eureka's client API programmatically. We have two possibilities:
- com.netflix.discovery.EurekaClient: It implements all HTTP API methods exposed by the Eureka Server, which have been described in the Eureka API section.
- org.springframework.cloud.client.discovery.DiscoveryClient: It is a Spring Cloud alternative to the native Netflix EurekaClient. It provides a simple, generic API useful for all of the discovery clients. There are two methods available, getServices and getInstances:
private static final Logger LOGGER = LoggerFactory.getLogger(ClientController.class);
@Autowired
private DiscoveryClient discoveryClient;
@GetMapping("/ping")
public List<ServiceInstance> ping() {
List<ServiceInstance> instances = discoveryClient.getInstances("CLIENT-SERVICE");
LOGGER.info("INSTANCES: count={}", instances.size());
instances.stream().forEach(it -> LOGGER.info("INSTANCE: id={}, port={}", it.getServiceId(), it.getPort()));
return instances;
}
There is one interesting thing related to the preceding implementation. If you call the /ping endpoint just after the service startup, it won't display any instances. This is related to the response caching mechanisms and it is described in detail in the next section.