溫馨提示:

本文內容基於個人學習Nacos 2.0.1版本程式碼總結而來,因個人理解差異,不保證完全正確。如有理解錯誤之處歡迎各位拍磚指正,相互學習;轉載請註明出處。

Nacos服務端在處理健康檢查和心跳檢查任務的時候它是使用攔截器鏈來執行的。攔截器鏈內部有多個攔截器,通過獲取不同的攔截器鏈例項,在例項內部指定具體的攔截器型別來組成一組攔截器。這裡使用了攔截器模式和模板模式來組織程式碼。攔截器模式體現在整體攔截機制的實現;模板模式主要體現在對攔截器鏈的抽象實現上。

攔截器模式有三個要素

  • 攔截器
  • 排程者
  • 業務邏輯

攔截器

定義一個攔截器的基本功能,同時限定了傳入的攔截物件型別必須為Interceptable。這裡只定義了基本的功能和基本的限定攔截物件。這裡將其描述為基本的功能,那就意味著它的實現將會有更高階的功能。

  1. /**
  2. * Nacos naming interceptor.
  3. * 攔截器物件
  4. * @author xiweng.yy
  5. */
  6. public interface NacosNamingInterceptor<T extends Interceptable> {
  7. /**
  8. * Judge whether the input type is intercepted by this Interceptor.
  9. * 此攔截器的例項將會判斷傳入的物件是否是他需要處理的型別,此方法可以實現不同攔截器處理不同物件的隔離操作
  10. * <p>This method only should judge the object type whether need be do intercept. Not the intercept logic.
  11. * @param type type
  12. * @return true if the input type is intercepted by this Interceptor, otherwise false
  13. */
  14. boolean isInterceptType(Class<?> type);
  15. /**
  16. * Do intercept operation.
  17. * 執行攔截操作
  18. * <p>This method is the actual intercept operation.
  19. * @param object need intercepted object
  20. * @return true if object is intercepted, otherwise false
  21. */
  22. boolean intercept(T object);
  23. /**
  24. * The order of interceptor. The lower the number, the earlier the execution.
  25. * 攔截器排序,數字越低,優先順序越高
  26. * @return the order number of interceptor
  27. */
  28. int order();
  29. }

被攔截的物件

Interceptable 定義了對攔截操作相關的執行方法,passIntercept()在未被攔截的時候需要執行,afterIntercept()在被攔截之後需要執行。被攔截物件的業務邏輯需要由攔截器負責排程。

  1. /**
  2. * Interceptable Interface.
  3. *
  4. * @author xiweng.yy
  5. */
  6. public interface Interceptable {
  7. /**
  8. * If no {@link NacosNamingInterceptor} intercept this object, this method will be called to execute.
  9. */
  10. void passIntercept();
  11. /**
  12. * If one {@link NacosNamingInterceptor} intercept this object, this method will be called.
  13. */
  14. void afterIntercept();
  15. }

排程者

排程者主要是用來管理攔截器的組織方式,觸發攔截器的攔截操作。下圖展示了Naming模組的攔截器鏈的繼承關係。

整體的構成由NacosNamingInterceptorChain定義基本框架,AbstractNamingInterceptorChain實現通用邏輯,HealthCheckInterceptorChainInstanceBeatCheckTaskInterceptorChain則分別服務於健康檢查和心跳檢查。

NacosNamingInterceptorChain

定義了攔截器鏈物件應該具有的基本行為:新增攔截器、執行攔截器。

  1. /**
  2. * Nacos naming interceptor chain.
  3. * Nacos Naming模組的攔截器連結口,攔截器鏈用於儲存並管理多個攔截器
  4. * @author xiweng.yy
  5. */
  6. public interface NacosNamingInterceptorChain<T extends Interceptable> {
  7. /**
  8. * Add interceptor.
  9. * 新增指定型別的攔截器物件
  10. * @param interceptor interceptor
  11. */
  12. void addInterceptor(NacosNamingInterceptor<T> interceptor);
  13. /**
  14. * Do intercept by added interceptors.
  15. * 執行攔截的業務操作
  16. * @param object be interceptor object
  17. */
  18. void doInterceptor(T object);
  19. }

AbstractNamingInterceptorChain

