[spring-cloud: 服務發現]-源碼解析

DiscoveryClient

DiscoveryClient 接口定義了常見的服務發現操作,如獲取服務實例、獲取所有服務ID、驗證客戶端可用性等,通常用于 Eureka 或 Consul 等服務發現框架。

public interface DiscoveryClient extends Ordered {/*** Default order of the discovery client.*/int DEFAULT_ORDER = 0;/*** A human-readable description of the implementation, used in HealthIndicator.* @return The description.*/String description();/*** Gets all ServiceInstances associated with a particular serviceId.* @param serviceId The serviceId to query.* @return A List of ServiceInstance.*/List<ServiceInstance> getInstances(String serviceId);/*** @return All known service IDs.*/List<String> getServices();/*** Can be used to verify the client is valid and able to make calls.* <p>* A successful invocation with no exception thrown implies the client is able to make* calls.* <p>* The default implementation simply calls {@link #getServices()} - client* implementations can override with a lighter weight operation if they choose to.*/default void probe() {getServices();}/*** Default implementation for getting order of discovery clients.* @return order*/@Overridedefault int getOrder() {return DEFAULT_ORDER;}}

Simple

1. SimpleDiscoveryClientAutoConfiguration

SimpleDiscoveryClientAutoConfiguration 是 Spring Boot 自動配置類,基于配置文件屬性創建一個簡單的服務發現客戶端。

/*** Spring Boot auto-configuration for simple properties-based discovery client.** @author Biju Kunjummen* @author Charu Covindane*/
@Configuration(proxyBeanMethods = false)
@AutoConfigureBefore({ CommonsClientAutoConfiguration.class })
public class SimpleDiscoveryClientAutoConfiguration implements ApplicationListener<WebServerInitializedEvent> {private ServerProperties server;private InetUtils inet;private int port = 0;private SimpleDiscoveryProperties simple = new SimpleDiscoveryProperties();@Autowired(required = false)public void setServer(ServerProperties server) {this.server = server;}@Autowiredpublic void setInet(InetUtils inet) {this.inet = inet;}@Bean@ConditionalOnMissingBeanpublic SimpleDiscoveryProperties simpleDiscoveryProperties(@Value("${spring.application.name:application}") String serviceId) {simple.getLocal().setServiceId(serviceId);simple.getLocal().setHost(inet.findFirstNonLoopbackHostInfo().getHostname());simple.getLocal().setPort(findPort());return simple;}@Bean@Orderpublic DiscoveryClient simpleDiscoveryClient(SimpleDiscoveryProperties properties) {return new SimpleDiscoveryClient(properties);}private int findPort() {if (port > 0) {return port;}if (server != null && server.getPort() != null && server.getPort() > 0) {return server.getPort();}return 8080;}@Overridepublic void onApplicationEvent(WebServerInitializedEvent webServerInitializedEvent) {port = webServerInitializedEvent.getWebServer().getPort();if (port > 0) {simple.getLocal().setHost(inet.findFirstNonLoopbackHostInfo().getHostname());simple.getLocal().setPort(port);}}}

2. SimpleDiscoveryClient

SimpleDiscoveryClient 是一個簡單的 DiscoveryClient 實現,使用屬性文件作為服務實例的來源,提供獲取服務實例和服務列表的功能。

/*** A {@link org.springframework.cloud.client.discovery.DiscoveryClient} that will use the* properties file as a source of service instances.** @author Biju Kunjummen* @author Olga Maciaszek-Sharma* @author Charu Covindane*/
public class SimpleDiscoveryClient implements DiscoveryClient {private SimpleDiscoveryProperties simpleDiscoveryProperties;public SimpleDiscoveryClient(SimpleDiscoveryProperties simpleDiscoveryProperties) {this.simpleDiscoveryProperties = simpleDiscoveryProperties;}@Overridepublic String description() {return "Simple Discovery Client";}@Overridepublic List<ServiceInstance> getInstances(String serviceId) {List<ServiceInstance> serviceInstances = new ArrayList<>();List<DefaultServiceInstance> serviceInstanceForService = this.simpleDiscoveryProperties.getInstances().get(serviceId);if (serviceInstanceForService != null) {serviceInstances.addAll(serviceInstanceForService);}return serviceInstances;}@Overridepublic List<String> getServices() {return new ArrayList<>(this.simpleDiscoveryProperties.getInstances().keySet());}@Overridepublic int getOrder() {return this.simpleDiscoveryProperties.getOrder();}}

