分布式系统面临的问题—配置问题
微服务意味着要将单体应用中的业务拆分成一个个子服务,每个服务的粒度相对较小,因此系统中会出现大量的服务。由于每个服务都需要必要的配置信息才能运行,所以一套集中式的、动态的配置管理设施是必不可少的。
是什么?
SpringCloud Config为微服务架构中的微服务提供集中化的外部配置支持,配置服务器为各个不同微服务应用的所有环境提供一个中心化的外部配置。
能干嘛?
- 集中管理配置文件
- 不同环境不同配置,动态化的配置更新,分环境部署,比如:dev、test、prod、beta、release
- 运行期间动态调整配置,不需要在每个服务部署的机器上编写配置文件,服务会向配置中心统一拉取配置自己的信息
- 当配置发生变动时,服务不需要重启即可感知到配置的变化并应用新的配置
- 将配置信息以REST接口的形式暴露
怎么玩?
SpringCloud Config分为服务端和客户端两部分。
- 服务端也称为分布式配置中心,它是一个独立的微服务应用,用来连接配置服务器并为客户端提供获取配置信息,加密、解密信息等访问接口。
- 客户端则是通过指定的配置中心来管理应用资源,以及业务相关的配置内容,并在启动的时候从配置中心获取和加载配置信息。
- 配置服务器默认采用git来存储配置信息,这样就有助于对环境配置进行版本管理,并且可以通过git客户端工具来方便的管理和访问配置内容。
Config服务端配置与测试
因为我们在使用Springcloud Config的时候是要从github上拉取数据,因此你首先要有个github账号,并且建立一个Repository,然后再获取这个Repository的git地址
如:https://github.com/coderzpw1/springcloud-config.git
关于git和github的知识这里我不做赘述
1. 添加pom依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
2. application配置
server:
port: 3344
spring:
application:
name: cloud-config-center # 注册进Eureka服务器的微服务名
cloud:
config:
server:
git:
uri: https://github.com/coderzpw1/springcloud-config.git #Github上面的git仓库的名字
search-paths:
- springcloud-config # 搜索的路径
label: main # 读取分支
# 服务注册到eureka地址
eureka:
client:
service-url:
defaultZone: http://localhost:7001/eureka
3. 主方法
4. 启动并测试
Config客户端配置与测试
1. pom依赖
<!--config客户端-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
2. bootstrap配置文件(这里我们不用application)
server:
port: 3355
spring:
application:
name: config-client
cloud:
# Config客户端配置
config:
label: main # 分支名称
name: config # 配置文件名称
profile: test # 读取后缀名称
uri: http://localhost:3344 # 配置中心地址
# 上述四个参数进行拼接 uri+/+label+/+name+'-'+profile -> 读取http://localhost/main/config-test的信息作为config
eureka:
client:
service-url:
defaultZone: http://localhost:7001/eureka
# 暴露监控的接口
management:
endpoints:
web:
exposure:
include: "*"
3. 主方法
4. 测试:对外暴露信息接口
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RefreshScope // 具备刷新的能力
public class ConfigClientController {
@Value("${config.info}")
private String configInfo;
@GetMapping("/configInfo")
public String getConfigInfo (){
return configInfo;
}
}
测试: