首先引入Nacos包
<dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency>spring-cloud-starter-alibaba-nacos-discovery-2.2.1.RELEASE.jar
在NacosStarter包中通过Spring的SPI加载了一系列配置
D:\mavenLocalRepository\com\alibaba\cloud\spring-cloud-starter-alibaba-nacos-discovery\2.2.1.RELEASE\spring-cloud-starter-alibaba-nacos-discovery-2.2.1.RELEASE.jar!\META-INF\spring.factories
其中有一个配置类,声明了NacosServiceRegister这个bean,放到SpringIOC中后边会用到
@AutoConfigureAfter({AutoServiceRegistrationConfiguration.class, AutoServiceRegistrationAutoConfiguration.class, NacosDiscoveryAutoConfiguration.class})
public class NacosServiceRegistryAutoConfiguration {
public NacosServiceRegistryAutoConfiguration() {
}
// Nacos服务注册类
@Bean
public NacosServiceRegistry nacosServiceRegistry(NacosDiscoveryProperties nacosDiscoveryProperties) {
return new NacosServiceRegistry(nacosDiscoveryProperties);
}
............................
POM文件中再整合DubboCloud,等于Dubbo使用Nacos作为注册中心来注册和发现服务
<dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-dubbo</artifactId> </dependency> spring-cloud-starter-dubbo-2.2.1.RELEASE.jar
在Dubbo中分两种情况,POM中配置了SpringWeb包是WEB环境,否则非WEB
非WEB环境配置使用Dubbo包下
com.alibaba.cloud.dubbo.autoconfigure.DubboServiceRegistrationNonWebApplicationAutoConfiguration#onApplicationStarted
WEB环境使用Nacos包下:com.alibaba.cloud.nacos.registry.NacosServiceRegistryAutoConfiguration#nacosAutoServiceRegistration
WEB环境:
在Nacos包下通过SPI向IOC添加Bean:NacosAutoServiceRegistration
public class NacosServiceRegistryAutoConfiguration {
public NacosServiceRegistryAutoConfiguration() {
}
..................................
@Bean
@ConditionalOnBean({AutoServiceRegistrationProperties.class})
public NacosAutoServiceRegistration nacosAutoServiceRegistration(NacosServiceRegistry registry, AutoServiceRegistrationProperties autoServiceRegistrationProperties, NacosRegistration registration) {
return new NacosAutoServiceRegistration(registry, autoServiceRegistrationProperties, registration);
}
NacosAutoServiceRegistration 这个Bean继承了 AbstractAutoServiceRegistration,而AbstractAutoServiceRegistration监听了WebServerInitializedEvent事件来完成注册。
public abstract class AbstractAutoServiceRegistration<R extends Registration> implements AutoServiceRegistration, ApplicationContextAware, ApplicationListener<WebServerInitializedEvent> {
private static final Log logger = LogFactory.getLog(AbstractAutoServiceRegistration.class);
..................
// 监听事件WebServerInitializedEvent ,代表WEB初始化完成后执行
publ