前言
在分布式系统中,由于服务数量巨多,为了方便服务配置文件统一管理,实时更新,所以需要分布式配置中心组件。
在Spring Cloud中,有分布式配置中心组件spring cloud config ,它支持配置服务放在配置服务的内存中(即本地),也支持放在远程Git仓库中。在spring cloud config 组件中,分两个角色,一是config server,二是config client。
- 新建springboot工程,添加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
- 在启动类中添加注解
@SpringBootApplication
@EnableDiscoveryClient
@EnableConfigServer
public class ConfigServiceApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigServiceApplication.class, args);
}
}
- 配置application.yml文件(关键)
spring:
application:
name: config-service
cloud:
config:
server:
git:
uri: https://github.com/******/config-repo
username: ******
password: ******
basedir: D:\Documents\GitHub\config-repo
eureka:
client:
service-url:
default-zone: http://locahost:8761/eureka/
至此,服务端配置完成,接下来配置客户端:
- 引入pom依赖
org.springframework.cloud
spring-cloud-config-client
- application.yml改为bootstrap.yml
eureka:
client:
service-url:
default-zone: http://localhost:8761/eureka/
spring:
cloud:
config:
discovery:
# 开启服务配置中心发现
enabled: true
# 设置服务配置中心名称
service-id: config-service
# 设置环境
profile: dev
application:
# 设置客户端服务名称
name: product
客户端配置完成,经过测试可以正常获取git中提交的配置文件,下一篇讲解spring cloud config的热部署