如下图,org.springframework.cloud.spring-cloud-commons 包下定义了一系列接口,其中就包括serviceregistry 的系列规范,并通过SPI机制去调用接口实现。 在该包的META-INF/spring.factories 文件中,可以找到EnableAutoConfiguration.class 为key的value中有AutoServiceRegistrationAutoConfiguration.class 这一项。 来看看这个AutoServiceRegistrationAutoConfiguration 配置类: 对应的,在com.alibaba.cloud.nacos 包下(位于spring-cloud-starter-nacos-discovery jar包中)的META-INF/spring.fatories 有个nacos服务注册配置类,如下图: 这个NacosServiceRegistryAutoConfiguration 配置类就定义了上面SpringCloud的AutoServiceRegistration 接口的实现类:
package com.alibaba.cloud.nacos.registry;
...
@Configuration(proxyBeanMethods = false)
@EnableConfigurationProperties
@ConditionalOnNacosDiscoveryEnabled
@ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled",
matchIfMissing = true)
@AutoConfigureAfter({ AutoServiceRegistrationConfiguration.class,
AutoServiceRegistrationAutoConfiguration.class,
NacosDiscoveryAutoConfiguration.class })
public class NacosServiceRegistryAutoConfiguration {
@Bean
public NacosServiceRegistry nacosServiceRegistry(
NacosDiscoveryProperties nacosDiscoveryProperties) {
return new NacosServiceRegistry(nacosDiscoveryProperties);
}
@Bean
@ConditionalOnBean(AutoServiceRegistrationProperties.class)
public NacosRegistration nacosRegistration(
ObjectProvider<List<NacosRegistrationCustomizer>> registrationCustomizers,
NacosDiscoveryProperties nacosDiscoveryProperties,
ApplicationContext context) {
return new NacosRegistration(registrationCustomizers.getIfAvailable(),
nacosDiscoveryProperties, context);
}
@Bean
@ConditionalOnBean(AutoServiceRegistrationProperties.class)
public NacosAutoServiceRegistration nacosAutoServiceRegistration(
NacosServiceRegistry registry,
AutoServiceRegistrationProperties autoServiceRegistrationProperties,
NacosRegistration registration) {
return new NacosAutoServiceRegistration(registry,
autoServiceRegistrationProperties, registration);
}
}
NacosAutoServiceRegistration 中的register() 方法开始注册服务,整个调用流程为:
继续追根溯源,这个registry() 方法是在AbstractAutoServiceRegistration implements ApplicationListener<WebServerInitializedEvent> 类的onApplicationEvent() 方法(onApplicationEvent->bind->start->registey) 。 调用的心跳默认5秒一次,具体可参考BeatReactor 类中的buildBeatInfo() 方法,其中有个beatInfo.setPeriod(instance.getInstanceHeartBeatInterval()); 这里获取到一个常量5s。 更加详细的流程可以参考:源码阅读|年轻人可以不讲武德,但是你得会阅读Naocs源码
另外上面最后一步的NamingClientProxy 接口的实现如下,利用到了委托模式(delegate)也叫代理模式?:
|