对于一些简单的项目来说,我们一般都是直接把相关配置放在单独的配置文件中,以 properties 或者 yml 的格式出现,更省事儿的方式是直接放到 application.properties 或 application.yml 中。但是这样的方式有个明显的问题,那就是,当修改了配置之后,必须重启服务,否则配置无法生效。
一、实现最简单的配置中心
最简单的配置中心,就是启动一个服务作为服务方,之后各个需要获取配置的服务作为客户端来这个服务方获取配置。
现在github中建立配置文件,我这里使用的是码云:https://gitee.com/。
新建一个仓库SpringCloudConfig,在仓库根路径下创建一个文件夹config,目录结构如下:
配置文件的内容大致如下,用于区分,略有不同。
data:
env: config-single-dev
user:
username: single-client-user
password: 1291029102
注意文件的名称不是乱起的,例如上面的 config-single-client-dev.yml 和 config-single-client-prod.yml 这两个是同一个项目的不同版本,项目名称为 config-single-client(spring.application.name配置的值), 一个对应开发版,一个对应正式版。
创建配置中心服务端
1、新建 Spring Boot 项目,引入 config-server 和 starter-web
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- spring cloud config 服务端包 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
2、配置 config 相关的配置项
bootstrap.yml 文件:
spring:
application:
name: config-single-server # 应用名称
cloud:
config:
server:
git:
uri: https://gitee.com/linhongwei/SpringCloudConfig #配置文件所在仓库
username: github 登录账号
password: github 登录密码
default-label: master #配置文件分支
search-paths: config #配置文件所在根目录
application.yml:
server:
port: 3301
3、在启动类上增加相关注解 @EnableConfigServer
@EnableConfigServer
@SpringBootApplication
public class ConfigServerApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigServerApplication.class, args);
}
}