【源码分析】Nacos服务注册源码分析-客户端

Nacos客户端入口

首先在我们使用Nacos时,会在客户端引入对应的依赖,例如需要Nacos的注册中心功能需要引入

        <!--nacos-discovery  注册中心依赖--><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId></dependency>

而熟悉Springboot的自然知道,为什么引用一个starter就能引入对应的功能?这离不开Springboot的自动配置功能,这也是其特点之一。
而说到自动配置,那自然离不开自动配置类,他即是功能的入口。
那Nacos有哪些自动配置类呢?

NacosServiceAutoConfiguration

这是Nacos服务器通信的基础设施,是整个 Nacos 集成的"连接管理中心"。

@Configuration(proxyBeanMethods = false
)
@ConditionalOnDiscoveryEnabled
@ConditionalOnNacosDiscoveryEnabled
public class NacosServiceAutoConfiguration {public NacosServiceAutoConfiguration() {}@Beanpublic NacosServiceManager nacosServiceManager() {return new NacosServiceManager();}// Spring 应用 → NacosServiceManager → Nacos SDK → Nacos 服务器}

NacosServiceManager 被多个 Nacos 相关组件使用:

服务发现组件:
NacosServiceDiscovery 使用它获取 NamingService 实例
NacosRegistration 使用它进行服务注册

配置中心组件:
NacosConfigManager 使用它获取 ConfigService 实例
配置刷新机制依赖它提供的服务对象

延迟初始化: NacosServiceManager 不会在创建时立即连接 Nacos 服务器,而是采用延迟初始化策略

按需创建服务对象:
当系统需要 NamingService (服务发现) 时,按需创建并缓存
当系统需要 ConfigService (配置中心) 时,按需创建并缓存

服务对象缓存机制:

基于属性(如命名空间、分组)创建缓存键
相同配置的服务请求复用同一个服务对象实例
避免重复创建连接,优化资源使用

生命周期管理:
与 Spring 容器生命周期绑定
在应用关闭时释放资源、关闭连接

NacosDiscoveryAutoConfiguration

这是Nacos的服务发现自动配置类,主要有如下功能

