自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Nacos 服務(wù)注冊源碼分析

開發(fā) 架構(gòu)
本文我們一起以源碼的維度來分析 Nacos 做為服務(wù)注冊中心的服務(wù)注冊過程,我會以服務(wù)端、客戶端兩個角度來進行分析,Nacos 客戶端我主要是采用 spring-cloud-alibaba 作為核心的客戶端組件。

[[410664]]

本文我們一起以源碼的維度來分析 Nacos 做為服務(wù)注冊中心的服務(wù)注冊過程,我會以服務(wù)端、客戶端兩個角度來進行分析,Nacos 客戶端我主要是采用 spring-cloud-alibaba 作為核心的客戶端組件。對于 Nacos 服務(wù)端我會講解到, Nacos 如何實現(xiàn) AP/CP 兩種模式共存的,以及如何區(qū)分的。最后還會分享我在源碼調(diào)試過程中如何定位核心類的一點經(jīng)驗。

下面我先對我的環(huán)境做一個簡單的介紹:

  • 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 服務(wù)架構(gòu)

以 Spring-Boot 為服務(wù)基礎(chǔ)搭建平臺, Nacos 在服務(wù)架構(gòu)中的位置如下圖所示:

圖片

總的來說和 Nacos 功能類似的中間件有 Eureka、Zookeeper、Consul 、Etcd 等。Nacos 最大的特點就是既能夠支持 AP、也能夠支持 CP 模式,在分區(qū)一致性方面使用的是 Raft 協(xié)議來實現(xiàn)。

Nacos 客戶端

服務(wù)注冊客戶端

添加依賴

Nacos 服務(wù)注冊是客戶端主動發(fā)起,利用 Spring 啟完成事件進行拓展調(diào)用服務(wù)注冊方法。首先我們需要導(dǎo)入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 

通過我的分析發(fā)現(xiàn) NacosServiceRegistryAutoConfiguration 是咱們服務(wù)注冊的核心配置類,該類中定義了三個核心的 Bean 對象:

  • NacosServiceRegistry
  • NacosRegistration
  • NacosAutoServiceRegistration

NacosAutoServiceRegistration

NacosAutoServiceRegistration 實現(xiàn)了服務(wù)向 Nacos 發(fā)起注冊的功能,它繼承自抽象類 AbstractAutoServiceRegistration 。

在抽象類 AbstractAutoServiceRegistration 中實現(xiàn) ApplicationContextAware、ApplicationListener 接口。在容器啟動、并且上下文準備就緒過后會調(diào)用 onApplicationEvent 方法。

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

再調(diào)用 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(); 

然后調(diào)用 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.  

最后調(diào)用 register(); 在內(nèi)部去調(diào)用 serviceRegistry.register() 方法完成服務(wù)注冊。

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

NacosServiceRegistry

NacosServiceRegistry 類主要的目的就是實現(xiàn)服務(wù)注冊

  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.    // 創(chuàng)建 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.    } 

我們可以看到最后調(diào)用的是 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); 

然后再調(diào)用 serverProxy.registerService(groupedServiceName, groupName, instance); 方法進行服務(wù)注冊,通過 beatReactor.addBeatinfo() 創(chuàng)建 schedule 每間隔 5s 向服務(wù)端發(fā)送一次心跳數(shù)據(jù)

  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 進行服務(wù)注冊 
  20.     reqApi(UtilAndComs.nacosUrlInstance, params, HttpMethod.POST); 
  21.      

服務(wù)注冊服務(wù)端

Nacos 做為服務(wù)注冊中心,既可以實現(xiàn)AP ,也能實現(xiàn) CP 架構(gòu)。來維護我們服務(wù)中心的服務(wù)列表。下面是我們服務(wù)列表一個簡單的數(shù)據(jù)模型示意圖:

圖片

其實就和咱們 NacosServiceRegistry#registry 構(gòu)建 Instance 實例的過程是一致的。繼續(xù)回到我們源碼分析我們直接來看服務(wù)端的 /nacos/v1/ns/instance 接口,被定義在 InstanceController#register 方法。

服務(wù)注冊

在 InstanceController#register 方法中,主要是解析 request 參數(shù)然后調(diào)用 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 方法的調(diào)用

  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); 

再調(diào)用 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.     } 