Composite

1. CompositeDiscoveryClientAutoConfiguration

CompositeDiscoveryClientAutoConfiguration 是一個自動配置類,負責創建并注入 CompositeDiscoveryClient,將多個 DiscoveryClient 合并成一個客戶端。

/*** Auto-configuration for composite discovery client.** @author Biju Kunjummen*/
@Configuration(proxyBeanMethods = false)
@AutoConfigureBefore(SimpleDiscoveryClientAutoConfiguration.class)
public class CompositeDiscoveryClientAutoConfiguration {@Bean@Primarypublic CompositeDiscoveryClient compositeDiscoveryClient(List<DiscoveryClient> discoveryClients) {return new CompositeDiscoveryClient(discoveryClients);}}

2. CompositeDiscoveryClient

CompositeDiscoveryClient 是一個將多個 DiscoveryClient 組合在一起的客戶端,它依次查詢各個客戶端獲取服務實例,確保高可用性和靈活性。

public class CompositeDiscoveryClient implements DiscoveryClient {private final List<DiscoveryClient> discoveryClients;public CompositeDiscoveryClient(List<DiscoveryClient> discoveryClients) {AnnotationAwareOrderComparator.sort(discoveryClients);this.discoveryClients = discoveryClients;}@Overridepublic String description() {return "Composite Discovery Client";}@Overridepublic List<ServiceInstance> getInstances(String serviceId) {if (this.discoveryClients != null) {for (DiscoveryClient discoveryClient : this.discoveryClients) {List<ServiceInstance> instances = discoveryClient.getInstances(serviceId);if (instances != null && !instances.isEmpty()) {return instances;}}}return Collections.emptyList();}@Overridepublic List<String> getServices() {LinkedHashSet<String> services = new LinkedHashSet<>();if (this.discoveryClients != null) {for (DiscoveryClient discoveryClient : this.discoveryClients) {List<String> serviceForClient = discoveryClient.getServices();if (serviceForClient != null) {services.addAll(serviceForClient);}}}return new ArrayList<>(services);}@Overridepublic void probe() {if (this.discoveryClients != null) {for (DiscoveryClient discoveryClient : this.discoveryClients) {discoveryClient.probe();}}}public List<DiscoveryClient> getDiscoveryClients() {return this.discoveryClients;}}

Nacos

Nacos是一個開源的動態服務發現、配置管理和服務管理平臺,廣泛用于微服務架構中的服務治理與配置管理。

1. NacosDiscoveryAutoConfiguration

NacosDiscoveryAutoConfiguration 類是一個 Spring 配置類,用于自動配置 Nacos 服務發現功能。它在 Nacos 服務發現啟用時創建所需的 NacosDiscoveryPropertiesNacosServiceDiscovery Bean,并確保在沒有其他相關 Bean 的情況下提供默認配置。

@Configuration(proxyBeanMethods = false)
@ConditionalOnDiscoveryEnabled
@ConditionalOnNacosDiscoveryEnabled
public class NacosDiscoveryAutoConfiguration {@Bean@ConditionalOnMissingBeanpublic NacosDiscoveryProperties nacosProperties() {return new NacosDiscoveryProperties();}@Bean@ConditionalOnMissingBeanpublic NacosServiceDiscovery nacosServiceDiscovery(NacosDiscoveryProperties discoveryProperties, NacosServiceManager nacosServiceManager) {return new NacosServiceDiscovery(discoveryProperties, nacosServiceManager);}}

