springcloud~配置(zhi)中心的使用
配(pei)置(zhi)中心(xin)作為springcloud里最底層的(de)框架,所(suo)(suo)發揮的(de)意思是舉足輕重(zhong)的(de),所(suo)(suo)以(yi)(yi)的(de)組(zu)件的(de)配(pei)置(zhi)信息(xi)都可(ke)以(yi)(yi)通(tong)過springcloud config來管理,它會把配(pei)置(zhi)信息(xi)分(fen)布(bu)式的(de)存儲(chu)到(dao)(dao)git上,所(suo)(suo)以(yi)(yi)信息(xi)安全這塊可(ke)以(yi)(yi)放(fang)心(xin),其它應用程(cheng)序在更新配(pei)置(zhi)時,直(zhi)接在遠(yuan)程(cheng)GIT倉(cang)庫(ku)更新即可(ke),而且更新后自動(dong)同步到(dao)(dao)對(dui)應的(de)程(cheng)序里,不需要(yao)重(zhong)啟這個應用程(cheng)序!
配置服務-服務端,最底層應用
依賴包
dependencies { compile('org.springframework.cloud:spring-cloud-config-server', 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-server' ) testCompile('org.springframework.boot:spring-boot-starter-test') }
配置項
server: port: 8200 spring: application: name: lind-config-server cloud: config: server: git: uri: https://github.com/bfyxzls/lindconfig.repo.git/ search-paths: config-repo username: bfyxzls@sina.com password: 纟 eureka: instance: prefer-ip-address: true instance-id: ${spring.application.name}:${server.port} client: serviceUrl: defaultZone: http://localhost:8761/eureka/
啟(qi)動代(dai)碼
@EnableDiscoveryClient @EnableConfigServer @SpringBootApplication class Application { public static void main(String[] args) { // demo //localhost://8200/email-svt.yml SpringApplication.run(Application.class, args); } }
在github上添(tian)加對應的倉庫(ku),客戶端的配(pei)置文(wen)件將會(hui)同(tong)步到GIT倉庫(ku),建議配(pei)置文(wen)件采用yml語法!
/****************************************************************************************
* 配置服務的路勁規則:
*
* /{application}/{profile}[/{label}]
* /{application}-{profile}.yml
* /{label}/{application}-{profile}.yml
* /{application}-{profile}.properties
* /{label}/{application}-{profile}.properties
****************************************************************************************/
倉儲如(ru)圖:

查看配置中心服務端是(shi)否正常
訪問://localhost:8200/email-svt.yml

配置中心-客戶端,遍及在所有應用中
依賴包
dependencies { compile('org.springframework.boot:spring-boot-starter-web', 'org.springframework.cloud:spring-cloud-starter-config', 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-server') testCompile('org.springframework.boot:spring-boot-starter-test') }
配置(zhi)項
spring: application: name: email #注(zhu)意這里的email是指配(pei)置中心git倉庫里yml文(wen)件的application的部分 cloud: config: uri: http://localhost:8200 server: port: 8300 eureka: client: serviceUrl: defaultZone: http://localhost:8761/eureka/
啟動項(xiang)
@EnableEurekaClient @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
我們可以在客(ke)戶(hu)端使(shi)用$Value注(zhu)解完成配置文(wen)件(jian)的讀取(qu)!
@RestController public class HomeController { @Value("${server.port}") // git配置文件里(li)的(de)key String serverPort; @RequestMapping("/") public String index() { return "serverPort=" + serverPort; } }
結果如圖:

感謝各位的閱讀!