SpringCloud-Config配置中心搭建保姆级教程

发布时间 2023-09-23 19:16:29作者: 佛祖让我来巡山

一、分布式配置中⼼

在使⽤微服务架构开发的项⽬中,每个服务都有⾃⼰的配置⽂件(application.yml),如果将每个服务的配置⽂件直接写在对应的服务中,存在以下问题:
1. 服务开发完成之后,需要打包部署,配置⽂件也会打包在jar⽂件中,不便于项⽬部署之后的配置修改(在源码中修改——重新打包——重新上传——重新运⾏)
2. 微服务架构中服务很多,配置⽂件也很多,分散在不同服务中不便于配置的管理
3. 如果想要对服务进⾏集群部署,需要打包多个jar⽂件,上传,运⾏

1、分布式配置中⼼介绍

2、分布式配置中⼼搭建

步骤:
1、创建⼀个Git远程仓库,⽤来存放配置⽂件
2、搭建分布式配置中⼼服务器(Spring Cloud Config)Config server
  2.1、连接到配置⽂件的Git仓库
  2.2、注册到eureka
3、修改每个服务,删除application.yml中的所有配置,连接到分布式配置中⼼

1、创建Git远程仓库存储配置文件

1、创建远程仓库:https://gitee.com/qfytao/fmmall-config.git
2、在本地D盘创建 fmmall-config⽬录,作为本地存放配置⽂件的⽬录,在⽬录中创建files⽬录
3、使⽤idea打开 fmmall-config ⽬录
4、项⽬中服务的配置⽂件拷⻉粘贴到files⽬录,以服务的名称给配置⽂件命名

5、将本地仓库push到创建的git远程仓库

2、搭建分布式配置中⼼服务器

1、创建SpringBoot应⽤,添加依赖

2、配置application.yml

server:
  port: 8888
spring:
  application:
    name: config-server
  cloud:
    config:
      server:
        git:
          uri: 'https://gitee.com/qfytao/fmmall-config.git'
          search-paths: files
          username: 366274379@qq.com
          password: admin123
eureka:
  client:
    service-url:
      defaultZone: 'http://zhangsan:123456@localhost:8761/eureka'

3、在启动类添加注解

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

4、运⾏测试

访问 http://localhost:8888/api-order-submit/master

3、配置服务,通过分布式配置中⼼加载配置⽂件

1、添加依赖

<dependency>
 <groupId>org.springframework.cloud</groupId>
 <artifactId>spring-cloud-starter-config</artifactId>
</dependency>
2、配置服务的application.yml
spring:
  cloud:
    config:
      uri: 'http://localhost:8888'
      name: api-order-submit
      label: master