SpringCloud-Config

184 阅读1分钟

简介

SpringCloud Config为微服务架构中的微服务提供集中化的外部配置支持,配置服务器为各个不同微服务应用的所有环境提供了一个中心化的外部配置。

架构

微服务通过ConfigServer来从远程git仓库获取对应的配置文件 5.png

实践

前提

  1. 在github或码云创建对应仓库,本人创建仓库springcloud-Config
  2. 在本地建立clone仓库
  3. 在本地仓库新建application.yml并push到github以验证是否连接成功
spring:
  profiles:
    active: dev
---
spring:
  profiles: dev
  application:
    name: springcloud-dev
---
spring:
  profiles: test
  application:
    name: springcloud-test

代码操作

  1. 导入依赖
<dependencies>
        <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-config-server -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-config-server</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
    </dependencies>
  1. 编写配置
server:
  port: 3344
spring:
  application:
    name: Config_3344
  cloud:
    config:
      server:
        git:
        # uri指向访问的git仓库
          uri:  https://gitee.com/Llinsihan/springcloud-Config.git
  1. 修改启动类
@SpringBootApplication
@EnableConfigServer
public class Config3344Application {
    public static void main(String[] args) {
        SpringApplication.run(Config3344Application.class,args);
    }
}

此时我们可以通过http://localhost:3344/application-dev.yml 访问github上的application文件中的dev部分。

注意:我们这里的3344服务器对应着图中的ConfigServer $U{H{JG6L.png 现在我们去配置一个微服务从当前的3344服务器获取配置

获取配置很简单,我们只需编写配置文件即可

spring:
  cloud:
    config:
      name: config-dept # 需要从git上获取的资源名
      uri: http://localhost:3344 #从server获取
      profile: dev 
      label: master # 仓库的分支

这里的uri指向我们的3344服务器即对应图中的ConfigServer从中获取我们的配置。 5.png