Programmatically identify when a new instance of a microservice has been created or killed?

时间:2019-03-19 14:47:45

标签: spring spring-boot microservices spring-cloud spring-cloud-config

Is there a way to programmatically identify if the number of instances of a single microservices has reached a certain number at a given time? For instance: how can I know programmatically how many instances of my Account microservices there are running right now? Also, how to find out when that number changed?

My intention is to notify an admin when it goes over a threshold. I'm using Spring Boot with Spring Cloud, Spring Config and Consul as service discovery. I would be willing to change to Eureka if needed.

1 个答案:

答案 0 :(得分:2)

Well, based documentation you can use DiscoveryClient in order to get instances based on some service on the documentation example is "STORES", take a look, you can do it by following example:

@Autowired
private DiscoveryClient discoveryClient;

public List<ServiceInstance> getInstances(String serviceName) {
    List<ServiceInstance> list = discoveryClient.getInstances(serviceName);
    if (list != null && list.size() > 0 ) {
        // logic here if it is necessary. 
    }
    return list;
}