所讲代码仓库地址:https://gitee.com/raoyuuuu/springcloud-demo
前言:
需要了解配置Git、有Git远程仓库,比如GitHub、码云Gitee,这边用的是码云
步骤:
- gitee建立仓库
- 创建配置
- 创建config-server,从gitee拉取配置
- 创建config-client,模拟从config-server拿到gitee中的配置信息
- 改造provider,也从gitee中拿到配置信息
参考
玩转Spring Cloud之配置中心(config server &config client)
测试用的application.yml,配置信息如下
spring:
profiles:
active: dev
---
spring:
profiles: dev
application:
name: springcloud-config-dev
---
spring:
profiles: test
application:
name: springcloud-config-test
3、 创建config-server,从gitee拉取配置
3.1、创建spring boot项目
3.2、依赖
3.3、application配置4.0.0 com.example cloud-parent 0.0.1-SNAPSHOT com.example cloud-config-server 0.0.1-SNAPSHOT cloud-config-server Demo project for Spring Boot 1.8 org.springframework.boot spring-boot-starter org.springframework.boot spring-boot-starter-test test org.springframework.cloud spring-cloud-config-server org.springframework.boot spring-boot-maven-plugin
server:
port: 8003
spring:
application:
name: cloud-config-server
profiles:
active: git
cloud:
config:
server:
git:
uri: https://gitee.com/xxxxxx/cloud-config.git
search-paths: /**
# 有的这边可能还需要配置访问gitee的username和password
3.4、CloudConfigServerApplication配置
@SpringBootApplication
@EnableConfigServer//注解开启
public class CloudConfigServerApplication {
public static void main(String[] args) {
SpringApplication.run(CloudConfigServerApplication.class, args);
}
}
启动项目,访问 http://localhost:8003/application-test.yml
可以看到已经成功获取到远程仓库中的配置信息了,接下来可以进行客户端client的测试
spring:
profiles:
active: dev
---
server:
port: 8004
spring:
profiles: dev
application:
name: springcloud-config-dev
---
server:
port: 8005
spring:
profiles: test
application:
name: springcloud-config-test
4.2、创建spring boot项目
4.3、依赖
4.0.0 com.example cloud-parent 0.0.1-SNAPSHOT com.example cloud-config-client 0.0.1-SNAPSHOT cloud-config-client Demo project for Spring Boot 1.8 org.springframework.boot spring-boot-starter-web org.springframework.cloud spring-cloud-starter-config org.springframework.cloud spring-cloud-starter-bootstrap org.springframework.boot spring-boot-starter-test test org.springframework.boot spring-boot-maven-plugin
为什么要加bootstrap依赖?
https://www.mmbyte.com/article/73387.html
空
4.5、bootstrap配置spring:
cloud:
config:
name: springcloud-config-client
profile: test
label: master
uri: http://localhost:8003 # config-server的地址,这里是本地启动的地址
以上配置:通过uri找到config-server,通过config-server找到git中master节点-文件为springcloud-config-client-test
4.6、TestController@RestController
public class TestController {
@Value("${spring.application.name}")
private String applicationName;
@Value("${server.port}")
private String port;
@RequestMapping("config")
public String getConfig(){
return "applicationName:"+applicationName+"----------port:"+port;
}
}
启动server和client
访问 http://localhost:8005/config ,因为此时获取的是test下的配置,此时server.port=8005
修改bootstrap配置 profile: dev
访问 http://localhost:8004/config ,因为此时获取的是dev下的配置,此时server.port=8004
通过上面client测试通过server获取配置成功,可以依葫芦画瓢进行下一步 改造provider,也从gitee中拿到配置信息了



