- 本文springboot版本:
2.0.2.RELEASE
,springcloud版本:Finchley.RC1
本文使用我公開的註冊中心: http://www.wekri.com/eureka;
UI: http://www.wekri.com/eureka_ui;
配置倉庫
本文使用碼雲git庫,實際環境最好使用公司內部git服務。
demo倉庫:https://gitee.com/wekri/spring-cloud-config-repo.git
創建config server
依賴:
dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
啓動方法加上@EnableConfigServer
註解開啓配置服務器的功能
@EnableConfigServer
@EnableDiscoveryClient
@SpringBootApplication
public class ConfigurationServiceApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigurationServiceApplication.class, args);
}
}
項目配置文件:bootstrap.yml
- config.label:使用倉庫的分支
- server.git.uri:配置git倉庫地址
- server.git.search-paths:
- server.git.username:git倉庫用戶名
- server.git.password:git倉庫密碼
注意:如果使用application.properties
配置文件,{application}
不需要加單引號,
如果使用bootstrap.yml
配置文件,'{application}'
需要加上單引號。
server:
port: 8080
spring:
application:
name: config-server
cloud:
config:
label: master
server:
git:
uri: https://gitee.com/wekri/spring-cloud-config-repo.git
search-paths: '{application}'
username:
password:
eureka:
client:
serviceUrl.defaultZone: http://goma.wekri.com/eureka
instance:
hostname: localhost
instance-id: config-server
然後啓動項目,就可以訪問到配置了http://127.0.0.1:8080/config-client/dev
http請求地址和資源文件映射如下:
/{application}/{profile}[/{label}]
/{application}-{profile}.yml
/{label}/{application}-{profile}.yml
/{application}-{profile}.properties
/{label}/{application}-{profile}.properties
客戶端使用
新建一個springboot項目:configuration-client
。
依賴
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
配置文件:
server:
port: 8088
spring:
application:
name: config-client
profiles:
active: dev
cloud:
config:
profile: ${spring.profiles.active} #dev,test,staging,prod
discovery:
enabled: true # 默認false,設爲true表示使用註冊中心中的configserver配置而不自己配置configserver的uri
serviceId: config-server # 指定config server在服務發現中的serviceId,默認爲:configserver
eureka:
client:
serviceUrl.defaultZone: http://goma.wekri.com/eureka
instance:
hostname: localhost
啓動項目,可以使用environment.getProperty("env")
獲取到相應的配置。
碼雲源碼:查看
轉載聲明:商業轉載請聯繫作者獲得授權,非商業轉載請註明出處 © wekri
原文地址:http://www.wekri.com/2018/05/17/springcloud/springCloudConfig