AbstractNamingInterceptorChain實現了NacosNamingInterceptorChain所定義的對NacosNamingInterceptor的操作。在構造方法中提供了具體的攔截器實現類的載入,它這裡使用了SPI方式載入。預設可以載入的攔截器必須是NacosNamingInterceptor的例項。在攔截器的執行方法doInterceptor()中會按優先順序呼叫每一個攔截器,首先判斷被攔截的物件是否是此攔截器處理,接著呼叫攔截器的intercept()方法,成功後呼叫被攔截物件的afterIntercept()方法。若未攔截成功則呼叫被攔截物件的passIntercept()方法。因此在攔截器中的intercept()方法中可以定義攔截器對被攔截物件的處理邏輯,而被攔截物件則可以在afterIntercept()和passIntercept()方法中定義自身的處理邏輯。從而實現在攔截器中被處理和自身處理任務依賴於攔截器來觸發。

  1. /**
  2. * Abstract Naming Interceptor Chain.
  3. * 抽象的命名服務攔截器鏈,用於定義攔截器鏈的工作流程
  4. * @author xiweng.yy
  5. */
  6. public abstract class AbstractNamingInterceptorChain<T extends Interceptable> implements NacosNamingInterceptorChain<T> {
  7. // 儲存多個攔截器
  8. private final List<NacosNamingInterceptor<T>> interceptors;
  9. // 限制使用範圍為當前包或者其子類
  10. protected AbstractNamingInterceptorChain(Class<? extends NacosNamingInterceptor<T>> clazz) {
  11. this.interceptors = new LinkedList<>();
  12. // 使用SPI模式載入指定的攔截器型別
  13. // 而且NacosNamingInterceptor內部有判斷它需要攔截物件的型別,因此非常靈活
  14. interceptors.addAll(NacosServiceLoader.load(clazz));
  15. // 對攔截器的順序進行排序
  16. interceptors.sort(Comparator.comparingInt(NacosNamingInterceptor::order));
  17. }
  18. /**
  19. * Get all interceptors.
  20. *
  21. * @return interceptors list
  22. */
  23. protected List<NacosNamingInterceptor<T>> getInterceptors() {
  24. return interceptors;
  25. }
  26. @Override
  27. public void addInterceptor(NacosNamingInterceptor<T> interceptor) {
  28. // 若手動新增,則需要再次進行排序
  29. interceptors.add(interceptor);
  30. interceptors.sort(Comparator.comparingInt(NacosNamingInterceptor::order));
  31. }
  32. @Override
  33. public void doInterceptor(T object) {
  34. // 因為內部的攔截器已經排序過了,所以直接遍歷
  35. for (NacosNamingInterceptor<T> each : interceptors) {
  36. // 若當前攔截的物件不是當前攔截器所要處理的型別則調過
  37. if (!each.isInterceptType(object.getClass())) {
  38. continue;
  39. }
  40. // 執行攔截操作成功之後,繼續執行攔截後操作
  41. if (each.intercept(object)) {
  42. object.afterIntercept();
  43. return;
  44. }
  45. }
  46. // 未攔截的操作
  47. object.passIntercept();
  48. }
  49. }

doInterceptor() 方法中使用當前攔截器鏈內部的所有攔截器對被攔截物件進行處理,並且組織了被攔截物件被攔截之後的方法呼叫流程。即:攔截之後執行被攔截物件的afterIntercept()方法,未攔截時執行passIntercept()方法。

HealthCheckInterceptorChain

健康檢查攔截器鏈負責載入AbstractHealthCheckInterceptor型別的攔截器。

  1. /**
  2. * Health check interceptor chain.
  3. * @author xiweng.yy
  4. */
  5. public class HealthCheckInterceptorChain extends AbstractNamingInterceptorChain<NacosHealthCheckTask> {
  6. private static final HealthCheckInterceptorChain INSTANCE = new HealthCheckInterceptorChain();
  7. private HealthCheckInterceptorChain() {
  8. super(AbstractHealthCheckInterceptor.class);
  9. }
  10. public static HealthCheckInterceptorChain getInstance() {
  11. return INSTANCE;
  12. }
  13. }

InstanceBeatCheckTaskInterceptorChain

例項心跳檢查器鏈負責載入AbstractBeatCheckInterceptor型別的攔截器。

  1. /**
  2. * Instance beat check interceptor chain.
  3. *
  4. * @author xiweng.yy
  5. */
  6. public class InstanceBeatCheckTaskInterceptorChain extends AbstractNamingInterceptorChain<InstanceBeatCheckTask> {
  7. private static final InstanceBeatCheckTaskInterceptorChain INSTANCE = new InstanceBeatCheckTaskInterceptorChain();
  8. private InstanceBeatCheckTaskInterceptorChain() {
  9. super(AbstractBeatCheckInterceptor.class);
  10. }
  11. public static InstanceBeatCheckTaskInterceptorChain getInstance() {
  12. return INSTANCE;
  13. }
  14. }

