必要性

统一配置中心config是指,将所有服务的配置全部放到git中,config服务端拉取所有配置,其它服务从config服务端中拉取相应的服务。

为什么需要配置中心呢?

1.配置内容的安全性。一些比较重要的信息如数据库的账号密码,不会暴露给开发人员,就会放到配置中心。

2.更新配置需要重启。一般项目配置更新后需要重启项目,而从config server刷新配置就可实时更新。

架构

首先把所有配置放到git中,config server拉取所有配置并放入本地(是一个git仓库),其他服务拉取config server中自身需要的配置

config集成

git项目创建(我是用的是github)

项目文件名保持 服务名-运行环境 格式,比如 product-dev.yml(或者product-dev.properties)

config server

pom文件引入依赖

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

启动类添加注解

@EnableConfigServer

application配置文件(要注册到eureka)

spring:
  application:
    name: config
  cloud:
    config:
      server:
        git:
          uri: **
          username: ***
          password: ***
#          basedir: D:\ideaproject\SpringCloud\config-repo
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/

git的uri,账号密码

basedir:拉取git中的配置文件的本地存放位置

运行

启动项目后,使用 localhost:8080/product-dev.yml

若页面显示配置文件内容,热正常启动

若不显示,可能是yml文件格式错误,缩进等。也可能是git的uri,账号密码错误

客户端(项目名为product)

pom依赖

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

配置文件

若服务想拉取config server的配置,需要将配置文件application.yml(或application.properities)改为bootstrap.yml(bootstrap.properities)

内容保存

spring:
  application:
    name: product
  cloud:
    config:
      profile: dev
      discovery:
        service-id: CONFIG
        enabled: true
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/
  instance:
    prefer-ip-address: true

其他全部写到git中响应配置文件中

其中

profile:指git配置文件中服务名后边的 运行环境 名称,这里是dev

service-id:配置中心在eureka中的名称是CONFIG,是指项目从eureka中搜索名为CONFIG的,从中拉取配置

启动即可

Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