Spring cloud DiscoveryClient. getLocalServiceInstance() deprecated, how to use Registration?

2.1k Views Asked by At

I have a requirement to get the current instance-id of the running microservice, the problem is that I have the requirement that if the process is not registered a "random generated" instance id has to be provided.

I'm trying to get the service instance id from the DiscoveryClient but as the code points out the getLocalServiceInstance is deprecated and I can't use it.

I tried to use the Registration as stated in the javadoc but coudn't find a way to get it initialized.

Is there a conventional/specific way to get a service own registration?

Btw, I cannot use a direct implementation because it is a starter that does not know what DiscoveryService implementation will be available at runtime.

/**
 * @deprecated use the {@link org.springframework.cloud.client.serviceregistry.Registration} bean instead
 *
 * @return ServiceInstance with information used to register the local service
 */
@Deprecated
ServiceInstance getLocalServiceInstance();
2

There are 2 best solutions below

0
On

Code

discoveryClient.getServices().forEach(id -> {
            discoveryClient.getInstances(id).forEach(instance -> {
                logger.info("/hello, host:" + instance.getHost() + ", service_id:" + instance.getServiceId());
            });
        });
0
On

We can directly inject a Registration bean to do that, since class Registration is an abstraction, it should be adapted by different discovery clients, like if you are using Eureka, it will be an EurekaRegistration instance. For getting service instanceId, we can use the following code:

@Resource
private Registration serviceRegistration;

public Object someMethod() {
    //...
    String instanceId = serviceRegistration.getInstanceId();
    //...
}

we can also customize the instanceId by using eureka.instance.instance-id property in application.yml, see spring eureka instanceId answer.