SpringCloud学习-config使用
创建git版本项目用于管理配置文件

注意文件名的格式
config-server-dev 分别为config-server为application名称,dev为环境区分profile
文件具体内容如下
vsersion=22.33
message=hello world
创建配置中心项目
1.添加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
2.修改application.properties
spring.cloud.config.server.git.uri=对应的git地址-http地址
spring.cloud.config.label=master
spring.application.name=config-server
server.port=1006
spring.cloud.config.server.git.username=git账号
spring.cloud.config.server.git.password=git密码
3.启动服务,访问http://localhost:1006/config-server/test,可以直接看到git中配置的键值对
{
"name": "config-server",
"profiles": [
"test"
],
"label": null,
"version": "0492619e7238e1e12e8c6e05b382074c785e7eae",
"state": null,
"propertySources": [
{
"name": "http://gitlab.wonhigh.cn/budget-project/spring-cloud-config.git/config-server-test.properties",
"source": {
"vsersion": "22.33",
"message": "hello world"
}
}
]
}
创建配置中心客户端项目
1.导入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
2.新建bootstrap.properties文件,不是application.properties对象
spring.application.name=config-server ##注意这个名字必须和配置中心的名字一致
spring.cloud.config.label=master
spring.cloud.config.profile=dev
spring.cloud.config.uri= http://localhost:1006/
3.新建controller类直接注入属性
@RestController
public class DemoController {
@Value("${vsersion}")
private String version;
@Value("${message}")
private String message;
@GetMapping("/test")
public String demo(){
return "Hello,"+version+","+message;
}
}
4.启动应用,访问地址http://localhost:1008/test

配置文件半自动刷新
1.增加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
2.修改config的配置
在bootstrap.properties文件增加以下配置
management.endpoints.enabled-by-default=true
management.endpoint.health.show-details=always
management.endpoints.web.exposure.include=*
management.endpoints.web.base-path=/actuator
上面的配置建立在springboot2.x的基础上,其他低版本的配置不一样
3.需要自动刷新注入值的类上面增加注解@RefreshScope
@RestController
@RefreshScope
public class DemoController {
@Value("${vsersion}")
private String version;
@Value("${message}")
private String message;
@GetMapping("/test")
public String demo(){
return "Hello,"+version+","+message;
}
}
4.修改git配置并提交,手动请求刷新地址http://localhost:1008/actuator/refresh,注意是post请求,执行之后的结果
[
"config.client.version",
"vsersion"
]
如果返回的数组不为空,则表示配置已更新,并且需要对应注入的属性值也完成了刷新
本文详细介绍如何使用SpringCloud Config搭建配置中心,包括创建Git版本项目管理配置文件、配置中心项目及客户端项目的设置,实现配置文件的动态刷新,适合于微服务架构下统一管理各服务配置。

被折叠的 条评论
为什么被折叠?



