SpringCloud极简入门(十)配置中心(Spring Cl
作者:陈刚,叩丁狼高级讲师。原创文章,转载请注明出处。
一.简述
配置中心(Spring Cloud Config)顾名思义,他是Spring Cloud团队为微服务应用提供集中化的外部配置支持,它分为服务端和客户端两个部分。服务端是一个微服务应用,它可以从本地仓库读取配置文件,也可以从远程git仓库读取配置文件,从而为客户端提供配置信息,加密/解密信息等访问接口,而客户端则是微服务架构中的各个微服务应用,他们可以指定配置中心来管理本身的应用资源与相关配置内容,并在启动的时候加载配置信息。如图:
image.png
二.配置git
本案例以码云为例,首先我们需要创建一个远程仓库,创库中创建两个配置文件 config-client-dev.properties,config-client-test.properties表示两套配置环境 dev和test ,如下
image.png
内容分别为:
notify=You are successful for dev
server.port=7777
notify=You are successful for test
server.port=9999
这里分别指定了一个两个配置环境的服务器端口和一个自定义的配置参数 notify .
此仓库地址为:“https://gitee.com/baidu11.com/springcloud-config.git”
三.创建配置服务
1.搭建SpringBoot应用 Config-Server ,pom 引入 spring-cloud-config-server 配置依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<spring-cloud.version>Finchley.M9</spring-cloud.version>
</properties>
<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>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
2.主程序类打上 @EnableConfigServer 标签开启配置服务
/**
* @EnableConfigServer :开启配置服务
*/
@SpringBootApplication
@EnableConfigServer
@PropertySource("classpath:application.properties")
public class ConfigServerApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigServerApplication.class, args);
}
}
3.修改 application.properties 配置
spring.application.name=config-server
server.port=5555
#配置git仓库地址
spring.cloud.config.server.git.uri=https://gitee.com/baidu11.com/springcloud-config.git
#主分支
spring.cloud.config.label=master
#访问git仓库的用户名
#spring.cloud.config.server.git.username=
#访问git仓库的用户密码
#spring.cloud.config.server.git.password=
上面配置了服务器名,服务端口和最重要的一个配置 spring.cloud.config.server.git.uri指向了我们刚才创建的git仓库地址,ConfigServer会从该地址中去找配置文件 ,而如果git仓库访问权限是共有的,无需配置用户名和密码
4.启动服务,测试:输入地址:http://localhost:5555/config-client-dev.properties ,您可看到:
image.png
image.png
通过该请求,配置服务已经从指定的git仓库中去找到了 config-client-dev.properties命名的配置文件。
![](https://img.haomeiwen.com/i807144/25889b73cfa93773.jpeg)