美文网首页Java
springcloud之config

springcloud之config

作者: GG_lyf | 来源:发表于2021-01-09 19:32 被阅读0次

前言

  在整个项目中,如果修改每一个微服务的application.yml,那就太痛苦了,怎么办呢?可以把这些配置文件给推到云端,集体管理就行。这时config就起到了作用。


开搞

  在分布式系统中,由于服务数量巨大,为了方便服务配置文件统一管理,实时更新,所以需要分布式配置中心组件,在spring cloud中,有分布式配置中心组件spring cloud config,他支持配置服务放在配置服务的内存中(即本地),也支持放在GitHub中。

  在spring cloud config组件中,分两个角色,一个是config server,一个是config client。

  config server 是一个可横向扩展,集中式的配置服务,他用于集中管理应用程序各个环境下的配置,默认使用git存储配置文件内容,也可使用svn或本地存储。

  config client是config server的客户端,用于操作存储在config server中的配置内容。
微服务在启动的时候会请求config server获取配置文件内容,请求到后再启动容器。

  这东西就是配置中心,把所有的服务配置文件都放在一个代码管理平台上,通过spring cloud config去读取服务对应所需要的配置文件。

1.在现有的springboot项目中创建一个config微服务,并且用的是maven创建的,并且在GitHub中创建一个仓库,私有的公有的都行

2.添加依赖

<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-config-server</artifactId>
</dependency>
<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

3.修改application.yml

server:
  port: 9005
spring:
  application:
    name: config
  cloud:
    config:
      server:
        git:
          uri: https://github.com/*****/*****#git仓库地址
          username: *****@qq.com            #用户名
          password: *****             #密码
          skip-ssl-validation: true              #不用ssh
      label: master                              #分支

eureka:
  instance:
    prefer-ip-address: true
  client:
    service-url:
      defaultZone: http://127.0.0.1:9001/eureka/,http://127.0.0.1:9002/eureka/

4.修改启动类

@SpringBootApplication
@EnableConfigServer  //启用config
@EnableEurekaClient
public class ConfigApplication {

  public static void main(String[] args) {
    SpringApplication.run(ConfigApplication.class,args);
  }
}

5.客户端添加依赖

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

6.修改被代理的微服务的yml(将原本的application.yml推到github,将本地的application.yml删了之后添加一个bootstrap.yml),值得注意的是那个application.yml的名字必须是{xxx}-{xxx}.yml的形式,这两个东西要和你的配置文件里的name和profile一致

spring:
  cloud:
    config:
      label: master                #分支
      name: base                  #名字
      profile: dev                #后缀
      uri: http://127.0.0.1:9005 #config的地址和端口

7.最好是先启动配置中心再启动被代理的微服务,不然微服务会报错。启动之后正常访问端口就行。如果微服务的端口不叫8080,而启动之后显示的是8080那么就是报错了。

8.流程: 要访问的那个路径(端口还是微服务的端口) -> 要访问的那个微服务 -> 微服务的bootstrap.yml -> eureka通过bootstrap中的uri找到springcloud config -> config用bootstrap.yml中的name,profile和label找到git仓库中的base -dev/pro.yml,并拉取 -> 微服务拿到xxx-xxx.yml开始加载 -> 访问路径得到结果

流程图

相关文章

网友评论

    本文标题:springcloud之config

    本文链接:https://www.haomeiwen.com/subject/eouboktx.html