本篇主要整理了spring cloud config的使用,包含本地模式以及远端模式。
项目工程包含一个eurekaServer注册中心,一个eurekaClient,一个Spring Cloud Config配置中心。
首先是pom文件,需要添加spring cloud config的依赖支持,同时也将spring cloud config作为eureka Client注册到eureka上面,也要添加eureka相关依赖。
具体pom文件如下:
4.0.0 org.example configserver 1.0-SNAPSHOT org.springframework.boot spring-boot-starter-parent 2.2.10.RELEASE 1.8 1.8 UTF-8 org.springframework.cloud spring-cloud-dependencies Hoxton.SR12 pom import org.projectlombok lombok junit junit test org.springframework.boot spring-boot-starter-test test org.springframework.cloud spring-cloud-starter-netflix-eureka-client org.springframework.cloud spring-cloud-config-server org.springframework.boot spring-boot-maven-plugin
第二步,需要在启动类上面添加一个@EnableConfigServer注解
@SpringBootApplication
@EnableDiscoveryClient
@EnableConfigServer
public class ConfigServerApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigServerApplication.class, args);
}
}
第三步,添加相关配置项
这边分为两种模式,一种是本地模式,就是配置文件存放在本地目录,一种是远端模式,是配置文件存放在服务器上面。
-
本地模式
本地模式需要设置spring.profiles.active属性为native,同时设置spring cloud config指定存放配置文件的目录。
spring: application: name: config-server profiles: active: native # 本地模式 cloud: config: server: native: search-locations: classpath:/cloud-repo # 指定目录方式 server: port: 8888我这边在项目的resources目录下新建了一个cloud-repo目录,用于存储读取的配置文件信息。
config.properties配置文件:name=yuanzhihao
启动项目,可以通过浏览器输入http://{ip}:{port}/{application}-{profile}.properties去访问到我们配置的文件信息。
application对应的就是配置文件的名称,profile对应的是配置文件的版本信息,我们这边开发的时候会根据profile后缀来区分不同的开发环境的配置信息,如果配置文件不区分版本的话,通过验证,profile随便填什么都是访问的自己。 -
远端模式
远端模式支持通过配置代码仓库的地址以及账号和密码来读取存放在代码服务器上面的配置文件。
配置文件如下:spring: application: name: config-server cloud: config: server: git: uri: http://localhost:5001/root/cloud-repo.git # 指定代码仓地址 username: root # 用户名 password: 12345678 # 密码 default-label: main # 仓库分支 search-paths: cloud-repo @RestController @Slf4j public class HelloController { @Value("${name}") private String name; @GetMapping("/hello") public String hello() { return "Hello " + name; } }启动client1,通过浏览器访问该接口,可以获取到name的值,读取成功!
项目源码参考
源码地址:https://github.com/yzh19961031/SpringCloudDemo



