27-springcloud-config-3-构建 Spring cloud config 配置中心服务端

发布时间 2023-04-14 09:46:14作者: companion

构建一个 spring cloud config 配置中心按照如下方式进行:

1、创建一个普通的 Spring Boot 项目

2、在 pom.xml 文件中添加如下依赖:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-config-server</artifactId>
</dependency>

3、在入口类,也就是 main 方法的类上添加注解 @EnableConfigServer

@EnableConfigServer //开启spring cloud config配置中心支持
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

4、在application.properties中配置一下git仓库信息,此处我们使用gitee  (也可以使用码云GitHub,由于网络比较慢,可能连接失败) ,

首先我的gitee上有一个名为 springcloud的项目,我们的配置文件如下:

server.port=8888

spring.application.name=34-springcloud-service-config

spring.cloud.config.server.git.uri=https://gitee.com/verycat/springcloud.git
spring.cloud.config.server.git.search-paths=config-center
spring.cloud.config.server.git.username=verycat
spring.cloud.config.server.git.password=123456.

其中:

1.uri 表示配置中心所在仓库的位置

2.search-paths 表示仓库下的子目录

3.username 表示你的 GitHub 用户名

4.password 表示你的 GitHub 密码

至此我们的配置中心服务端就创建好了。

此时启动我们的配置中心,通过/{application}/{profile}/{label}就能访问到我们

的配置文件了;

配置文件的映射规则:

/{application}/{profile}[/{label}]

http://localhost:8888/application/dev/master 

 

/{application}-{profile}.properties

http://localhost:8888/application-dev.properties 

 

/{label}/{application}-{profile}.properties

http://localhost:8888/master/application-dev.properties 

 

/{application}-{profile}.yml

http://localhost:8888/application-dev.yml 

 

 

/{label}/{application}-{profile}.yml

http://localhost:8888/master/application-dev.yml 

其中:

{application} 表示配置文件的名字,对应的配置文件即 application

{profile} 表示环境,有 devtestonline 及默认,

{label} 表示分支,默认我们放在 master 分支上,

通过浏览器上访问 http://localhost:8888/application/dev/master

返回的 JSON 格式的数据:

name 表示配置文件名 application 部分,

profiles 表示环境部分,

label 表示分支,

version 表示 GitHub 上提交时产生的版本号,

同时当我们访问成功后,在控制台会打印了相关的日志信息;

当访问成功后配置中心会通过 git clone 命令将远程配置文件在本地也保存一

份,以确保在 git 仓库故障时我们的应用还可以继续正常使用。