  • 自动装配 Nacos 服务发现组件
  • 初始化服务发现相关的基础设施 Bean
  • 使应用能够与 Nacos 服务器进行服务注册与发现交互
@Configuration(proxyBeanMethods = false
)
@ConditionalOnDiscoveryEnabled
@ConditionalOnNacosDiscoveryEnabled
public class NacosDiscoveryAutoConfiguration {public NacosDiscoveryAutoConfiguration() {}@Bean@ConditionalOnMissingBeanpublic NacosDiscoveryProperties nacosProperties() {return new NacosDiscoveryProperties();}@Bean@ConditionalOnMissingBean // 需要传入NacosServiceManager ,通过其进行服务发现public NacosServiceDiscovery nacosServiceDiscovery(NacosDiscoveryProperties discoveryProperties, NacosServiceManager nacosServiceManager) { return new NacosServiceDiscovery(discoveryProperties, nacosServiceManager);}
}

NacosServiceRegistryAutoConfiguration

上面两个,一个是提供操作服务的Service,一个是提供服务发现的功能,那这个就是提供自动注册的功能,其自动配置类如下:

@Configuration(proxyBeanMethods = false
)
@EnableConfigurationProperties
@ConditionalOnNacosDiscoveryEnabled // 自定义Condition注解,具体参考自动配置相关知识
@ConditionalOnProperty(value = {"spring.cloud.service-registry.auto-registration.enabled"},matchIfMissing = true
)
// 用于控制自动配置顺序
@AutoConfigureAfter({AutoServiceRegistrationConfiguration.class, AutoServiceRegistrationAutoConfiguration.class, NacosDiscoveryAutoConfiguration.class})
public class NacosServiceRegistryAutoConfiguration {public NacosServiceRegistryAutoConfiguration() {}@Bean // 用于提供注册功能的Service,其调用NacosServiceManager 进行实现 父类为 ServiceRegistry<R>public NacosServiceRegistry nacosServiceRegistry(NacosServiceManager nacosServiceManager, NacosDiscoveryProperties nacosDiscoveryProperties) {return new NacosServiceRegistry(nacosServiceManager, nacosDiscoveryProperties);}@Bean // 承载服务注册所需的实例信息,是注册数据的容器@ConditionalOnBean({AutoServiceRegistrationProperties.class})public NacosRegistration nacosRegistration(ObjectProvider<List<NacosRegistrationCustomizer>> registrationCustomizers, NacosDiscoveryProperties nacosDiscoveryProperties, ApplicationContext context) {return new NacosRegistration((List)registrationCustomizers.getIfAvailable(), nacosDiscoveryProperties, context);}@Bean // 自动服务注册的触发器,监听事件并执行注册@ConditionalOnBean({AutoServiceRegistrationProperties.class})public NacosAutoServiceRegistration nacosAutoServiceRegistration(NacosServiceRegistry registry, AutoServiceRegistrationProperties autoServiceRegistrationProperties, NacosRegistration registration) {return new NacosAutoServiceRegistration(registry, autoServiceRegistrationProperties, registration);}
}

自动注册剖析

在上述第三个自动配置生效后,会返回一个 new NacosAutoServiceRegistration(registry, autoServiceRegistrationProperties, registration);
分析其继承关系。
在这里插入图片描述
可以发现其关系图中,有 ApplicationListener< WebServerInitializedEvent > 这个类,其作用是会监听对应事件,而这个事件就是WebServerInitializedEvent 代表嵌入式 Web 服务器已完成初始化并启动的通知机制。

public void onApplicationEvent(WebServerInitializedEvent event) {ApplicationContext context = event.getApplicationContext();if (!(context instanceof ConfigurableWebServerApplicationContext) || !"management".equals(((ConfigurableWebServerApplicationContext)context).getServerNamespace())) {this.port.compareAndSet(0, event.getWebServer().getPort());this.start(); // start方法}}
==

start 方法

public void start() {if (!this.isEnabled()) {if (logger.isDebugEnabled()) {logger.debug("Discovery Lifecycle disabled. Not starting");}} else {if (!this.running.get()) {this.context.publishEvent(new InstancePreRegisteredEvent(this, this.getRegistration()));this.registrationLifecycles.forEach((registrationLifecycle) -> {registrationLifecycle.postProcessBeforeStartRegister(this.getRegistration());});this.register(); // 进行注册this.registrationLifecycles.forEach((registrationLifecycle) -> {registrationLifecycle.postProcessAfterStartRegister(this.getRegistration());});if (this.shouldRegisterManagement()) {this.registrationManagementLifecycles.forEach((registrationManagementLifecycle) -> {registrationManagementLifecycle.postProcessBeforeStartRegisterManagement(this.getManagementRegistration());});this.registerManagement();this.registrationManagementLifecycles.forEach((registrationManagementLifecycle) -> {registrationManagementLifecycle.postProcessAfterStartRegisterManagement(this.getManagementRegistration());});}this.context.publishEvent(new InstanceRegisteredEvent(this, this.getConfiguration()));this.running.compareAndSet(false, true);}}}

register方法

private final ServiceRegistry<R> serviceRegistry;
......
protected void register() {if (!this.registration.getNacosDiscoveryProperties().isRegisterEnabled()) {log.debug("Registration disabled.");} else {if (this.registration.getPort() < 0) {this.registration.setPort(this.getPort().get());}super.register();}}
// ==> super.register()
protected void register() {this.serviceRegistry.register(this.getRegistration()); // NacosRegistration}

serviceRegistry.register

public void register(Registration registration) {if (StringUtils.isEmpty(registration.getServiceId())) {log.warn("No service to register for nacos client...");} else {NamingService namingService = this.namingService();String serviceId = registration.getServiceId();String group = this.nacosDiscoveryProperties.getGroup();Instance instance = this.getNacosInstanceFromRegistration(registration);try {namingService.registerInstance(serviceId, group, instance); // 进行注册log.info("nacos registry, {} {} {}:{} register finished", new Object[]{group, serviceId, instance.getIp(), instance.getPort()});} catch (Exception var7) {Exception e = var7;if (this.nacosDiscoveryProperties.isFailFast()) {log.error("nacos registry, {} register failed...{},", new Object[]{serviceId, registration.toString(), e});ReflectionUtils.rethrowRuntimeException(e);} else {log.warn("Failfast is false. {} register failed...{},", new Object[]{serviceId, registration.toString(), e});}}}}

namingService.registerInstance

public void registerInstance(String serviceName, String groupName, Instance instance) throws NacosException {NamingUtils.checkInstanceIsLegal(instance);this.checkAndStripGroupNamePrefix(instance, groupName);this.clientProxy.registerService(serviceName, groupName, instance); // 通过代理去获取对应的注册服务}

clientProxy.registerService

public void registerService(String serviceName, String groupName, Instance instance) throws NacosException {this.getExecuteClientProxy(instance).registerService(serviceName, groupName, instance);}

getExecuteClientProxy

 private NamingClientProxy getExecuteClientProxy(Instance instance) {return (NamingClientProxy)(!instance.isEphemeral() && !this.grpcClientProxy.isAbilitySupportedByServer(AbilityKey.SERVER_SUPPORT_PERSISTENT_INSTANCE_BY_GRPC) ? this.httpClientProxy : this.grpcClientProxy);}

是否临时服务判断

Nacos 提供两种注册方式,一种是临时,会进行心跳检测,如果心跳检测不超过,或者超时,就会被任务不健康实例,会对其进行下线,其次会将其加入一个队列中,去检测是否健康,如果不健康,那就移除。
一种是永久注册,下面详细介绍

临时实例 (Ephemeral = true)

  1. 生命周期特点

    • 基于心跳维持,客户端需要定期发送心跳包
    • 如果一定时间内未收到心跳,Nacos会自动将实例标记为不健康,并最终移除
  2. 适用场景

    • 适合大多数微服务场景,特别是云原生环境
    • 实例会随应用的启停自动注册和注销
  3. 数据存储

    • 存储在内存中,提供更高的性能
    • 在Nacos服务器重启时数据会丢失

持久化实例 (Ephemeral = false)

  1. 生命周期特点

    • 实例信息持久化到磁盘
    • 不依赖心跳维持,即使客户端宕机实例也不会被自动移除
  2. 适用场景

    • 适合那些需要保持稳定注册状态的场景
    • 如某些关键基础设施服务,需要手动管理其上下线
  3. 数据存储

    • 数据持久化到磁盘数据库中
    • Nacos重启后数据仍然存在

HttpClient.registerService

public void registerService(String serviceName, String groupName, Instance instance) throws NacosException {LogUtils.NAMING_LOGGER.info("[REGISTER-SERVICE] {} registering service {} with instance: {}", new Object[]{this.namespaceId, serviceName, instance});String groupedServiceName = NamingUtils.getGroupedName(serviceName, groupName);if (instance.isEphemeral()) {throw new UnsupportedOperationException("Do not support register ephemeral instances by HTTP, please use gRPC replaced.");} else {Map<String, String> params = new HashMap(32);params.put("namespaceId", this.namespaceId);params.put("serviceName", groupedServiceName);params.put("groupName", groupName);params.put("clusterName", instance.getClusterName());params.put("ip", instance.getIp());params.put("port", String.valueOf(instance.getPort()));params.put("weight", String.valueOf(instance.getWeight()));params.put("enable", String.valueOf(instance.isEnabled()));params.put("healthy", String.valueOf(instance.isHealthy()));params.put("ephemeral", String.valueOf(instance.isEphemeral()));params.put("metadata", JacksonUtils.toJson(instance.getMetadata()));this.reqApi(UtilAndComs.nacosUrlInstance, params, "POST");}}

Grpc.registerService

 public void registerService(String serviceName, String groupName, Instance instance) throws NacosException {LogUtils.NAMING_LOGGER.info("[REGISTER-SERVICE] {} registering service {} with instance {}", new Object[]{this.namespaceId, serviceName, instance});if (instance.isEphemeral()) {this.registerServiceForEphemeral(serviceName, groupName, instance);} else {this.doRegisterServiceForPersistent(serviceName, groupName, instance);}}

自上,自动注册服务就到此为止

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/898031.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Java中关于Optional的 orElse 操作,以及 orElse 与 orElseGet 的区别

文章目录 1. 大概说明2. 详细分析2.1 .orElse 操作2.2 .orElse 的作用&#xff1a;避免空指针异常2.3 为什么要用&#xff1f;2.4 orElseGet如何使用2.5 orElse和orElseGet的区别 1. 大概说明 这篇文章的目的是为了说明&#xff1a; orElse 如何使用orElseGet 如何使用两者的…

数据结构-树(详解)

目录 一、树的基本概念二、树的节点结构三、树的基本操作&#xff08;一&#xff09;插入操作&#xff08;二&#xff09;删除操作&#xff08;三&#xff09;查找操作&#xff08;四&#xff09;遍历操作 四、树的实现五、总结 一、树的基本概念 树是一种非线性数据结构&…

【eNSP实战】配置端口映射(NAT Server)

拓图 要求&#xff1a; 将AR1上的GE 0/0/1接口的地址从TCP协议的80端口映射到内网 Web服务器80端口 AR1接口配置 interface GigabitEthernet0/0/0ip address 192.168.0.1 255.255.255.0 # interface GigabitEthernet0/0/1ip address 11.0.1.1 255.255.255.0 # ip route-s…

RabbitMQ 基本原理详解

1. 引言 在现代分布式系统中&#xff0c;消息队列&#xff08;Message Queue&#xff09;是实现异步通信、解耦系统组件、提高系统可靠性和扩展性的重要工具。RabbitMQ 作为一款开源的消息中间件&#xff0c;因其高性能、易用性和丰富的功能&#xff0c;被广泛应用于各种场景。…

算法——层序遍历和中序遍历构造二叉树

晴问 #include <iostream> #include <vector> #include <queue> #include <unordered_map>using namespace std;struct TreeNode {int data;TreeNode *left;TreeNode *right;TreeNode(int data) : data(data), left(nullptr), right(nullptr) {} };//…

prometheus自定义监控(pushgateway和blackbox)和远端存储VictoriaMetrics

1 pushgateway采集 1.1 自定义采集键值 如果自定义采集需求时&#xff0c;就可以通过写脚本 定时任务定期发送数据到 pushgateway 达到自定义监控 1.部署 pushgateway&#xff0c;以 10.0.0.42 节点为例 1.下载组件 wget https://github.com/prometheus/pushgateway/relea…

feign配置重试次数不生效

一、问题产生 自定义重试次数&#xff0c;实现如下 ConditionalOnProperty(prefix "feign.client", name "enable", havingValue "true") Configuration public class FeignConfig {Beanpublic FeignInterceptor feignInterceptor() {retur…

Dify使用部署与应用实践

最近在研究AI Agent&#xff0c;发现大家都在用Dify&#xff0c;但Dify部署起来总是面临各种问题&#xff0c;而且我在部署和应用测试过程中也都遇到了&#xff0c;因此记录如下&#xff0c;供大家参考。Dify总体来说比较灵活&#xff0c;扩展性比较强&#xff0c;适合基于它做…

二叉树的统一迭代法 标记法

我们以中序遍历为例&#xff0c;在二叉树&#xff1a;听说递归能做的&#xff0c;栈也能做&#xff01; (opens new window)中提到说使用栈的话&#xff0c;无法同时解决访问节点&#xff08;遍历节点&#xff09;和处理节点&#xff08;将元素放进结果集&#xff09;不一致的情…

BaseActivity 和 BaseFragment 的现代化架构:ViewBinding 与 ViewModel 的深度整合

BaseActivity 和 BaseFragment 实现&#xff0c;集成了 View Binding&#xff0c;并增加了对 Lifecycle 和 ViewModel 的支持&#xff0c;同时进一步简化了代码结构&#xff0c;使其更易用、更灵活。 启用 View Binding 确保在 build.gradle 中启用了 View Binding&#xff1a…

从零开始学习机器人---如何高效学习机械原理

如何高效学习机械原理 1. 理解课程的核心概念2. 结合图形和模型学习3. 掌握公式和计算方法4. 理论与实践相结合5. 总结和复习6. 保持好奇心和探索精神 总结 机械原理是一门理论性和实践性都很强的课程&#xff0c;涉及到机械系统的运动、动力传递、机构设计等内容。快速学习机械…

剖析sentinel的限流和熔断

sentinel的限流和熔断 前言源码分析滑动窗口源码限流源码熔断源码 完结撒花&#xff0c;sentinel源码还是挺简单的&#xff0c;如有需要收藏的看官&#xff0c;顺便也用发财的小手点点赞哈&#xff0c;如有错漏&#xff0c;也欢迎各位在评论区评论&#xff01; 前言 平时发起一…

硬盘分区误删后的数据救赎

一、硬盘分区误删的概述 硬盘分区误删&#xff0c;是许多电脑用户在使用过程中可能遭遇的棘手问题。分区&#xff0c;作为硬盘上存储数据的逻辑单元&#xff0c;一旦被误删除&#xff0c;不仅会导致该分区内的所有数据瞬间消失&#xff0c;还可能影响到整个硬盘的存储结构和数…

代码随想录算法训练营第三十五天(20250303) |01背包问题 二维,01背包问题 一维,416. 分割等和子集 -[补卡20250316]

01背包问题 二维 链接 遍历物品没有大小顺序要求重点是模拟&#xff0c;推导出递推公式 #include <iostream> #include <vector>int main(){int m, n;std::cin>>m>>n;std::vector<int> weight(m,0),value(m,0);for(int i{0}; i<m; i){std:…

老牌软件,方便处理图片,量大管饱。

今天介绍的图片查看器名字是&#xff1a;FastStone Image Viewer&#xff0c;是一款可查看、编辑、批量重命名、批量转换的图片查看软件。文末有分享链接。 软件以资源管理器的方式管理你电脑里的图片&#xff0c;点击左侧可选择文件夹&#xff0c;右边可预览图片。 软妹用得最…

【数据库相关】mysql数据库巡检

mysql数据库巡检 巡检步骤**一、基础状态检查****二、服务器资源监控****CPU使用****内存使用****磁盘I/O****网络流量** **三、数据库内部健康度****全局状态****慢查询监控****锁与并发** **四、存储引擎健康****InnoDB引擎****MyISAM引擎** **五、日志与备份****六、安全与权…

Python进阶编程总结

&#x1f9d1; 博主简介&#xff1a;CSDN博客专家&#xff0c;历代文学网&#xff08;PC端可以访问&#xff1a;https://literature.sinhy.com/#/literature?__c1000&#xff0c;移动端可微信小程序搜索“历代文学”&#xff09;总架构师&#xff0c;15年工作经验&#xff0c;…

Redis复制(replica)主从模式

Redis主从复制 Redis 的复制&#xff08;replication&#xff09;功能允许用户根据一个 Redis 服务器来创建任意多个该服务器的复制品&#xff0c;其中被复制的服务器为主服务器&#xff08;master&#xff09;&#xff0c;而通过复制创建出来的服务器复制品则为从服务器&#…

Adobe Premiere Pro2023配置要求

Windows 系统 最低配置 处理器&#xff1a;Intel 第六代或更新版本的 CPU&#xff0c;或 AMD Ryzen™ 1000 系列或更新版本的 CPU&#xff0c;需要支持 Advanced Vector Extensions 2&#xff08;AVX2&#xff09;。操作系统&#xff1a;Windows 10&#xff08;64 位&#xff…

【Kubernets】Deployment 和 StatefulSet 有什么区别?什么时候用 StatefulSet?

Deployment 和 StatefulSet 的区别 在 Kubernetes 中&#xff0c;Deployment 和 StatefulSet 都用于管理 Pod&#xff0c;但它们适用于不同的场景。 1. Deployment&#xff1a;管理无状态应用 特点&#xff1a; 无状态&#xff1a;Pod 之间相互独立&#xff0c;不需要保持顺…