spring cloud config

一、config-server
依赖的包:
1 2 3 4 5 6 7 8
| <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>
|
在这里需要明白的是我们的依赖包,不要使用 spring-cloud-dependencies和 spring-boot-dependencies在子项目中,你如果再父项目中这样弄的话,你的子项目就可以不添加版本号也可以使用相应的依赖;
启动类:
1 2 3 4 5 6 7 8 9 10 11 12 13
| package com.saxon.springcloud;
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.config.server.EnableConfigServer;
@SpringBootApplication @EnableConfigServer public class SpringCloudConfig { public static void main (String[] args) { SpringApplication.run (SpringCloudConfig.class, args); } }
|
配置文件:
1 2 3 4 5 6 7 8
| server: port: 3344 spring: cloud: config: server: git: uri: https://gitee.com/Saxon_MO/springcloud.git
|
这里需要注意的是uri是http的地址不是ssh地址;就是你配置文件的地址
放在git上面的配置文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| spring: profiles: active: test --- server: port: 8081 spring: profiles: dev
--- server: port: 8083 spring: profiles: test
|
配置文件所在地址:
1 2 3 4 5
| /{application}/{profile}[/{label}] /{application}-{profile}.yml /{label}/{application}-{profile}.yml /{application}-{profile}.properties /{label}/{application}-{profile}.properties
|
使用这个mapping,获得配置文件
例如使用:http://localhost:3344/application-dev.yaml
获得下图的信息:

二、config-client
依赖:
1 2 3 4 5 6 7 8
| <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-config-client</artifactId> </dependency>
|
客户端,spring cloud config是基于CS架构的配置获得
配置文件:
bootstrap.yaml(系统级配置)
1 2 3 4 5 6 7
| spring: cloud: config: uri: http://localhost:3344 profile: dev label: master name: client-config
|
application.yaml
1 2 3
| spring: application: name: saxon
|
启动类:
1 2 3 4 5 6 7 8 9 10 11 12
| package com.saxon.springcloud;
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication public class SpringCloud_Config_client { public static void main (String[] args) { SpringApplication.run (SpringCloud_Config_client.class,args); } }
|
为了让我们清晰的看出是否获得配置文件,我们写一个controller来查看我们的信息
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| package com.saxon.springcloud.controller;
import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController;
@RestController public class ConfigController { @Value ("${server.port}") private String port;
@GetMapping ("/getConfig") public String getConfig () { return port; } }
|
@Value (“${server.port}”),可以自动填充我们获得的配置文件信息,里面就是属性
可以通过这个把我们的配置全部提交到远程的GIT仓库,然后使用这个功能获得配置就可以了,更方便运维和其他的使用;
获得config远程的一定要使用==bootstrap.yaml==,不然会有错