参考了尚硅谷的spring cloud课程,做了一些笔记,完整代码:https://github.com/yao09605/mscloud
准备一个github仓库作为存放配置文件的地方
远程的config文件使用官网约定的命名方式
有以下几种约定的文件格式:
/{application}/{profile}[/{label}]
/{application}-{profile}.yml
/{label}/{application}-{profile}.yml
/{application}-{profile}.properties
/{label}/{application}-{profile}.properties
其中:
application
对应spring.config.name
(应用名)
profile
对应环境名spring.config.profile
(环境名)
label
对应spring.config.label
(github分支)
举个例子:
我们上传一个config-dev.yml
到github上的master
分支上
读取这个配置的应用应该有如下配置:
spring:
application:
name: config-client
cloud:
config:
label: master
name: config
profile: dev
uri: http://localhost:3344
添加如下依赖
<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>
server:
port: 3344
spring:
application:
name: cloud-config-center
cloud:
config:
server:
git:
uri: https://github.com/yao09605/springcloud-config.git #库地址
search-paths:
- springcloud-config
label: master #分支
eureka: #服务注册中心
client:
service-url:
defaultZone: http://localhost:7001/eureka
@SpringBootApplication
@EnableConfigServer
public class ConfigCenterMain3344 {
public static void main(String[] args) {
SpringApplication.run(ConfigCenterMain3344.class,args);
}
}
测试:http://localhost:3344/master/config-dev.yml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</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>
bootstrap.yml优先级高于application.yml,所以这里用bootstrap,因为真正的配置在配置中心
server:
port: 3355
spring:
application:
name: config-client
cloud:
config: #去哪里读配置,去配置中心读
label: master
name: config
profile: dev
uri: http://localhost:3344
eureka:
client:
service-url:
defaultZone: http://eureka7001.com:7001/eureka
management: #暴露端口用于实时刷新
endpoints:
web:
exposure:
include: "*"
@SpringBootApplication
public class ConfigClientMain3355 {
public static void main(String[] args) {
SpringApplication.run(ConfigClientMain3355.class,args);
}
}
@RefreshScope //用于刷新配置
@RestController
public class ConfigClientController {
@Value("${config.info}") //注入远程配置文件中的字段,配置文件中没有这个字段的话就启动不起来了
private String configInfo;
@GetMapping("/configInfo")
public String getConfigInfo(){
return configInfo;
}
}
访问:http://localhost:3355/configInfo