nacos是阿里巴巴开源的一个集注册中心和配置中心为一体的组件,先已加入到apache大家庭中。本文主要介绍nacos作为注册中心中的服务注册原理
首先,所有的服务注册功能,都使用一个相同的接口---ServiceRegistry
package org.springframework.cloud.client.serviceregistry;
/**
* Contract to register and deregister instances with a Service Registry.
*
* @author Spencer Gibb
* @since 1.2.0
*/
public interface ServiceRegistry<R extends Registration> {
/**
* Register the registration. Registrations typically have information about
* instances such as: hostname and port.
* @param registration the registraion
*/
void register(R registration);
/**
* Deregister the registration.
* @param registration
*/
void deregister(R registration);
/**
* Close the ServiceRegistry. This a lifecycle method.
*/
void close();
/**
* Sets the status of the registration. The status values are determined
* by the individual implementations.
*
* @see org.springframework.cloud.client.serviceregistry.endpoint.ServiceRegistryEndpoint
* @param registration the registration to update
* @param status the status to set
*/
void setStatus(R registration, String status);
/**
* Gets the status of a particular registration.
*
* @see org.springframework.cloud.client.serviceregistry.endpoint.ServiceRegistryEndpoint
* @param registration the registration to query
* @param <T> the type of the status
* @return the status of the registration
*/
<T> T getStatus(R registration);
}
这个接口中最重要的方法就是register()服务注册方法和deregister()服务注销方法
可以看到,这个方法是在类org.springframework.cloud.client.serviceregistry.AbstractAutoServiceRegistration中被调用
具体调用的方法在bind()方法中,调用了start()方法,然后在start()中调用了registry()
@EventListener(WebServerInitializedEvent.class)
public void bind(WebServerInitializedEvent event) {
ApplicationContext context = event.getApplicationContext();
if (context instanceof ConfigurableWebServerApplicationContext) {
if ("management".equals(
((ConfigurableWebServerApplicationContext) context).getServerNamespace())) {
return;
}
}
this.port.compareAndSet(0, event.getWebServer().getPort());
this.start();
}
public void start() {
if (!isEnabled()) {
i