微服务学习-SpringCloud -Nacos (服务注册源码学习)

源码版本及下载

此次源码版本为1.4.1,2.x版本在服务请求时使用了grpc的方式,所以先以1.4.1版本学习,后续再看2.x版本。
源码下载地址:: link
打开页面后,下拉到最下面,下载nacos-1.4.1.zip,解压导入idea即可。

服务注册核心流程图(看不清请双击打开大图)

请添加图片描述
此图主要是对核心注册流程进行了大概梳理,可以在后续详细看源码时配合互补。

源码详解

客户端注册源码

在微服务使用nacos需要在pom文件中引入依赖:

<dependency>
	<groupId>com.alibaba.cloud</groupId>
	<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
	<version>2.2.5.RELEASE</version>
</dependency>
  • 开始分析客户端源码
    SpringCloud这一套组件都是基于SpringBoot开发的,那么SpringBoot引入其它组件的方式是什么呢?
    自动装配
    所以第一步,我们先找它的在自动装配类。
    在这里插入图片描述
    打开文件:
    在这里插入图片描述
    由类名推断服务注册的自动装配类为:
    com.alibaba.cloud.nacos.registry.NacosServiceRegistryAutoConfiguration
    我们打开此类:
    在这里插入图片描述
    对应我画的流程图,我们重点关注第一个和第三个bean。
    先看NacosAutoServiceRegistration。
    当Springboot启动时,会发布事件。我们来看NacosAutoServiceRegistration,继承了AbstractAutoServiceRegistration,
    在这里插入图片描述
    在看AbstractAutoServiceRegistration类,我们发现它实现了ApplicationListener。
    在这里插入图片描述
    当我们实现了ApplicationListener时,我们就需要实现它的onApplicationEvent方法。
  public void onApplicationEvent(WebServerInitializedEvent event) {
        this.bind(event);
    }

    /** @deprecated */
    @Deprecated
    public void bind(WebServerInitializedEvent event) {
        ApplicationContext context = event.getApplicationContext();
        if (!(context instanceof ConfigurableWebServerApplicationContext) || !"management".equals(((ConfigurableWebServerApplicationContext)context).getServerNamespace())) {
            this.port.compareAndSet(0, event.getWebServer().getPort());
            this.start();
        }
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值