-
SpringCloud Config为什么会出现
微服务意味着要将单体应用中的业务拆分成一个个子服务,每个服务的粒度相对较小,因此系统中会出现大量的服务.由于每个服务都需要必要的配置信息(比如application.yml等配置文件)才能运行,所以一套集中式的动态的配置管理设施必不可少.
SpringCloud提供了ConfigServer来解决这个问题. -
SpringCloud Config是什么
SpringCloud Config为微服务架构中的微服务提供集中化的外部配置支持,配置服务器为各个不同的微服务应用的所有环境提供了一个中心化的外部配置.
-
SpringCloud Config怎么做
-
SpringCloud Config能做什么
-
SpringCloud Config配置
- application.yml
server:
port: 3344
spring:
application:
name: cloud-config-center # 注册进Eureka服务器的微服务名
cloud:
config:
server:
# 通过地址+仓库+分支唯一确定
git:
# 地址
uri: https://github.com/zzyybs/springcloud-config.git
# 搜索目录(仓库)
search-paths:
- springcloud-config
# 分支
label: master
eureka:
client:
# register-with-eureka: true
service-url:
defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka #集群版
- 主启动文件ConfigCenterMain3344.java
package com.atguigu.springcloud;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.config.server.EnableConfigServer;
@SpringBootApplication
// 激活配置中心
@EnableConfigServer
@Slf4j
public class ConfigCenterMain3344 {
public static void main(String[] args) {
SpringApplication.run(ConfigCenterMain3344.class, args);
}
}
- 若修改host文件,添加如下语句,完成域名和ip地址的映射.则可以通过http://config-3344.com:3344/dev/config-prod.yml访问,否则要通过http://localhost:3344/dev/config-prod.yml访问.
127.0.0.1 config-3344.com
- BootstrapContext上下文
bootstrap.yml是大环境的配置文件,而application.yml是本微服务的配置文件,两个配置文件内容合并才是总的配置.
bootstrap.yml配置文件:
server:
port: 3355
spring:
application:
name: config-client
cloud:
# config客户端配置
config:
# 这三个都对应着config配置文件配置规则中的名称
# master分支傻姑娘的config-dev.yml的配置文件读取是http:config-3344.com/master/config-dev.yml
label: master # 分支名称
name: config # 配置文件名称
profile: dev # 读取后缀名称
# config client去config server找,config server去github找
uri: http://localhost:3344 # 配置中心地址
eureka:
client:
register-with-eureka: true
service-url:
defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka #集群版
- 分布式配置的动态刷新问题
背景:
当从github上将配置文件更改后,从config server获取的是最新的结果,但是从config client并不能获取新结果,需要重启微服务.
解决办法: 动态刷新
- pom.yml文件中引入actuator监控
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
- 修改yml,暴露监控端口
# 暴露监控端点
management:
endpoints:
web:
exposure:
include: "*"
- @RefreshScope业务类controller添加注解@RefreshScope,用以刷新获取config server中的配置文件
- 发送Post请求刷新config client端口.虽然每次修改github上的配置都需要发送post请求,但是比起重启微服务来说简便一些.
curl -X POST "http:localhost:3355/actuator/refresh"