Nacos 服务注册源码分析

开发 架构
本文我们一起以源码的维度来分析 Nacos 做为服务注册中心的服务注册过程,我会以服务端、客户端两个角度来进行分析,Nacos 客户端我主要是采用 spring-cloud-alibaba 作为核心的客户端组件。

[[410664]]

本文我们一起以源码的维度来分析 Nacos 做为服务注册中心的服务注册过程,我会以服务端、客户端两个角度来进行分析,Nacos 客户端我主要是采用 spring-cloud-alibaba 作为核心的客户端组件。对于 Nacos 服务端我会讲解到, Nacos 如何实现 AP/CP 两种模式共存的,以及如何区分的。最后还会分享我在源码调试过程中如何定位核心类的一点经验。

下面我先对我的环境做一个简单的介绍:

  • Jdk 1.8
  • nacos-server-1.4.2
  • spring-boot-2.3.5.RELEASE
  • spring-cloud-Hoxton.SR8
  • spring-cloiud-alibab-2.2.5.RELEASE

Nacos 服务架构

以 Spring-Boot 为服务基础搭建平台, Nacos 在服务架构中的位置如下图所示:

图片

总的来说和 Nacos 功能类似的中间件有 Eureka、Zookeeper、Consul 、Etcd 等。Nacos 最大的特点就是既能够支持 AP、也能够支持 CP 模式,在分区一致性方面使用的是 Raft 协议来实现。

Nacos 客户端

服务注册客户端

添加依赖

Nacos 服务注册是客户端主动发起,利用 Spring 启完成事件进行拓展调用服务注册方法。首先我们需要导入spring-cloud-starter-alibaba-nacos-discovery依赖:

  1. <dependency> 
  2.   <groupId>com.alibaba.cloud</groupId> 
  3.   <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> 
  4. </dependency> 

分析源码

对于 spring-boot 组件我们首先先找它的 META-INF/spring.factories 文件

  1. org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ 
  2.   com.alibaba.cloud.nacos.discovery.NacosDiscoveryAutoConfiguration,\ 
  3.   com.alibaba.cloud.nacos.ribbon.RibbonNacosAutoConfiguration,\ 
  4.   com.alibaba.cloud.nacos.endpoint.NacosDiscoveryEndpointAutoConfiguration,\ 
  5.   com.alibaba.cloud.nacos.registry.NacosServiceRegistryAutoConfiguration,\ 
  6.   com.alibaba.cloud.nacos.discovery.NacosDiscoveryClientConfiguration,\ 
  7.   com.alibaba.cloud.nacos.discovery.reactive.NacosReactiveDiscoveryClientConfiguration,\ 
  8.   com.alibaba.cloud.nacos.discovery.configclient.NacosConfigServerAutoConfiguration,\ 
  9.   com.alibaba.cloud.nacos.NacosServiceAutoConfiguration 
  10. org.springframework.cloud.bootstrap.BootstrapConfiguration=\ 
  11.   com.alibaba.cloud.nacos.discovery.configclient.NacosDiscoveryClientConfigServiceBootstrapConfiguration 

通过我的分析发现 NacosServiceRegistryAutoConfiguration 是咱们服务注册的核心配置类,该类中定义了三个核心的 Bean 对象:

  • NacosServiceRegistry
  • NacosRegistration
  • NacosAutoServiceRegistration

NacosAutoServiceRegistration

NacosAutoServiceRegistration 实现了服务向 Nacos 发起注册的功能,它继承自抽象类 AbstractAutoServiceRegistration 。

