ConfigServer配置管理器本质上讲github上存储的配置文件,下载下来传递给其他客户端作为启动时的配置文件,对于大型的项目来说,具有很大的优势,对各类配置文件方便管理。下面主要分两步:
配置服务器搭建
依赖文件
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
添加启动类注解
package com.example.config_server;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.config.server.EnableConfigServer;
@SpringBootApplication
@EnableDiscoveryClient
@EnableConfigServer
public class ConfigServerApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigServerApplication.class, args);
}
}
配置文件
server:
port: 8088
spring:
application:
name: configServer
cloud:
config:
server:
git:
# 仓库地址
uri: https://github.com/GISHanBo/springConfig.git
# search-paths: my-sample-config git下的文件夹路径
# username: 私有项目用户名
# password:私有项目密码
# 启动程序后的测试地址 http://127.0.0.1:8088/master/application-dev.properties
这样服务器端就搭建完成了,运行服务器端程序,浏览器访问http://127.0.0.1:8088/master/application-dev.properties,mater为分支名,后面的为git里对应的配置文件名称,浏览器里就可以看到放在git里的配置文件信息
客户端使用
添加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
配置文件一定是bootstrap.properties,不能是application.propertie。否则配置文件后面会有冲突
#配置服务器地址
spring.cloud.config.uri=http://localhost:8088/
#文件名-之前内容
spring.cloud.config.name=application\
#文件名-之后点之前内容
spring.cloud.config.profile=consumer
#分支名称
spring.cloud.config.label=master
Contoller自己根据自己的需求编写就可以了,启动这个客户端,用配置github文件的接口和controller路径测试请求是不是能正常运行,最终测试正常,而且github中的配置文件修改端口后,重新运行,在新的接口正常运行
我的github项目配置如下图