2. NacosDiscoveryClientConfiguration

NacosDiscoveryClientConfiguration 類用于配置和初始化 Nacos 服務發現客戶端及其相關功能,如 DiscoveryClientNacosWatch

@Configuration(proxyBeanMethods = false)
@ConditionalOnDiscoveryEnabled
@ConditionalOnBlockingDiscoveryEnabled
@ConditionalOnNacosDiscoveryEnabled
@AutoConfigureBefore({ SimpleDiscoveryClientAutoConfiguration.class, CommonsClientAutoConfiguration.class })
@AutoConfigureAfter(NacosDiscoveryAutoConfiguration.class)
public class NacosDiscoveryClientConfiguration {@Beanpublic DiscoveryClient nacosDiscoveryClient(NacosServiceDiscovery nacosServiceDiscovery) {return new NacosDiscoveryClient(nacosServiceDiscovery);}/*** NacosWatch is no longer enabled by default .* see https://github.com/alibaba/spring-cloud-alibaba/issues/2868*/@Bean@ConditionalOnMissingBean@ConditionalOnProperty(value = "spring.cloud.nacos.discovery.watch.enabled", matchIfMissing = false)public NacosWatch nacosWatch(NacosServiceManager nacosServiceManager,NacosDiscoveryProperties nacosDiscoveryProperties) {return new NacosWatch(nacosServiceManager, nacosDiscoveryProperties);}}

3. NacosDiscoveryClient

NacosDiscoveryClient 實現了 DiscoveryClient 接口,通過與 Nacos 服務發現交互,提供獲取服務實例和服務列表的功能,同時支持故障容錯。

public class NacosDiscoveryClient implements DiscoveryClient {private static final Logger log = LoggerFactory.getLogger(NacosDiscoveryClient.class);public static final String DESCRIPTION = "Spring Cloud Nacos Discovery Client";private NacosServiceDiscovery serviceDiscovery;@Value("${spring.cloud.nacos.discovery.failure-tolerance-enabled:false}")private boolean failureToleranceEnabled;public NacosDiscoveryClient(NacosServiceDiscovery nacosServiceDiscovery) {this.serviceDiscovery = nacosServiceDiscovery;}@Overridepublic String description() {return DESCRIPTION;}@Overridepublic List<ServiceInstance> getInstances(String serviceId) {try {return Optional.of(serviceDiscovery.getInstances(serviceId)).map(instances -> {ServiceCache.setInstances(serviceId, instances);return instances;}).get();}catch (Exception e) {if (failureToleranceEnabled) {return ServiceCache.getInstances(serviceId);}throw new RuntimeException("Can not get hosts from nacos server. serviceId: " + serviceId, e);}}@Overridepublic List<String> getServices() {try {return Optional.of(serviceDiscovery.getServices()).map(services -> {ServiceCache.setServiceIds(services);return services;}).get();}catch (Exception e) {log.error("get service name from nacos server failed.", e);return failureToleranceEnabled ? ServiceCache.getServiceIds(): Collections.emptyList();}}}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/917436.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/917436.shtml
英文地址,請注明出處:http://en.pswp.cn/news/917436.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

QML 基礎語法與對象模型

QML (Qt Meta-Object Language) 是一種聲明式語言&#xff0c;專為創建流暢的用戶界面和應用程序邏輯而設計。作為 Qt 框架的一部分&#xff0c;QML 提供了簡潔、直觀的語法來描述 UI 組件及其交互方式。本文將深入解析 QML 的基礎語法和對象模型。 一、QML 基礎語法 1. 基本對…

HTTPS的概念和工作過程

一.HTTPS是什么HTTPS也是一個應用層協議&#xff0c;是在HTTP協議的基礎上引入了一個加密層&#xff08;SSL&#xff09;HTTP協議內容都是按照文本的方式明文傳輸的&#xff0c;這就導致傳輸過程中可能出現被篡改的情況最著名的就是十多年前網絡剛發展的時期&#xff0c;出現“…

