Spring Cloud Config?
Spring Cloud Config 是一种用来动态获取Git、SVN、本地的配置文件的一种工具
两个组件组成:
Config Server 管理配置
Config Client 获取配置
Spring Cloud Config Server:
pom.xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
Application.java
@EnableConfigServer
public class Application {
......
application.yml
spring:
application:
name: config
cloud:
config:
server:
git:
uri: https://gitee.com/SpringCloud/config-repo
username: username
password: password
# 设置配置文件本地存放路径
basedir: /Users/admin/code/basedir
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
测试访问:
/{name}-{profiles}.yml
/{label}/{name}-{profiles}.yml
name 服务名
profiles 环境
label 分支
Spring Cloud Config Client:
pom.xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-client</artifactId>
</dependency>
bootstrap.yml
spring:
cloud:
config:
discovery:
enabled: true
service-id: CONFIG
profile: dev
application:
name: order
注意:如果Eureka端口被修改,则eureka.client的配置不能放到git远端
eureka:
client:
service-url:
defaultZone: http://localhost:8762/eureka/
Spring Cloud Bus 实现自动更新配置
Server端和Client端的pom.xml加上
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bus-amqp</artifactId>
</dependency>
测试启动成功后在RabbitMQ上查看bus是否创建了消息队列
http://localhost:15672/#queues
暴露bus-refresh接口,在Server端application.yml加上
management:
endpoints:
web:
expose: "*"
在需要刷新配置的地方加上注解@RefreshScope,例如:
@Data
@Component
@ConfigurationProperties("girl")
@RefreshScope
public class GirlConfig {
private String name;
private String age;
}
测试发送post请求刷新配置:
curl -v -X POST "http://localhost:8080/actuator/bus-refresh"
集成WebHooks实现动态刷新配置
开源中国gitee的WebHooks目前和SpringCloud Config组件不兼容,所以只能用github的WebHooks
url必须为外网地址,可以使用netapp.cn获取免费隧道
SpringCloud Config组件提供了用于WebHooks的路由叫做monitor