spring-cloud-zookeeper
spring-cloud-zookeeper copied to clipboard
NullPointerException for ZookeeperAutoServiceRegistration
ZookeeperAutoServiceRegistration throws an exception when ServiceInstanceRegistration method getServiceInstance() is called before ZookeeperAutoServiceRegistration method getPort()
It happens because method getServiceInstance()
calls build()
and when getPort()
will be called it will return null instead 0.
https://github.com/spring-cloud/spring-cloud-zookeeper/blob/ec845a47a00d560e6cf234a342fd31614823a20c/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/serviceregistry/ServiceInstanceRegistration.java#L64-L69
https://github.com/spring-cloud/spring-cloud-zookeeper/blob/ec845a47a00d560e6cf234a342fd31614823a20c/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/serviceregistry/ServiceInstanceRegistration.java#L71-L73
https://github.com/spring-cloud/spring-cloud-zookeeper/blob/ec845a47a00d560e6cf234a342fd31614823a20c/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/serviceregistry/ServiceInstanceRegistration.java#L83-L88
https://github.com/spring-cloud/spring-cloud-zookeeper/blob/ec845a47a00d560e6cf234a342fd31614823a20c/spring-cloud-zookeeper-discovery/src/main/java/org/springframework/cloud/zookeeper/serviceregistry/ZookeeperAutoServiceRegistration.java#L70-L79
Also getInstanceId()
method returns null.
Use case when we need to call getServiceInstance
for example to create leader candidate and associate with registration id for further understanding which node is a leader.
@Bean
public DefaultCandidate bean(ServiceInstanceRegistration registration) {
return return new DefaultCandidate(registration.getServiceInstance().getId(), "default");
}
As workaround for fixing this: before calling registration.getServiceInstance()
this line should be called registration.setPort(0);
For example:
@Bean
public DefaultCandidate bean(ServiceInstanceRegistration registration) {
registration.setPort(0);
return return new DefaultCandidate(registration.getServiceInstance().getId(), "default");
}
Not so elegant solution, but it works.