小結

通過模板模式來實現攔截器機制。

  • AbstractNamingInterceptorChain 抽象出聯結器鏈對攔截器載入的通用方法,定義了攔截器對被攔截物件的通用處理流程。
  • AbstractHealthCheckInterceptor 定義了健康檢查攔截器被攔截的物件型別
  • AbstractBeatCheckInterceptor 定義了心跳檢查攔截器被攔截的物件型別

通過對攔截器鏈的組織方式梳理可以看到有明顯的兩條路線,一個是健康檢查,一個是心跳檢查。分析後續具體的攔截器,以及他們所要處理的任務就很清晰了。

業務邏輯

業務邏輯是被攔截器攔截之後需要進行的操作。

健康檢查類的被攔截物件

健康檢查的抽象攔截器AbstractHealthCheckInterceptor定義了它的子類將要處理的任務型別為NacosHealthCheckTask

HealthCheckTaskV2

  1. /**
  2. * Health check task for v2.x.
  3. * v2版本的健康檢查
  4. * <p>Current health check logic is same as v1.x. TODO refactor health check for v2.x.
  5. *
  6. * @author nacos
  7. */
  8. public class HealthCheckTaskV2 extends AbstractExecuteTask implements NacosHealthCheckTask {
  9. /**
  10. * 一個客戶端物件(此客戶端代表提供服務用於被應用訪問的客戶端)
  11. * 從這裡可以看出,啟動一個健康檢查任務是以客戶端為維度的
  12. */
  13. private final IpPortBasedClient client;
  14. private final String taskId;
  15. private final SwitchDomain switchDomain;
  16. private final NamingMetadataManager metadataManager;
  17. private long checkRtNormalized = -1;
  18. /**
  19. * 檢查最佳響應時間
  20. */
  21. private long checkRtBest = -1;
  22. /**
  23. * 檢查最差響應時間
  24. */
  25. private long checkRtWorst = -1;
  26. /**
  27. * 檢查上次響應時間
  28. */
  29. private long checkRtLast = -1;
  30. /**
  31. * 檢查上上次響應時間
  32. */
  33. private long checkRtLastLast = -1;
  34. /**
  35. * 開始時間
  36. */
  37. private long startTime;
  38. /**
  39. * 任務是否取消
  40. */
  41. private volatile boolean cancelled = false;
  42. public HealthCheckTaskV2(IpPortBasedClient client) {
  43. this.client = client;
  44. this.taskId = client.getResponsibleId();
  45. this.switchDomain = ApplicationUtils.getBean(SwitchDomain.class);
  46. this.metadataManager = ApplicationUtils.getBean(NamingMetadataManager.class);
  47. // 初始化響應時間檢查
  48. initCheckRT();
  49. }
  50. /**
  51. * 初始化響應時間值
  52. */
  53. private void initCheckRT() {
  54. // first check time delay
  55. // 2000 + (在5000以內的隨機數)
  56. checkRtNormalized =
  57. 2000 + RandomUtils.nextInt(0, RandomUtils.nextInt(0, switchDomain.getTcpHealthParams().getMax()));
  58. // 最佳響應時間
  59. checkRtBest = Long.MAX_VALUE;
  60. // 最差響應時間為0
  61. checkRtWorst = 0L;
  62. }
  63. public IpPortBasedClient getClient() {
  64. return client;
  65. }
  66. @Override
  67. public String getTaskId() {
  68. return taskId;
  69. }
  70. /**
  71. * 開始執行健康檢查任務
  72. */
  73. @Override
  74. public void doHealthCheck() {
  75. try {
  76. // 獲取當前傳入的Client所釋出的所有Service
  77. for (Service each : client.getAllPublishedService()) {
  78. // 只有當Service開啟了健康檢查才執行
  79. if (switchDomain.isHealthCheckEnabled(each.getGroupedServiceName())) {
  80. // 獲取Service對應的InstancePublishInfo
  81. InstancePublishInfo instancePublishInfo = client.getInstancePublishInfo(each);
  82. // 獲取叢集元資料
  83. ClusterMetadata metadata = getClusterMetadata(each, instancePublishInfo);
  84. // 使用Processor代理物件對任務進行處理
  85. ApplicationUtils.getBean(HealthCheckProcessorV2Delegate.class).process(this, each, metadata);
  86. if (Loggers.EVT_LOG.isDebugEnabled()) {
  87. Loggers.EVT_LOG.debug("[HEALTH-CHECK] schedule health check task: {}", client.getClientId());
  88. }
  89. }
  90. }
  91. } catch (Throwable e) {
  92. Loggers.SRV_LOG.error("[HEALTH-CHECK] error while process health check for {}", client.getClientId(), e);
  93. } finally {
  94. // 若任務執行狀態為已取消,則再次啟動
  95. if (!cancelled) {
  96. HealthCheckReactor.scheduleCheck(this);
  97. // worst == 0 means never checked
  98. if (this.getCheckRtWorst() > 0) {
  99. // TLog doesn't support float so we must convert it into long
  100. long checkRtLastLast = getCheckRtLastLast();
  101. this.setCheckRtLastLast(this.getCheckRtLast());
  102. if (checkRtLastLast > 0) {
  103. long diff = ((this.getCheckRtLast() - this.getCheckRtLastLast()) * 10000) / checkRtLastLast;
  104. if (Loggers.CHECK_RT.isDebugEnabled()) {
  105. Loggers.CHECK_RT.debug("{}->normalized: {}, worst: {}, best: {}, last: {}, diff: {}",
  106. client.getClientId(), this.getCheckRtNormalized(), this.getCheckRtWorst(),
  107. this.getCheckRtBest(), this.getCheckRtLast(), diff);
  108. }
  109. }
  110. }
  111. }
  112. }
  113. }
  114. @Override
  115. public void passIntercept() {
  116. doHealthCheck();
  117. }
  118. @Override
  119. public void afterIntercept() {
  120. // 若任務執行狀態為已取消,則再次啟動
  121. if (!cancelled) {
  122. HealthCheckReactor.scheduleCheck(this);
  123. }
  124. }
  125. @Override
  126. public void run() {
  127. // 呼叫健康檢查
  128. doHealthCheck();
  129. }
  130. /**
  131. * 獲取叢集元資料
  132. * @param service 服務資訊
  133. * @param instancePublishInfo 服務對應的ip等資訊
  134. * @return
  135. */
  136. private ClusterMetadata getClusterMetadata(Service service, InstancePublishInfo instancePublishInfo) {
  137. Optional<ServiceMetadata> serviceMetadata = metadataManager.getServiceMetadata(service);
  138. if (!serviceMetadata.isPresent()) {
  139. return new ClusterMetadata();
  140. }
  141. String cluster = instancePublishInfo.getCluster();
  142. ClusterMetadata result = serviceMetadata.get().getClusters().get(cluster);
  143. return null == result ? new ClusterMetadata() : result;
  144. }
  145. public long getCheckRtNormalized() {
  146. return checkRtNormalized;
  147. }
  148. public long getCheckRtBest() {
  149. return checkRtBest;
  150. }
  151. public long getCheckRtWorst() {
  152. return checkRtWorst;
  153. }
  154. public void setCheckRtWorst(long checkRtWorst) {
  155. this.checkRtWorst = checkRtWorst;
  156. }
  157. public void setCheckRtBest(long checkRtBest) {
  158. this.checkRtBest = checkRtBest;
  159. }
  160. public void setCheckRtNormalized(long checkRtNormalized) {
  161. this.checkRtNormalized = checkRtNormalized;
  162. }
  163. public boolean isCancelled() {
  164. return cancelled;
  165. }
  166. public void setCancelled(boolean cancelled) {
  167. this.cancelled = cancelled;
  168. }
  169. public long getStartTime() {
  170. return startTime;
  171. }
  172. public void setStartTime(long startTime) {
  173. this.startTime = startTime;
  174. }
  175. public long getCheckRtLast() {
  176. return checkRtLast;
  177. }
  178. public void setCheckRtLast(long checkRtLast) {
  179. this.checkRtLast = checkRtLast;
  180. }
  181. public long getCheckRtLastLast() {
  182. return checkRtLastLast;
  183. }
  184. public void setCheckRtLastLast(long checkRtLastLast) {
  185. this.checkRtLastLast = checkRtLastLast;
  186. }
  187. }

