Spring Cloud Config为分布式系统中的外部化配置提供服务器端和客户端支持。 使用config组件只需要以下几步:
1. 引入依赖
在springboot项目pom文件中添加如下依赖
<!--config-server依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
<!--eureka-client依赖 (如果是使用eureka作为注册中心管理项目,不是不需要引入)-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
2. 配置application.yml文件
# 配置服务端口
server:
port: 20010
# 配置注册中心参数 (如果是使用eureka作为注册中心管理项目,不是不需要引入)
eureka:
port: 8761
instance:
hostname: localhost
client:
serviceUrl:
defaultZone: http://${eureka.instance.hostname}:${eureka.port}/eureka/
# 配置服务名称
spring:
application:
name: config
# 配置git仓库地址 账号密码(这里使用码云平台作为实验)
cloud:
config:
server:
git:
username: test
password: test
uri: https://gitee.com/test/study-project-repertory
3. 在项目启动类上添加注解
@SpringBootApplication
@EnableConfigServer
@EnableDiscoveryClient // 如果是使用eureka作为注册中心管理项目,不是不需要引入
public class ApesConfigServiceApplication {
public static void main(String[] args) {
SpringApplication.run(ApesConfigServiceApplication.class, args);
}
}
4. 测试访问远程仓库中的配置文件
- 启动项目
- 远程仓库存放配置文件eureka-service-dev.yml
server:
port: 8761
eureka:
instance:
hostname: localhost
client:
registerWithEureka: false
fetchRegistry: false
serviceUrl:
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
- 打开浏览器地址栏输入:http://localhost:20010