Unity —— Android 應用構建與發布?

文章目錄1 ?Gradle模板??&#xff1a;了解Gradle模板的作用及使用方法&#xff0c;以增強對構建流程的控制。?2 ?Gradle模板變量??&#xff1a;參考文檔——自定義Gradle模板文件中可用的變量列表。2.1 修改Unity應用的Gradle工程文件2.1.1 通過Gradle模板文件2.1.2 導出…

【iOS】strong和copy工作流程探尋、OC屬性關鍵字復習

文章目錄前言strong和copy的區別為什么要用copy&#xff1f;什么時候用什么修飾&#xff1f;strong&#xff08;ARC自動管理&#xff09;strong修飾變量的底層流程圖底層代碼核心實現小結copy底層流程圖對比與strong的關鍵不同之處內部調用關系&#xff08;偽代碼&#xff09;小…

程序代碼篇---多循環串口程序切換

上位機版&#xff08;Python&#xff09;要實現根據串口接收結果高效切換四個 while 循環函數&#xff0c;我們可以采用狀態機模式&#xff0c;配合非阻塞串口讀取來設計程序結構。這種方式可以實現快速切換&#xff0c;避免不必要的資源消耗。下面是一個高效的實現方案&#x…

rk3568上,實現ota,計算hash,驗證簽名,判斷激活分區,并通過dd命令,寫入對應AB分區

通過自定義升級程序&#xff0c;更直觀的理解ota升級原理。 一、模擬計算hash&#xff0c;驗證簽名&#xff0c;判斷激活分區&#xff0c;并通過dd命令&#xff0c;寫入對應分區 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <u…

數據分析—numpy庫

numpy庫NumPy 庫全面指南NumPy (Numerical Python) 是 Python 科學計算的基礎庫&#xff0c;提供了高性能的多維數組對象和工具。以下是 NumPy 的核心功能和使用方法。一、安裝與基礎1. 安裝 NumPypip install numpy2. 導入 NumPyimport numpy as np # 標準導入方式二、數組創建…

Vue3 setup、ref和reactive函數

一、setup函數1.理解&#xff1a;Vue3.0中一個新的配置項&#xff0c;值為一個函數。2.setup是所有Composition API(組合API)的“表演舞臺”。3.組件中用到的&#xff1a;數據、方法等等&#xff0c;均要配置在setup中。4.setup函數的兩種返回值&#xff1a;(1).若返回一個對象…

python中appium 的NoSuchElementException錯誤 原因以及解決辦法

錯誤收集D:\Program\Util\python.exe "D:/Program/myUtil/PyCharm 2024.3.5/plugins/python-ce/helpers/pycharm/_jb_pytest_runner.py" --target demo.py::TestAppium Testing started at 15:57 ... Launching pytest with arguments demo.py::TestAppium --no-hea…

mybatis-plus從入門到入土(四):持久層接口之BaseMapper和選裝件

大家好&#xff0c;今天繼續更新MybatisPlus從入門到入土系列&#xff0c;上一次的持久層接口還沒講完&#xff0c;只講了IService接口&#xff0c;今天我們繼續來講一下。 BaseMapper BaseMapper中的方法也比較簡單&#xff0c;都是增刪改查的基礎API&#xff0c;不知道大家還…

數組和指針的關系

在 C 語言中&#xff0c;?指針和數組有著非常緊密的聯系&#xff0c;但它們本質上是 ?不同的概念。理解它們的關系是掌握 C 語言內存操作的關鍵。下面我會從多個角度幫你梳理 ?指針和數組的直接聯系&#xff0c;并解釋它們的異同點。1. 數組和指針的本質區別?概念本質存儲方…

AI大模型探索之路-實戰篇:智能化IT領域搜索引擎之github網站在線搜索