心跳檢查類的被攔截物件

ClientBeatCheckTaskV2

雖然它繼承了NacosHealthCheckTask,但內部只使用了InstanceBeatCheckTaskInterceptorChain,沒有使用HealthCheckInterceptorChain, 按理說應該劃分到"心跳檢查類的被攔截物件" 這個類別的。不知道為何這樣設計,已提issues。

  1. /**
  2. * Client beat check task of service for version 2.x.
  3. * @author nkorange
  4. */
  5. public class ClientBeatCheckTaskV2 extends AbstractExecuteTask implements BeatCheckTask, NacosHealthCheckTask {
  6. private final IpPortBasedClient client;
  7. private final String taskId;
  8. /**
  9. * 使用攔截器鏈
  10. */
  11. private final InstanceBeatCheckTaskInterceptorChain interceptorChain;
  12. public ClientBeatCheckTaskV2(IpPortBasedClient client) {
  13. this.client = client;
  14. this.taskId = client.getResponsibleId();
  15. this.interceptorChain = InstanceBeatCheckTaskInterceptorChain.getInstance();
  16. }
  17. public GlobalConfig getGlobalConfig() {
  18. return ApplicationUtils.getBean(GlobalConfig.class);
  19. }
  20. @Override
  21. public String taskKey() {
  22. return KeyBuilder.buildServiceMetaKey(client.getClientId(), String.valueOf(client.isEphemeral()));
  23. }
  24. @Override
  25. public String getTaskId() {
  26. return taskId;
  27. }
  28. @Override
  29. public void doHealthCheck() {
  30. try {
  31. // 獲取所有的Service
  32. Collection<Service> services = client.getAllPublishedService();
  33. for (Service each : services) {
  34. logger.info("開始對Service進行攔截操作,{}", each.getName());
  35. // 獲取Service對應的InstancePublishInfo
  36. HealthCheckInstancePublishInfo instance = (HealthCheckInstancePublishInfo) client.getInstancePublishInfo(each);
  37. // 建立一個InstanceBeatCheckTask,並交由攔截器鏈處理
  38. interceptorChain.doInterceptor(new InstanceBeatCheckTask(client, each, instance));
  39. }
  40. } catch (Exception e) {
  41. Loggers.SRV_LOG.warn("Exception while processing client beat time out.", e);
  42. }
  43. }
  44. @Override
  45. public void run() {
  46. doHealthCheck();
  47. }
  48. @Override
  49. public void passIntercept() {
  50. doHealthCheck();
  51. }
  52. @Override
  53. public void afterIntercept() {
  54. }
  55. }