在抽象类 AbstractAutoServiceRegistration 中实现 ApplicationContextAware、ApplicationListener 接口。在容器启动、并且上下文准备就绪过后会调用 onApplicationEvent 方法。

  1. public void onApplicationEvent(WebServerInitializedEvent event) { 
  2.    bind(event); 

再调用 bind(event) 方法:

  1. public void bind(WebServerInitializedEvent event) { 
  2.    ApplicationContext context = event.getApplicationContext(); 
  3.    if (context instanceof ConfigurableWebServerApplicationContext) { 
  4.       if ("management".equals(((ConfigurableWebServerApplicationContext) context) 
  5.             .getServerNamespace())) { 
  6.          return
  7.       } 
  8.    } 
  9.    this.port.compareAndSet(0, event.getWebServer().getPort()); 
  10.    this.start(); 

然后调用 start() 方法

  1. public void start() { 
  2.   if (!isEnabled()) { 
  3.     if (logger.isDebugEnabled()) { 
  4.       logger.debug("Discovery Lifecycle disabled. Not starting"); 
  5.     } 
  6.     return
  7.   } 
  8.  
  9.   // only initialize if nonSecurePort is greater than 0 and it isn't already running 
  10.   // because of containerPortInitializer below 
  11.   if (!this.running.get()) { 
  12.     this.context.publishEvent( 
  13.         new InstancePreRegisteredEvent(this, getRegistration())); 
  14.     register(); 
  15.     if (shouldRegisterManagement()) { 
  16.       registerManagement(); 
  17.     } 
  18.     this.context.publishEvent( 
  19.         new InstanceRegisteredEvent<>(this, getConfiguration())); 
  20.     this.running.compareAndSet(falsetrue); 
  21.   } 
  22.  

最后调用 register(); 在内部去调用 serviceRegistry.register() 方法完成服务注册。

  1. private final ServiceRegistry<R> serviceRegistry; 
  2.  
  3. protected void register() { 
  4.    this.serviceRegistry.register(getRegistration()); 

NacosServiceRegistry

NacosServiceRegistry 类主要的目的就是实现服务注册

  1. public void register(Registration registration) { 
  2.  
  3.    if (StringUtils.isEmpty(registration.getServiceId())) { 
  4.       log.warn("No service to register for nacos client..."); 
  5.       return
  6.    } 
  7.    // 默认情况下,会通过反射返回一个 `com.alibaba.nacos.client.naming.NacosNamingService` 的实例 
  8.    NamingService namingService = namingService(); 
  9.    // 获取 serviceId , 默认使用配置: spring.application.name  
  10.    String serviceId = registration.getServiceId(); 
  11.    // 获取 group , 默认 DEFAULT_GROUP  
  12.    String group = nacosDiscoveryProperties.getGroup(); 
  13.  
  14.    // 创建 instance 实例  
  15.    Instance instance = getNacosInstanceFromRegistration(registration); 
  16.  
  17.    try { 
  18.       // 注册实例 
  19.       namingService.registerInstance(serviceId, group, instance); 
  20.       log.info("nacos registry, {} {} {}:{} register finished"group, serviceId, 
  21.             instance.getIp(), instance.getPort()); 
  22.    } 
  23.    catch (Exception e) { 
  24.       log.error("nacos registry, {} register failed...{},", serviceId, 
  25.             registration.toString(), e); 
  26.       // rethrow a RuntimeException if the registration is failed. 
  27.       // issue : https://github.com/alibaba/spring-cloud-alibaba/issues/1132 
  28.       rethrowRuntimeException(e); 
  29.    } 

我们可以看到最后调用的是 namingService.registerInstance(serviceId, group, instance); 方法。

  1. public void registerInstance(String serviceName, String groupName, Instance instance) throws NacosException { 
  2.     NamingUtils.checkInstanceIsLegal(instance); 
  3.     String groupedServiceName = NamingUtils.getGroupedName(serviceName, groupName); 
  4.     if (instance.isEphemeral()) { 
  5.         BeatInfo beatInfo = beatReactor.buildBeatInfo(groupedServiceName, instance); 
  6.         beatReactor.addBeatInfo(groupedServiceName, beatInfo); 
  7.     } 
  8.     serverProxy.registerService(groupedServiceName, groupName, instance); 

然后再调用 serverProxy.registerService(groupedServiceName, groupName, instance); 方法进行服务注册,通过 beatReactor.addBeatinfo() 创建 schedule 每间隔 5s 向服务端发送一次心跳数据

  1. public void registerService(String serviceName, String groupName, Instance instance) throws NacosException { 
  2.      
  3.     NAMING_LOGGER.info("[REGISTER-SERVICE] {} registering service {} with instance: {}", namespaceId, serviceName, 
  4.             instance); 
  5.      
  6.     final Map<String, String> params = new HashMap<String, String>(16); 
  7.     params.put(CommonParams.NAMESPACE_ID, namespaceId); 
  8.     params.put(CommonParams.SERVICE_NAME, serviceName); 
  9.     params.put(CommonParams.GROUP_NAME, groupName); 
  10.     params.put(CommonParams.CLUSTER_NAME, instance.getClusterName()); 
  11.     params.put("ip", instance.getIp()); 
  12.     params.put("port", String.valueOf(instance.getPort())); 
  13.     params.put("weight", String.valueOf(instance.getWeight())); 
  14.     params.put("enable", String.valueOf(instance.isEnabled())); 
  15.     params.put("healthy", String.valueOf(instance.isHealthy())); 
  16.     params.put("ephemeral", String.valueOf(instance.isEphemeral())); 
  17.     params.put("metadata", JacksonUtils.toJson(instance.getMetadata())); 
  18.      
  19.     // POST: /nacos/v1/ns/instance 进行服务注册 
  20.     reqApi(UtilAndComs.nacosUrlInstance, params, HttpMethod.POST); 
  21.      

服务注册服务端

Nacos 做为服务注册中心,既可以实现AP ,也能实现 CP 架构。来维护我们服务中心的服务列表。下面是我们服务列表一个简单的数据模型示意图:

图片

其实就和咱们 NacosServiceRegistry#registry 构建 Instance 实例的过程是一致的。继续回到我们源码分析我们直接来看服务端的 /nacos/v1/ns/instance 接口,被定义在 InstanceController#register 方法。

服务注册

在 InstanceController#register 方法中,主要是解析 request 参数然后调用 serviceManager.registerInstance , 如果返回 ok 就表示注册成功。

  1. @CanDistro 
  2. @PostMapping 
  3. @Secured(parser = NamingResourceParser.class, action = ActionTypes.WRITE) 
  4. public String register(HttpServletRequest request) throws Exception { 
  5.      
  6.     final String namespaceId = WebUtils 
  7.             .optional(request, CommonParams.NAMESPACE_ID, Constants.DEFAULT_NAMESPACE_ID); 
  8.     final String serviceName = WebUtils.required(request, CommonParams.SERVICE_NAME); 
  9.     NamingUtils.checkServiceNameFormat(serviceName); 
  10.      
  11.     final Instance instance = parseInstance(request); 
  12.      
  13.     serviceManager.registerInstance(namespaceId, serviceName, instance); 
  14.     return "ok"

registerInstance 方法的调用

  1. public void registerInstance(String namespaceId, String serviceName, Instance instance) throws NacosException { 
  2.      
  3.     createEmptyService(namespaceId, serviceName, instance.isEphemeral()); 
  4.      
  5.     Service service = getService(namespaceId, serviceName); 
  6.      
  7.     if (service == null) { 
  8.         throw new NacosException(NacosException.INVALID_PARAM, 
  9.                 "service not found, namespace: " + namespaceId + ", service: " + serviceName); 
  10.     } 
  11.      
  12.     addInstance(namespaceId, serviceName, instance.isEphemeral(), instance); 

再调用 addInstance() 方法

  1. @Resource(name = "consistencyDelegate"
  2. private ConsistencyService consistencyService; 
  3.  
  4. public void addInstance(String namespaceId, String serviceName, boolean ephemeral, Instance... ips) 
  5.         throws NacosException { 
  6.      
  7.     String key = KeyBuilder.buildInstanceListKey(namespaceId, serviceName, ephemeral); 
  8.      
  9.     Service service = getService(namespaceId, serviceName); 
  10.      
  11.     synchronized (service) { 
  12.         List<Instance> instanceList = addIpAddresses(service, ephemeral, ips); 
  13.          
  14.         Instances instances = new Instances(); 
  15.         instances.setInstanceList(instanceList); 
  16.          
  17.         consistencyService.put(key, instances); 
  18.     } 

调用 consistencyService.put(key, instances); 刷新 service 中的所有 instance。我们通过 consistencyService 的定义可以知道它将调用 DelegateConsistencyServiceImpl 类的 put 方法。在这个地方有一个 AP/CP 模式的选择我们可以通过

  1. @Override 
  2. public void put(String key, Record value) throws NacosException { 
  3.     mapConsistencyService(key).put(key, value); 
  4.  
  5. // AP 或者 CP 模式的选择, AP 模式采用 Distro 协议, CP 模式采用 Raft 协议。 
  6. private ConsistencyService mapConsistencyService(String key) { 
  7.     return KeyBuilder.matchEphemeralKey(key) ? ephemeralConsistencyService : persistentConsistencyService; 

AP 模式

Nacos 默认就是采用的 AP 模式使用 Distro 协议实现。实现的接口是 EphemeralConsistencyService 对节点信息的持久化主要是调用 put 方法

  1. @Override 
  2. public void put(String key, Record value) throws NacosException { 
  3.     // 数据持久化 
  4.     onPut(key, value); 
  5.     // 通知其他服务节点  
  6.     distroProtocol.sync(new DistroKey(key, KeyBuilder.INSTANCE_LIST_KEY_PREFIX), DataOperation.CHANGE, 
  7.             globalConfig.getTaskDispatchPeriod() / 2); 

在调用 doPut 来保存数据并且发通知

  1. public void onPut(String key, Record value) { 
  2.      
  3.     if (KeyBuilder.matchEphemeralInstanceListKey(key)) { 
  4.         Datum<Instances> datum = new Datum<>(); 
  5.         datum.value = (Instances) value; 
  6.         datum.key = key
  7.         datum.timestamp.incrementAndGet(); 
  8.         // 数据持久化  
  9.         dataStore.put(key, datum); 
  10.     } 
  11.      
  12.     if (!listeners.containsKey(key)) { 
  13.         return
  14.     } 
  15.      
  16.     notifier.addTask(key, DataOperation.CHANGE); 

在 notifier.addTask 主要是通过 tasks.offer(Pair.with(datumKey, action)); 向阻塞队列 tasks 中放注册实例信息。通过 Notifier#run 方法来进行异步操作以保证效率

  1. public class Notifier implements Runnable { 
  2.      
  3.     @Override 
  4.     public void run() { 
  5.         Loggers.DISTRO.info("distro notifier started"); 
  6.          
  7.         for (; ; ) { 
  8.             try { 
  9.                 Pair<String, DataOperation> pair = tasks.take(); 
  10.                 handle(pair); 
  11.             } catch (Throwable e) { 
  12.                 Loggers.DISTRO.error("[NACOS-DISTRO] Error while handling notifying task", e); 
  13.             } 
  14.         } 
  15.     } 
  16.      
  17.     private void handle(Pair<String, DataOperation> pair) { 
  18.          // 省略部分代码 
  19.             for (RecordListener listener : listeners.get(datumKey)) { 
  20.                 count++; 
  21.                 try { 
  22.                     if (action == DataOperation.CHANGE) { 
  23.                         listener.onChange(datumKey, dataStore.get(datumKey).value); 
  24.                         continue
  25.                     } 
  26.                     if (action == DataOperation.DELETE) { 
  27.                         listener.onDelete(datumKey); 
  28.                         continue
  29.                     } 
  30.                 } catch (Throwable e) { 
  31.                     Loggers.DISTRO.error("[NACOS-DISTRO] error while notifying listener of key: {}", datumKey, e); 
  32.                 } 
  33.             } 
  34.     } 

如果是 DataOperation.CHANGE 类型的事件会调用 listener.onChange(datumKey, dataStore.get(datumKey).value); 其实我们的 listener 就是我们的 Service 对象。

  1. public void onChange(String key, Instances value) throws Exception { 
  2.      
  3.     Loggers.SRV_LOG.info("[NACOS-RAFT] datum is changed, key: {}, value: {}"key, value); 
  4.      
  5.     for (Instance instance : value.getInstanceList()) { 
  6.          
  7.         if (instance == null) { 
  8.             // Reject this abnormal instance list: 
  9.             throw new RuntimeException("got null instance " + key); 
  10.         } 
  11.          
  12.         if (instance.getWeight() > 10000.0D) { 
  13.             instance.setWeight(10000.0D); 
  14.         } 
  15.          
  16.         if (instance.getWeight() < 0.01D && instance.getWeight() > 0.0D) { 
  17.             instance.setWeight(0.01D); 
  18.         } 
  19.     } 
  20.      
  21.     updateIPs(value.getInstanceList(), KeyBuilder.matchEphemeralInstanceListKey(key)); 
  22.      
  23.     recalculateChecksum(); 

updateIPs 方法会将服务实例信息,更新到注册表的内存中去,并且会以 udp 的方式通知当前服务的订阅者。

  1. public void updateIPs(Collection<Instance> instances, boolean ephemeral) { 
  2.     Map<String, List<Instance>> ipMap = new HashMap<>(clusterMap.size()); 
  3.     for (String clusterName : clusterMap.keySet()) { 
  4.         ipMap.put(clusterName, new ArrayList<>()); 
  5.     } 
  6.      
  7.     for (Instance instance : instances) { 
  8.         try { 
  9.             if (instance == null) { 
  10.                 Loggers.SRV_LOG.error("[NACOS-DOM] received malformed ip: null"); 
  11.                 continue
  12.             } 
  13.              
  14.             if (StringUtils.isEmpty(instance.getClusterName())) { 
  15.                 instance.setClusterName(UtilsAndCommons.DEFAULT_CLUSTER_NAME); 
  16.             } 
  17.              
  18.             if (!clusterMap.containsKey(instance.getClusterName())) { 
  19.                 Loggers.SRV_LOG 
  20.                         .warn("cluster: {} not found, ip: {}, will create new cluster with default configuration."
  21.                                 instance.getClusterName(), instance.toJson()); 
  22.                 Cluster cluster = new Cluster(instance.getClusterName(), this); 
  23.                 cluster.init(); 
  24.                 getClusterMap().put(instance.getClusterName(), cluster); 
  25.             } 
  26.              
  27.             List<Instance> clusterIPs = ipMap.get(instance.getClusterName()); 
  28.             if (clusterIPs == null) { 
  29.                 clusterIPs = new LinkedList<>(); 
  30.                 ipMap.put(instance.getClusterName(), clusterIPs); 
  31.             } 
  32.              
  33.             clusterIPs.add(instance); 
  34.         } catch (Exception e) { 
  35.             Loggers.SRV_LOG.error("[NACOS-DOM] failed to process ip: " + instance, e); 
  36.         } 
  37.     } 
  38.      
  39.     for (Map.Entry<String, List<Instance>> entry : ipMap.entrySet()) { 
  40.         //make every ip mine 
  41.         List<Instance> entryIPs = entry.getValue(); 
  42.         // 更新服务列表 
  43.         clusterMap.get(entry.getKey()).updateIps(entryIPs, ephemeral); 
  44.     } 
  45.      
  46.     setLastModifiedMillis(System.currentTimeMillis()); 
  47.     // 推送服务订阅者消息  
  48.     getPushService().serviceChanged(this); 
  49.     StringBuilder stringBuilder = new StringBuilder(); 
  50.      
  51.     for (Instance instance : allIPs()) { 
  52.         stringBuilder.append(instance.toIpAddr()).append("_").append(instance.isHealthy()).append(","); 
  53.     } 
  54.      
  55.     Loggers.EVT_LOG.info("[IP-UPDATED] namespace: {}, service: {}, ips: {}", getNamespaceId(), getName(), 
  56.             stringBuilder.toString()); 
  57.      

CP 模式

Nacos 默认就是采用的 CP 模式使用 Raft 协议实现。实现类是 PersistentConsistencyServiceDelegateImpl

首先我们先看他的 put 方法

  1. public void put(String key, Record value) throws NacosException { 
  2.     checkIsStopWork(); 
  3.     try { 
  4.         raftCore.signalPublish(key, value); 
  5.     } catch (Exception e) { 
  6.         Loggers.RAFT.error("Raft put failed.", e); 
  7.         throw new NacosException(NacosException.SERVER_ERROR, "Raft put failed, key:" + key + ", value:" + value, 
  8.                 e); 
  9.     } 

调用 raftCore.signalPublish(key, value); 主要的步骤如下

  • 判断是否是 Leader 节点,如果不是 Leader 节点将请求转发给 Leader 节点处理;
  • 如果是 Leader 节点,首先执行 onPublish(datum, peers.local()); 方法,内部首先通过 raftStore.updateTerm(local.term.get()); 方法持久化到文件,然后通过 NotifyCenter.publishEvent(ValueChangeEvent.builder().key(datum.key).action(DataOperation.CHANGE).build());异步更新到内存;
  • 通过 CountDownLatch 实现了一个过半机制 new CountDownLatch(peers.majorityCount()) 只有当成功的节点大于 N/2 + 1 的时候才返回成功。
  • 调用其他的 Nacos 节点的 /raft/datum/commit 同步实例信息。
  1. public void signalPublish(String key, Record value) throws Exception { 
  2.     if (stopWork) { 
  3.         throw new IllegalStateException("old raft protocol already stop work"); 
  4.     } 
  5.     if (!isLeader()) { 
  6.         ObjectNode params = JacksonUtils.createEmptyJsonNode(); 
  7.         params.put("key"key); 
  8.         params.replace("value", JacksonUtils.transferToJsonNode(value)); 
  9.         Map<String, String> parameters = new HashMap<>(1); 
  10.         parameters.put("key"key); 
  11.          
  12.         final RaftPeer leader = getLeader(); 
  13.          
  14.         raftProxy.proxyPostLarge(leader.ip, API_PUB, params.toString(), parameters); 
  15.         return
  16.     } 
  17.      
  18.     OPERATE_LOCK.lock(); 
  19.     try { 
  20.         final long start = System.currentTimeMillis(); 
  21.         final Datum datum = new Datum(); 
  22.         datum.key = key
  23.         datum.value = value; 
  24.         if (getDatum(key) == null) { 
  25.             datum.timestamp.set(1L); 
  26.         } else { 
  27.             datum.timestamp.set(getDatum(key).timestamp.incrementAndGet()); 
  28.         } 
  29.          
  30.         ObjectNode json = JacksonUtils.createEmptyJsonNode(); 
  31.         json.replace("datum", JacksonUtils.transferToJsonNode(datum)); 
  32.         json.replace("source", JacksonUtils.transferToJsonNode(peers.local())); 
  33.          
  34.         onPublish(datum, peers.local()); 
  35.          
  36.         final String content = json.toString(); 
  37.          
  38.         final CountDownLatch latch = new CountDownLatch(peers.majorityCount()); 
  39.         for (final String server : peers.allServersIncludeMyself()) { 
  40.             if (isLeader(server)) { 
  41.                 latch.countDown(); 
  42.                 continue
  43.             } 
  44.             final String url = buildUrl(server, API_ON_PUB); 
  45.             HttpClient.asyncHttpPostLarge(url, Arrays.asList("key"key), content, new Callback<String>() { 
  46.                 @Override 
  47.                 public void onReceive(RestResult<String> result) { 
  48.                     if (!result.ok()) { 
  49.                         Loggers.RAFT 
  50.                                 .warn("[RAFT] failed to publish data to peer, datumId={}, peer={}, http code={}"
  51.                                         datum.key, server, result.getCode()); 
  52.                         return
  53.                     } 
  54.                     latch.countDown(); 
  55.                 } 
  56.                  
  57.                 @Override 
  58.                 public void onError(Throwable throwable) { 
  59.                     Loggers.RAFT.error("[RAFT] failed to publish data to peer", throwable); 
  60.                 } 
  61.                  
  62.                 @Override 
  63.                 public void onCancel() { 
  64.                  
  65.                 } 
  66.             }); 
  67.              
  68.         } 
  69.          
  70.         if (!latch.await(UtilsAndCommons.RAFT_PUBLISH_TIMEOUT, TimeUnit.MILLISECONDS)) { 
  71.             // only majority servers return success can we consider this update success 
  72.             Loggers.RAFT.error("data publish failed, caused failed to notify majority, key={}"key); 
  73.             throw new IllegalStateException("data publish failed, caused failed to notify majority, key=" + key); 
  74.         } 
  75.          
  76.         long end = System.currentTimeMillis(); 
  77.         Loggers.RAFT.info("signalPublish cost {} ms, key: {}", (end - start), key); 
  78.     } finally { 
  79.         OPERATE_LOCK.unlock(); 
  80.     } 

判断 AP 模式还是 CP 模式

如果注册 nacos 的 client 节点注册时 ephemeral=true,那么 nacos 集群对这个 client 节点的效果就是 ap 的采用 distro,而注册nacos 的 client 节点注册时 ephemeral=false,那么nacos 集群对这个节点的效果就是 cp 的采用 raft。根据 client 注册时的属性,ap,cp 同时混合存在,只是对不同的 client 节点效果不同

Nacos 源码调试

Nacos 启动文件

首先我们需要找到 Nacos 的启动类,首先需要找到启动的 jar.

图片

然后我们在解压 target/nacos-server.jar

解压命令:

  1. # 解压 jar 包 
  2. tar -zxvf nacos-server.jar 
  3.  
  4. # 查看 MANIFEST.MF 内容 
  5. cat META-INF/MANIFEST.MF 
  6.  
  7. Manifest-Version: 1.0 
  8. Implementation-Title: nacos-console 1.4.2 
  9. Implementation-Version: 1.4.2 
  10. Archiver-Version: Plexus Archiver 
  11. Built-By: xiweng.yy 
  12. Spring-Boot-Layers-Index: BOOT-INF/layers.idx 
  13. Specification-Vendor: Alibaba Group 
  14. Specification-Title: nacos-console 1.4.2 
  15. Implementation-Vendor-Id: com.alibaba.nacos 
  16. Spring-Boot-Version: 2.5.0-RC1 
  17. Implementation-Vendor: Alibaba Group 
  18. Main-Class: org.springframework.boot.loader.PropertiesLauncher 
  19. Spring-Boot-Classpath-Index: BOOT-INF/classpath.idx 
  20. Start-Class: com.alibaba.nacos.Nacos 
  21. Spring-Boot-Classes: BOOT-INF/classes/ 
  22. Spring-Boot-Lib: BOOT-INF/lib/ 
  23. Created-By: Apache Maven 3.6.3 
  24. Build-Jdk: 1.8.0_231 
  25. Specification-Version: 1.4.2 

通过 MANIFEST.MF 中的配置信息,我们可以找到 Start-Class 这个配置这个类就是 Spring-Boot 项目的启动类 com.alibaba.nacos.Nacos

Nacos 调试

通过 com.alibaba.nacos.Nacos 的启动类,我们可以通过这个类在 Idea 中进行启动,然后调试。

本文转载自微信公众号「运维开发故事」,可以通过以下二维码关注。转载本文请联系运维开发故事公众号。

 

责任编辑:姜华 来源: 运维开发故事
相关推荐

2021-07-16 06:56:50

Nacos注册源码

2022-05-06 07:52:06

Nacos服务注册

2021-08-10 07:00:00

Nacos Clien服务分析

2021-08-09 07:58:36

Nacos 服务注册源码分析

2023-03-17 17:51:30

APIServer路由注册

2020-06-29 07:58:18

ZooKeeperConsul 注册中心

2022-02-07 07:10:32

服务注册功能

2023-03-01 08:15:10

NginxNacos

2022-05-08 17:53:38

Nacos服务端客户端

2022-02-09 07:03:01

SpringNacos服务注册

2021-08-04 11:54:25

Nacos注册中心设计

2021-04-18 07:33:20

项目Springboot Nacos

2023-04-26 08:19:48

Nacos高可用开发

2023-10-30 09:35:01

注册中心微服务

2023-01-16 18:32:15

架构APNacos

2023-02-26 00:00:00

2021-05-18 20:22:00

Spring ClouNacos服务

2023-11-29 16:21:30

Kubernetes服务注册

2021-07-09 06:48:30

注册源码解析

2022-05-02 22:01:49

订阅模式Eureka推送模式
点赞
收藏

51CTO技术栈公众号