Nacos服务注册与发现中心之服务注册
本文只介绍nacos的服务注册与发现中心功能中的服务提供者,在启动时与nacos服务器的交互,使用的是SpringCloud(Hoxton.SR12)集成Nacos1.0,其他集成方式不作介绍。
入口类及具体方法
服务注册的入口类为:AbstractAutoServiceRegistration.java
此类的类图为:

- 此类实现了ApplicationListener接口,用于监听WebServerInitializedEvent事件,该事件是web容器在准备完毕后发送的事件,关于此事件的介绍为:
* Event to be published when the {@link WebServer} is ready. Useful for obtaining the
* local port of a running server.
大概意思为:该事件是在web容器准备好(此处理解为初始化完毕,具体怎么算初始化完毕还没有找到相关定义,但是起码是已经完成了端口的监听)发布,用于获取运行中的服务端的本地端口
- AbstractAutoServiceRegistration类监听WebServerInitializedEvent事件的代码为:
public void onApplicationEvent(WebServerInitializedEvent event) {
bind(event);
}
- AbstractAutoServiceRegistration.bind(WebServerInitializedEvent event) 方法为:
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();
}
可以看出这个方法主要是设置了port变量的值为web容器监听的端口的值,而具体的逻辑在start()方法上。
- AbstractAutoServiceRegistration.start() 方法:
public void start() {
... //去掉不关心的代码
if (!this.running.get()) {
this.context.publishEvent(
new InstancePreRegisteredEvent(this, getRegistration()));
register();
if (shouldRegisterManagement()) {
registerManagement();
}
this.context.publishEvent(
new InstanceRegisteredEvent<>(this, getConfiguration()));
this.running.compareAndSet(false, true);
}
}
此处我们看到最终会调用register()方法进行服务的注册,而接下来就要说到Nacos提供的NacosAutoServiceRegistration类。
NacosAutoServiceRegistration
先来看看NacosAutoServiceRegistration的类图

可以看到,此类是继承了AbstractAutoServiceRegistration类。翻看代码发现他重写了AbstractAutoServiceRegistration的register()方法:
@Override
protected void register() {
if (!this.registration.getNacosDiscoveryProperties().isRegisterEnabled()) {
log.debug("Registration disabled.");
return;
}
if (this.registration.getPort() < 0) {
this.registration.setPort(getPort

&spm=1001.2101.3001.5002&articleId=125537131&d=1&t=3&u=28d9d114e0e9421dbe6eab90aead27cd)
3609





