一、代码示例
说明:此处使用的SpringBoot版本为2.1.13.RELEASE,SpringCloud版本为Greenwich.SR5
上文介绍了SpringCloud Config的Server端,下面介绍下具体Client端
1、maven依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
</dependencies>
2、application.yml
此处注意暴露refresh节点
spring:
application:
name: config-client02
management:
endpoints:
web:
exposure:
include: refresh
3、bootstrap.yml
spring:
cloud:
config:
#git仓库中的对应配置文件名,如果找不到会读取git中的application-profile.yml(猜测applicatio-profile.properties一样)
name: config-client
profile: dev
label: master
#server服务地址
uri: http://localhost:6001
4、启动类
package org.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ConfigClient6002Application {
public static void main(String[] args) {
SpringApplication.run(ConfigClient6002Application.class,args);
}
}
4、其他java类
controller类
注意添加主键@RefreshScope,否则动态刷新不生效
package org.example.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RefreshScope
public class ConfigController {
@Value("${spring.application.name}")
private String name;
@GetMapping("/name")
public String name(){
return name;
}
}
2、测试验证
启动config-server(见上一篇)、config-client,访问http://localhost:8081/name
git仓库中config-client.yml内容
git仓库中只有config-client.yml,实际上应该是有config-client-dev.yml、config-client-test.yml等多环境的配置。
上面测试了启动时读取配置文件,下面测试下动态修改配置文件。
我们直接在github上修改下配置文件
再次访问http://localhost:8081/name
刚刚修改的配置并没有生效。我们需要以post方式访问下http://localhost:8081/actuator/refresh,此处我们用postman工具进行post方式访问
再次访问http://localhost:8081/name
这样我们就做到了动态修改配置文件,不需要重启服务。
github:
https://github.com/panli1988/cloud01
https://github.com/panli1988/cloud02
参考:
https://blog.csdn.net/forezp/article/details/70148833
http://www.itmuch.com/spring-cloud/spring-cloud-index/
还有尚硅谷周阳老师的视频