InstanceBeatCheckTask

  1. /**
  2. * Instance beat check task.
  3. * Instance心跳檢查任務,此處它作為一個可被攔截器攔截的物件使用。
  4. * @author xiweng.yy
  5. */
  6. public class InstanceBeatCheckTask implements Interceptable {
  7. // 心跳檢查者列表
  8. private static final List<InstanceBeatChecker> CHECKERS = new LinkedList<>();
  9. // 客戶端物件(因為例項就代表的是客戶端)
  10. private final IpPortBasedClient client;
  11. // 服務物件
  12. private final Service service;
  13. // 健康檢查資訊
  14. private final HealthCheckInstancePublishInfo instancePublishInfo;
  15. static {
  16. // 新增不健康例項檢查器
  17. CHECKERS.add(new UnhealthyInstanceChecker());
  18. // 新增過期例項檢查器
  19. CHECKERS.add(new ExpiredInstanceChecker());
  20. // 新增使用者自定義的心跳檢查器
  21. CHECKERS.addAll(NacosServiceLoader.load(InstanceBeatChecker.class));
  22. }
  23. public InstanceBeatCheckTask(IpPortBasedClient client, Service service, HealthCheckInstancePublishInfo instancePublishInfo) {
  24. this.client = client;
  25. this.service = service;
  26. this.instancePublishInfo = instancePublishInfo;
  27. }
  28. @Override
  29. public void passIntercept() {
  30. // 未被攔截的時候執行自身邏輯
  31. for (InstanceBeatChecker each : CHECKERS) {
  32. each.doCheck(client, service, instancePublishInfo);
  33. }
  34. }
  35. @Override
  36. public void afterIntercept() {
  37. }
  38. public IpPortBasedClient getClient() {
  39. return client;
  40. }
  41. public Service getService() {
  42. return service;
  43. }
  44. public HealthCheckInstancePublishInfo getInstancePublishInfo() {
  45. return instancePublishInfo;
  46. }
  47. }

總結

  • 攔截器鏈確定了要載入的攔截器型別
  • 攔截器確定了要攔截的物件型別
  • 被攔截的物件又建立了自己的檢查策略