系列篇章?? No. 文章 1 AI大模型探索之路-實戰篇:智能化IT領域搜索引擎的構建與初步實踐 2 AI大模型探索之路-實戰篇:智能化IT領域搜索引擎之GLM-4大模型技術的實踐探索 3 AI大模型探索之路-實戰篇:智能化IT領域搜索引擎之知乎網站數據獲取(初步實踐) 4 AI大模型探索之路…

從0到1學PHP(十二):PHP 框架入門與項目實戰

目錄一、主流 PHP 框架介紹1.1 Laravel1.2 ThinkPHP1.3 Yii1.4 框架的優勢二、框架基本使用&#xff08;以 Laravel 為例&#xff09;2.1 框架的安裝與配置2.2 路由定義、控制器創建、視圖渲染2.3 數據庫操作&#xff08;ORM 的使用&#xff09;三、小型項目實戰3.1 項目需求分…

MPLS LSP

一、概述上一章我們已經介紹過,LSP是MPLS報文在MPLS網絡中轉發時經過的路徑,可以看作是由報文傳輸方向節點為對應FEC分配的MPLS入標簽組成的,因為每臺設備上為每個FEC分配的入標簽是唯一 的&#xff0c;并與由下游節點為本地節點上該FEC分配的出標簽建立映射關系&#xff0c; 所…

圖像、視頻、音頻多模態大模型中長上下文token壓縮方法綜述

多模態大模型MLLMs 能夠處理高分辨率圖像、長視頻序列和冗長音頻輸入等復雜上下文&#xff0c;但自注意力機制的二次復雜度使得大量輸入 token 帶來了巨大的計算和內存需求。 如下圖&#xff0c;上&#xff1a;圖像、視頻和音頻數據類型可以在其表示維度上進行擴展&#xff0c;…

Spring MVC 九大組件源碼深度剖析(一):MultipartResolver - 文件上傳的幕后指揮官

文章目錄一、為什么從 MultipartResolver 開始&#xff1f;二、核心接口&#xff1a;定義文件上傳的契約三、實現解析&#xff1a;兩種策略的源碼較量1. StandardServletMultipartResolver&#xff08;Servlet 3.0 首選&#xff09;2. CommonsMultipartResolver&#xff08;兼容…

stm32是如何實現電源控制的?

STM32的電源控制主要通過內置的電源管理模塊&#xff08;PWR&#xff09;實現&#xff0c;涵蓋電壓調節、功耗模式切換和電源監控等功能。以下是其核心機制及實現方式&#xff1a;??1. 電源架構與供電區域??STM32的電源系統分為多個供電區域&#xff0c;各司其職&#xff1…

《R for Data Science (2e)》免費中文翻譯 (第3章) --- Data transformation(1)

寫在前面 本系列推文為《R for Data Science (2)》的中文翻譯版本。所有內容都通過開源免費的方式上傳至Github&#xff0c;歡迎大家參與貢獻&#xff0c;詳細信息見&#xff1a; Books-zh-cn 項目介紹&#xff1a; Books-zh-cn&#xff1a;開源免費的中文書籍社區 r4ds-zh-cn …

rclone、rsync、scp使用總結

數據同步工具使用總結【rclone、rsync、scp】一、數據處理背景二、數據處理方法對比1、數據關系梳理2、不同工具處理方法3、經驗總結三、工具擴展知識1、rclone工具介紹&#xff08;1&#xff09;、rclone概述&#xff08;2&#xff09;、安裝工具及配置本地文件遷移到云上服務…

用latex+vscode+ctex寫畢業論文

文章目錄前言一、安裝latex二、安裝ctex包三、更新ctex包四、使用ctex文檔類前言 用latexvscodectex寫畢業論文。&#xff08;英文論文不用安裝ctex&#xff09; CTEX 宏集是面向中文排版的通用 LATEX 排版框架&#xff0c;為中文 LATEX 文檔提供了漢字輸出支持、標點壓縮、字…