調(diào)用 consistencyService.put(key, instances); 刷新 service 中的所有 instance。我們通過 consistencyService 的定義可以知道它將調(diào)用 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 協(xié)議, CP 模式采用 Raft 協(xié)議。 
  6. private ConsistencyService mapConsistencyService(String key) { 
  7.     return KeyBuilder.matchEphemeralKey(key) ? ephemeralConsistencyService : persistentConsistencyService; 

AP 模式

Nacos 默認就是采用的 AP 模式使用 Distro 協(xié)議實現(xiàn)。實現(xiàn)的接口是 EphemeralConsistencyService 對節(jié)點信息的持久化主要是調(diào)用 put 方法

  1. @Override 
  2. public void put(String key, Record value) throws NacosException { 
  3.     // 數(shù)據(jù)持久化 
  4.     onPut(key, value); 
  5.     // 通知其他服務(wù)節(jié)點  
  6.     distroProtocol.sync(new DistroKey(key, KeyBuilder.INSTANCE_LIST_KEY_PREFIX), DataOperation.CHANGE, 
  7.             globalConfig.getTaskDispatchPeriod() / 2); 

在調(diào)用 doPut 來保存數(shù)據(jù)并且發(fā)通知

  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.         // 數(shù)據(jù)持久化  
  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 類型的事件會調(diào)用 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 方法會將服務(wù)實例信息,更新到注冊表的內(nèi)存中去,并且會以 udp 的方式通知當(dāng)前服務(wù)的訂閱者。

  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.         // 更新服務(wù)列表 
  43.         clusterMap.get(entry.getKey()).updateIps(entryIPs, ephemeral); 
  44.     } 
  45.      
  46.     setLastModifiedMillis(System.currentTimeMillis()); 
  47.     // 推送服務(wù)訂閱者消息  
  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 協(xié)議實現(xiàn)。實現(xiàn)類是 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.     } 

調(diào)用 raftCore.signalPublish(key, value); 主要的步驟如下

  • 判斷是否是 Leader 節(jié)點,如果不是 Leader 節(jié)點將請求轉(zhuǎn)發(fā)給 Leader 節(jié)點處理;
  • 如果是 Leader 節(jié)點,首先執(zhí)行 onPublish(datum, peers.local()); 方法,內(nèi)部首先通過 raftStore.updateTerm(local.term.get()); 方法持久化到文件,然后通過 NotifyCenter.publishEvent(ValueChangeEvent.builder().key(datum.key).action(DataOperation.CHANGE).build());異步更新到內(nèi)存;
  • 通過 CountDownLatch 實現(xiàn)了一個過半機制 new CountDownLatch(peers.majorityCount()) 只有當(dāng)成功的節(jié)點大于 N/2 + 1 的時候才返回成功。
  • 調(diào)用其他的 Nacos 節(jié)點的 /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 節(jié)點注冊時 ephemeral=true,那么 nacos 集群對這個 client 節(jié)點的效果就是 ap 的采用 distro,而注冊nacos 的 client 節(jié)點注冊時 ephemeral=false,那么nacos 集群對這個節(jié)點的效果就是 cp 的采用 raft。根據(jù) client 注冊時的屬性,ap,cp 同時混合存在,只是對不同的 client 節(jié)點效果不同

Nacos 源碼調(diào)試

Nacos 啟動文件

首先我們需要找到 Nacos 的啟動類,首先需要找到啟動的 jar.

圖片

然后我們在解壓 target/nacos-server.jar

解壓命令:

  1. # 解壓 jar 包 
  2. tar -zxvf nacos-server.jar 
  3.  
  4. # 查看 MANIFEST.MF 內(nèi)容 
  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 調(diào)試

通過 com.alibaba.nacos.Nacos 的啟動類,我們可以通過這個類在 Idea 中進行啟動,然后調(diào)試。

本文轉(zhuǎn)載自微信公眾號「運維開發(fā)故事」,可以通過以下二維碼關(guān)注。轉(zhuǎn)載本文請聯(lián)系運維開發(fā)故事公眾號。

 

責(zé)任編輯:姜華 來源: 運維開發(fā)故事
相關(guān)推薦

2021-07-16 06:56:50

Nacos注冊源碼

2022-05-06 07:52:06

Nacos服務(wù)注冊

2021-08-10 07:00:00

Nacos Clien服務(wù)分析

2021-08-09 07:58:36

Nacos 服務(wù)注冊源碼分析

2023-03-17 17:51:30

APIServer路由注冊

2020-06-29 07:58:18

ZooKeeperConsul 注冊中心

2022-02-07 07:10:32

服務(wù)注冊功能

2023-03-01 08:15:10

NginxNacos

2022-05-08 17:53:38

Nacos服務(wù)端客戶端

2022-02-09 07:03:01

SpringNacos服務(wù)注冊

2021-08-04 11:54:25

Nacos注冊中心設(shè)計

2023-04-26 08:19:48

Nacos高可用開發(fā)

2021-04-18 07:33:20

項目Springboot Nacos

2023-10-30 09:35:01

注冊中心微服務(wù)

2023-11-29 16:21:30

Kubernetes服務(wù)注冊

2023-02-26 00:00:00

2023-01-16 18:32:15

架構(gòu)APNacos

2021-05-18 20:22:00

Spring ClouNacos服務(wù)

2021-07-09 06:48:30

注冊源碼解析

2024-04-10 12:22:19

DubboNacos微服務(wù)
點贊
收藏

51CTO技術(shù)棧公眾號