前言

曾经4天没有更新了,怎么说呢,就很忙,很忙,很忙。次要还是毕业以及从一个城市到另外一个城市的事件,这段时间尽最大可能放弃2,3天一更,最晚不超过4,5天一更。

随着模块的增多,会呈现配置文件繁冗的通病,每次都要关上好多层目录能力找到配置文件,SpringCloud中的Config组件就是为了解决这个问题,通过简略的配置就能实现配置文件的对立治理。

Config服务端

引入Config服务端

创立Config空父模块,在上面建设一个config-server子模块,批改子模块的pom文件

留神是子模块的pom文件,不像以前一样批改的是空父模块的pom文件
<dependencies>    <dependency>        <groupId>org.springframework.cloud</groupId>        <artifactId>spring-cloud-config-server</artifactId>    </dependency></dependencies>

配置文件

因为临时没必要注册进Eureka中,所以配置文件的编写还是比较简单的

server:  port: 8101spring:  cloud:    config:      server:        git:          uri: https://gitee.com/cutey_none/springcloud-study-config          username:          password:      label: master

spring.cloud.config.server.git.uri :寄存文件的地址,到时候客户端就从这里获取配置文件,能够本地,也能够是git

如果是公开仓库,那么usernamepassword 不必写

因为创立的springcloud-study-config 仓库设置的权限凋谢的,所以间接用我的也行,本人创立也行,就失常github或者gitee创立一个仓库就好。

仓库搁置的是各个微服务的配置文件

例子是治理config-client微服务(前面会创立)的配置文件,所以须要在仓库中创立一个config-client-dev.properties(-dev示意是开发环境下的配置文件)

config-client-dev.properties 文件的内容如下,能够看作是config-client服务的某些配置

主启动类

减少@EnableConfigServer 注解以提供config服务反对

@SpringBootApplication@EnableConfigServerpublic class ConfigServer8101 {    public static void main(String[] args) {        SpringApplication.run(ConfigServer8101.class, args);    }}

测试

SpringCloud Config有本人http服务拜访资源的模式

  • /{application}/{profile}[/{label}] >> /config-client/dev
  • /{application}-{profile}.yml >> /config-client-dev.yml
  • /{label}/{application}-{profile}.yml >> /master/config-client-dev.yml
  • /{application}-{profile}.properties >> /config-client-dev.properties
  • /{label}/{application}-{profile}.properties >> /master/config-client-profile.properties

单个运行ConfigServer8101我的项目即可,用上述5种形式拜访资源,能够看到均能胜利从服务端拜访资源

config客户端

引入config客户端

后面始终说的config-client 就是接下来要创立的模块,最终的我的项目构造目录如下

接着批改config-client9501 模块的pom文件,留神服务端和客户端引入的依赖是不一样的

<dependencies>    <dependency>        <groupId>org.springframework.cloud</groupId>        <artifactId>spring-cloud-starter-config</artifactId>    </dependency></dependencies>

配置文件

配置文件留神命名是bootstrap.yml

因为客户端要设置服务端的uri,所以应该优先加载客户端配置文件

server:  port: 9501spring:  application:    name: config-client  cloud:    config:      profile: dev      label: master      uri: http://localhost:8101

spring.cloud.config.uri :服务端的地址,去哪里取配置文件

主启动类和业务类

@SpringBootApplication@RestControllerpublic class ConfigClient9501 {    public static void main(String[] args) {        SpringApplication.run(ConfigClient9501.class, args);    }    @Value("${name}")    String name;    @GetMapping("/hi")    public String hello() {        return "hello, " + name;    }}
在这里可能会遇到提醒找不到占位符${name},那必定是哪一方面没有依照步骤来了

测试

留神哈,下面客户端的配置文件中是没有name这个变量的

服务端的我的项目不必进行,再开启config-client9501 我的项目,开启的我的项目如下

上面拜访localhost:9501/hi ,失常的状况下能够看到如下

其实曾经抽蛮多的系统工夫来写了,然而有时候遇到了一些问题也还是须要尽可能弄懂再艰深地讲进去,心愿能帮到看这篇文章的小伙伴啦!!!

创作不易,如果对你有帮忙,欢送点赞,珍藏和分享啦!

上面是集体公众号,有趣味的能够关注一下,说不定就是你的宝藏公众号哦,根本2,3天1更技术文章!!!