微服务意味着要将单体应用中的业务拆分成个个子服务,每个服务的粒度相对较小因此系统中会出现大量的服务
由于每个服务都需要必要的配置信息才能运行,所以一套集中式的、动态的配置管理设施是必不可少的
Spring Cloud提供了 ConfigServer 来解决这个问题,我们每个微服务自己带着一个 application.yml,上百个配置文件的管理会导致膨胀
官方地址:https://cloud.spring.io/spring-cloud-static/spring-cloud-config/2.2.2.RELEASE/reference/html/
Spring Cloud Config为微服务架构中的微服务提供集中化的外部配置攴持,配置服务器为各个不同微服务应用的所有环境提供了一个中心化的配置
Spring Cloud Config分为服务端和客户端两部分
首先要在 Github 上创建一个 Config 仓库,来配置环境
<!-- config-server -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
server:
port: 3344
spring:
application:
name: Config-center
cloud:
config:
server:
git:
# Github 上仓库的名字
uri: https://github.com/odousnag/SpringCloudStudy.git
# 搜索目录
search-paths:
- springcloud-config
# 读取分支
label: master
# Eureka
eureka:
client:
service-url:
# 单机版
# defaultZone: http://localhost:7001/eureka/
# 集群版
defaultZone: http://eureka7001.com:7001/eureka, http://eureka7002.com:7002/eureka
@SpringBootApplication
@EnableEurekaClient
@EnableConfigServer
public class ConfigCenterMain {
public static void main(String[] args) {
SpringApplication.run(ConfigCenterMain.class,args);
}
}
常用的三种:
/{label}/{application}-{profile}.properties
master 分支:http://config3344.com:3344/master/config-xxx.yml
dev 分支:http://config3344.com:3344/dev/config-xxx.yml
/{application}/{profile}[/{label}]
http://config3344.com:3344/config-xxx.yml
/{application}-{profile}.yml
http://config3344.com:3344/config/xxx/master
<!-- spring-cloud-starter-config -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
server:
port: 3355
spring:
application:
name: Config-client
cloud:
# Config 客户端配置
config:
# 读取分支
label: master
# 配置文件名称
name: config
# 读取名称后缀
profile: dev
# 配置中心地址
uri: http://localhost:3344
# Eureka
eureka:
client:
service-url:
# 单机版
# defaultZone: http://localhost:7001/eureka/
# 集群版
defaultZone: http://eureka7001.com:7001/eureka, http://eureka7002.com:7002/eureka
@RestController
public class ClientController {
/**
* 获取application-dev的信息
*/
@Value("${config.info}")
private String configInfo;
@GetMapping("/configInfo")
public String getConfigInfo(){
return configInfo;
}
}
实现了客户端访问SpringCloudConfig通过GitHub获取配置信息
Linux运维修改GitHub上的配置文件内容做调整,刷新服务端,发现ConfigServer配置中心立刻响应,刷新客户端,发现ConfigClient客户端没有任何响应
修改客户端
<!-- spring-boot-starter-actuator -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
# 暴露监控端口
management:
endpoints:
web:
exposure:
include: "*"
curl -X POST "http://localhost:3355/actuator/refresh"
出现的问题:
现在每次更改,都要手动发动请求,这不合适,实现广播,一次通知,处处修改
下一章到消息总线会讲到
原文:https://www.cnblogs.com/hewenhao-blogs/p/14728446.html