Spring cloud Config:分佈式配置中心 一、構建配置中心: (1)創建Spring Boot工程,命名爲config-server,並導入pom依賴 spring-cloud-config-server (2)創建Spring Boot的程序主類,添加@EnableConfigServer註解(開啓Spring Cloud Config服務端功能) (3)配置yml文件或(properties)spring: application: name: server-config cloud: config: server: git: uri: https://github.com/你的respository/ # git遠程倉庫地址 username: ******** #git倉庫用戶名 password: ........ #密碼 search-paths: Repo_config #配置相對搜索路徑,可配置多個,一般用來存儲配置文件 eureka: client: serviceUrl: defaultZone: http://alice:[email protected]:7555/eureka/ server: port: 7888 Repo-config的完整路徑如下:https://github.com/roseJoke/bloomRose/Repo_config 我是創建在git倉庫repository下。 新建配置文件(注意:yml與properties中配置格式不同,yml中用“:”,properties中用“=”,錯誤書寫會造成讀取異常、無內容,還應注意中英文格式) application.yml/properties 其中設置內容:from: git-default-1.0/from=git-default-1.0 application-dev.yml/properties 內容:from: git-dev-1.0 application-prod.yml/properties 內容:from: git-prod-1.0 application-test.yml/properties 內容:from: git-test-1.0 版本測試的話可以新建分支,這裏不詳細敘述了。 git上默認分支是master 如果沒有問題就可以啓動了application項目了 通過瀏覽器訪問http://localhost:7888/application/prod/master 會返回分支信息,如果沒有錯誤的話應該是沒什麼問題了 二、客戶端配置映射: (1)創建Spring Boot應用,命名爲config-client,並在pom中導入依賴 spring-cloud-starter-web (2) 創建應用主類,創建配置文件bootstrap.properites(舉例說明:以application-dev.yml爲例,application爲name,dev爲profile,label如果你沒創建分支默認是master) spring.application.name=application #對應配置文件中{application}部分 spring.cloud.config.profile=dev #對應配置文件中{profile}部分 spring.cloud.config.label=master #對應配置文件中{label}部分 spring.cloud.config.uri=http://服務器ip:7888/ #配置中心config-server的地址 server.port: 7889 (舉例說明:以application-dev.yml爲例,application爲name,dev爲profile,label如果你沒創建分支默認是master) (3)創建控制器 @RefreshScope @RestController public class TestController { //方式一訪問from /* @Value("${from}") private String from; @RequestMapping("/from") public String from(){ return this.from; }*/ //方式二 @Autowired private Environment env; @RequestMapping("/from") public String fromi(){ return env.getProperty("from"); } } 訪問http://localhost:7889/from 返回 git-dev-1.0 則配置中心基本功能搭建完成
Spring cloud Config:分佈式配置中心
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.