配置中心服务
Config Server 的搭建
创建pom文件
<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.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
- 之前的微服务使用的是spring-cloud-starter-config-server,配置中心使用的是spring-cloud-config-server。
添加启动类ConfigApplication
@SpringBootApplication
@EnableConfigServer //具备 Config Server 功能
@EnableDiscoveryClient //具备 Eureka Client 功能
public class ConfigApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigApplication.class, args);
}
}
- @EnableConfigServer注解来开启config的server功能。Config Server作为配置中心的服务端。
- @EnableDiscoveryClient把Config-Server和其它微服务一样作为一个服务基本单元,注册到服务发现。(在配置文件中配置服务的名称,及Eureka服务器的地址)
- Config Server作为配置中心的服务端承担如下作用
- 拉取配置时更新Git仓库副本,保证是配置为最新;
- 支持从yml、json、properties等文件加载配置;
- 默认配置存储基于Git仓库,从而支持配置的版本管理.
application.yml配置文件
server:
port: 8080
spring:
cloud:
config:
server:
git:
uri: https://didi.git
username: user
password: pass
application:
name: config-server
#服务注册eureka地址
eureka:
client:
registerWithEureka: true
fetchRegistry: true
serviceUrl:
defaultZone: http://${eureka.address:localhost}:${eureka.port:7001}/eureka/
Config Client的搭建
创建pom文件
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
创建bootstrap.yml
server:
port: 8081
spring:
application:
name: ${config-client.name:config-client}
cloud:
config:
label: master #分支名称
name: config-client#配置文件名称
profile: dev #读取后缀名称 上诉3个综合就是 master分支上 config-client-dev.yml
failFast: true
uri: http://${config.address:localhost}:${config.port:8888}
profiles:
active: ${config.active:dev}
eureka:
client:
serviceUrl:
defaultZone: http://${eureka.address:localhost}:${eureka.port:7001}/eureka/
instance:
healthCheckUrlPath: /health
leaseRenewalIntervalInSeconds: 10 # 设置心跳的时间间隔
metadataMap:
instanceId: ${spring.application.name}:${random.value} # 在信息列表显示主机名称
preferIpAddress: true # 访问的路径是否变为IP地址
statusPageUrlPath: /info
配置文件访问规则
springcloud有的访问规则:
/{application}/{profile}[/{label}]
/{application}-{profile}.yml
/{label}/{application}-{profile}.yml
/{application}-{profile}.properties
/{label}/{application}-{profile}.properties
-
{application} :是应用名称。例如:config-client。
-
{profile} :配置文件的版本,例如dev、prod、test等。
-
{label} : git 分支,默认是 master 分支。
使用spring.profiles.active来分区配置
在Spring Boot中多环境配置文件名需要满足application-{profile}.properties的格式,其中{profile}对应环境标识需要在application.properties文件中通过spring.profiles.active属性来设置具体加载哪个配置文件,对应于{profile}值。如果没有没有指定任何profile的配置文件的话,spring boot默认会启动application-default.properties。
如:spring.profiles.active=test就会加载application-test.properties配置文件内容
链接: Spring Cloud(十四)Config 配置中心与客户端的使用与详细.
链接: Spring Cloud入门教程(八):统一配置中心(Config).