微服務系列之-Config配置中心本地集成

一.Config概述

Spring Cloud Config 提供一種基於客戶端與服務端(C/S)模式的分佈式的配置管理。我們可以把我們的配置管理在我們的應用之外(config server 端),並且可以在外部對配置進行不同環境的管理,比如開發/測試/生產環境隔離,並且還能夠做到實時更新配置。

二.服務搭建

配置中心服務搭建好以後,我們主要有兩種方式實現配置的讀取,一種是本地模式,一種是遠程模式。本地模式即在本地讀取配置文件,遠程我們可以通過,github或者gitlap、gitee等項目工具管理配置文件。

首先,我們先介紹本地拉取配置文件服務端配置。

  1. 服務端依賴
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-config-server</artifactId>
        </dependency>
  1. 服務端配置
server:
  port: 8084
spring:
  application:
    name: qyconfigcenter
  profiles:
    active: native
    cloud:
      config:
        server:
          native:
            searchLocations: classpath:/config

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
  1. 服務端啓動類以及關鍵註解
@Slf4j
@RefreshScope
@EnableConfigServer
@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class})
public class ConfigCenterApplication
{
    public static void main( String[] args )
    {
        SpringApplication.run(ConfigCenterApplication.class, args);
        log.info("配置中心啓動成功!");
    }
}
  1. 項目結構
    在這裏插入圖片描述

其次,我們還要搭建客戶端來調用服務端配置。客戶端沒有數據庫連接的配置文件,我將數據庫配置文件放在本地配置中心管理。下面我們來試試用之前的模塊集成config客戶端能不能正常的從本地配置中心拉取數據庫連接配置。
客戶端我以我之前搭建的集成mybatisplus服務爲客戶端,拿現成的不要太香。

  1. 客戶端依賴
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
        </dependency>
  1. 客戶端配置文件
spring:
  application:
    name: qymybatisplusclient
  cloud:
    config:
      uri: http://localhost:8084/
      #      label: master
      failFast: true
      #      本地配置文件訪問
      profile: gr
      retry:
        initial-interval: 2000
        max-interval: 2000
        max-attempts: 2000
        multiplier: 1.2
  1. 客戶端啓動類
@Slf4j
@EnableDiscoveryClient
@SpringBootApplication(scanBasePackages = {"org.qy.mybatisplus.client"})
public class MybatisplusApplication
{
    public static void main( String[] args )
    {
        ApplicationContext context = SpringApplication.run(MybatisplusApplication.class, args);
        String serverPort = context.getEnvironment().getProperty("server.port");
        log.info("後臺管理服務客戶端啓動成功! Swagger2: http://127.0.0.1:".concat(serverPort).concat("/swagger-ui.html"));
    }
}

最後,我們就這樣很快速的搭建好本地配置中心的配置管理。我們來訪問一下能不能正常讀取數據庫數據。
在這裏插入圖片描述

三.配置文件名與URL的映射關係

Config Server 中配置文件的 HTTP 資源操作方式如下

/{application}/{profile}[/{label}]
/{application}-{profile}.yml
/{label}/{application}-{profile}.yml
/{application}-{profile}.properties
/{label}/{application}-{profile}.properties

其中,{application} 被用於 spring 配置的配置文件名稱,在 spring boot 中通常默認爲 application;{profile} 表示激活的配置文件,通常用於區分開發/測試/生產環境;{label} 則表示 git 的分支,默認爲 master。

這樣我們就做到了配置中心的本地化管理。下一章節,我們來配置遠程拉取配置文件。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章