springcloud学习记录-config
在分布式系统中,由于服务数量巨多,而每个服务都需要必要的配置信息才能运行,为了方便服务配置文件统一管理,实时更新,所以需要分布式配置中心组件,spring提供了Config组件来解决。
SpringCloud Config为微服务架构中的服务提供集中化的外部配置支持,config-server(config服务端)为各个不同的微服务应用的所有环境提供一个中心化的外部配置,其配置服务放在远程Git仓库(GitHub)中(也可使用SVN或本地文件或数据库)。
SpringCloud Config分为服务端和客户端:
(1)config-server:服务端也称为分布式配置中心,它是一个独立的微服务应用,用于连接配置服务器为客户端(config-client)提供获取配置信息的访问接口。
(2)config-client:客户端是通过制定的配置中心来管理应用资源,以及与业务相关的配置内容,并在启动时从配置中心获取和加载配置信息,配置服务器默认使用git来存储配置信息,这样有助于对环境配置进行版本管理,并且通过git客户端工具来方便管理和访问配置内容。
SpringCloud Config的功能:
(1)集中管理配置文件;
(2)不同环境不同配置,动态化更新配置,分环境部署,如dev/test/prod/beta/release;
(3)运行期间动态调整配置,不需在每个服务器及其上编写配置文件,服务会向配置中心统一拉取配置自己的信息;
(4)当配置发生变动时,服务不需重启即可感知到配置的变化并应用新的配置;
项目搭建
先看config-server:
1.新建module:service_config_server
pom.xml配置文件
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
2.在启动类上添加:@EnableConfigServer
@SpringBootApplication
@EnableConfigServer
public class ServiceConfigServerApplication {
public static void main(String[] args) {
SpringApplication.run(ServiceConfigServerApplication.class, args);
}
}
3.yml配置文件:bootstrap.yml
server:
port: 9001
spring:
application:
name: config-server
cloud:
config:
# label: master
server:
git:
uri: https://github.com/ayouyyyyyy/springcloud #指向的是配置文件所在的git项目uri
searchPaths: '{application}' #远程仓库的文件夹为对应的服务名
# search-paths: config-repo #指定的是匹配查询的路径名
username:
password:
不需要注册到Eureka中
再看一下config-client:‘
1.新建module:service_config_client
pom.xml:
<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.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
2.yml配置
spring:
application:
name: config-client #指定了配置文件的应用名
cloud:
config:
uri: http://localhost:9001/ #Config server的uri
profile: dev #指定的环境
label: master #指定分支
server:
port: 7001
management: #如果要用到动态刷新
endpoints:
web:
exposure:
include: "bus-refresh" #修改github上的配置文件之后,打开postman,请求方式是post,地址是http:,这个端口号是configServer的。//localhost:9001/actuator/bus-refresh
3.在GitHub上新建对应的yml文件
根据命名规则进行命名,文件夹名称是项目yml中配置的name。
4.在controller中进行测试,看看能不能读到GitHubyml文件中的参数。
注意开启:远程自动拉取@RefreshScope
@RestController
@RefreshScope //开启config远程配置自动拉取更新,是为了可以动态刷新这个Controller的Bean
public class ConfigClientController {
@Value("${from}")
private String fromValue;
/**
* 返回配置文件中的值
*/
@GetMapping("/from")
public String returnFormValue(){
return fromValue;
}
}
测试,访问controller时能够获取到GitHub上的参数值。