SpringCloud基础(3)–配置中心Config

在之前的学习中,我们发现SpringCloud存在许多需要在配置文件中配置的数据,但实际情况下,我们如果一个一个去配置文件必然极其繁琐。因此我们需要一种更加高级的集中化地配置文件管理工具,集中地对配置文件进行配置。

Spring Cloud Config 为分布式系统中的外部配置提供服务器端和客户端支持。使用 Config Server,您可以集中管理所有环境中应用程序的外部配置。

image-20230306230655437

我们创建一个新的项目config引入依赖:

<dependencies>
    <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>
</dependencies>

创建启动类并添加ConfigServer注解:

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

配置配置文件:

server:
  port: 8700
spring:
  application:
    name: configserver
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8801/eureka, http://localhost:8802/eureka

接下来就可以去实现Config了。

我们以本地仓库为例。首先创建本地仓库,在仓库里放入配置文件(以 服务名+环境 来命名)

在Config中添加本地仓库信息:

spring:
  cloud:
    config:
      server:
        git:
          # 这里填写的是本地仓库地址,远程仓库直接填写远程仓库地址 http://git...
          uri: file://${user.home}/Desktop/config-repo
          # 默认分支设定为你自己本地或是远程分支的名称
          default-label: main

当然这里也可以直接添加网络仓库地址。

这样我们就可以通过:

来访问配置文件了。

这里除了使用git保存之外,也支持其他一些方式,具体可以查看官网

这样我们就算配置完Config配置中心服务器了。接下来我们就需要配置客户端。

首先,我们给客户端添加依赖:

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

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

接下来我们删除原来的application.yml文件(也可以保留,最后无论是远端配置还是本地配置都会被加载),改用bootstrap.yml(在application.yml之前加载,可以实现配置文件远程获取)

bootstrap.yml中添加

spring:
  cloud:
    config:
        # 名称,其实就是文件名称
      name: bookservice
      # 配置服务器的地址
      uri: http://localhost:8700
      # 环境
      profile: prod
      # 分支
      label: main

这样就能从配置中心获取到配置信息了。