公眾號文章匯總
714
2025-03-31
《配置中心 Spring Cloud Config 詳解》系列文章更新,一起在技術的路上精進!本系列文章將會介紹Spring Cloud 中提供了分布式配置中心Spring Cloud Config。應用服務中除了實現系統功能的代碼,還需要連接資源和其它應用,經常有很多需要在外部配置的數據去調整應用的行為,如切換不同的數據庫,設置功能開關等。隨著微服務的不斷增加,需要系統具備可伸縮和可擴展性,除此之外就是管理相當多的服務實例的配置數據。在應用的開發階段由各個服務自治,但是到了生產環境之后會給運維帶來很大的麻煩,特別是微服務的規模比較大,配置的更新更為麻煩。為此,系統需要建立一個統一的配置管理中心。
在前面的文章,我們進一步介紹了如何通過組合方式獲取配置。本文將會接著前面一篇文章,重點介紹如何獲取指定服務的資源文件。
ResourceRepositoryConfiguration是資源的配置類,在SearchPathLocator對象存在時,將ResourceRepository加入到Spring的上下文中。
@Bean @ConditionalOnBean(SearchPathLocator.class) public ResourceRepository resourceRepository(SearchPathLocator service) { return new GenericResourceRepository(service); }
前面講到EnvironmentRepository,相比而言ResourceRepository用來定位一個應用的資源,返回的是某一個具體的資源文件,最后其內容轉換成文本格式;而EnvironmentRepository返回的信息更加全面,是一種鍵值對的格式,包括應用的基本信息,指定應用的配置源(可能來自多個源或者共享配置文件),這些鍵值對可以替換資源文本中的占位符。
public interface ResourceRepository { Resource findOne(String name, String profile, String label, String path); }
最后返回的Resource是一個資源描述符的接口,用于抽象底層資源的實際類型,如文件或類路徑資源。
spring: profiles: dev cloud: version: Camden SR4
上面是示例項目中客戶端服務獲取其對應的資源文件的結果,Resource流經過轉化成String文本,
ResourceRepository接口的實現類為GenericResourceRepository,覆寫了findOne方法,返回配置數據。
public class GenericResourceRepository implements ResourceRepository, ResourceLoaderAware { private SearchPathLocator service; //通過構造函數設置SearchPathLocator對象 public GenericResourceRepository(SearchPathLocator service) { this.service = service; } //... @Override public synchronized Resource findOne(String application, String profile, String label, String path) { String[] locations = this.service.getLocations(application, profile, label).getLocations(); try { for (int i = locations.length; i-- > 0;) { String location = locations[i]; for (String local : getProfilePaths(profile, path)) { Resource file = this.resourceLoader.getResource(location) .createRelative(local); if (file.exists() && file.isReadable()) { return file; } } } } //... } }
從上面實現來看,主要是通過構造函數設置SearchPathLocator對象,傳入應用名等參數調用#getLocations方法得到配置資源的具體路徑,SearchPathLocator的實現類會保證是最新的配置倉庫。因為profile可以有默認值default,在創建資源文件之前,先調用#getProfilePaths方法根據profile值對path進行處理,然后由resourceLoader的#getResource(location)方法創建絕對路徑的配置資源。
小結
本文主要介紹了 Spring Cloud Config 服務端 Config Server 中如何獲取指定服務的資源文件。至此,服務端的內容就講解完了。
除此之外,Spring Cloud Config 服務端內置了一些對外查詢的 API 端點,下一篇文章將會具體介紹這些 REST 接口。
Spring Cloud 分布式
版權聲明:本文內容由網絡用戶投稿,版權歸原作者所有,本站不擁有其著作權,亦不承擔相應法律責任。如果您發現本站中有涉嫌抄襲或描述失實的內容,請聯系我們jiasou666@gmail.com 處理,核實后本網站將在24小時內刪除侵權內容。
版權聲明:本文內容由網絡用戶投稿,版權歸原作者所有,本站不擁有其著作權,亦不承擔相應法律責任。如果您發現本站中有涉嫌抄襲或描述失實的內容,請聯系我們jiasou666@gmail.com 處理,核實后本網站將在24小時內刪除侵權內容。