Spring Cloud Config配置中心的使用

1、概述

1. 爲何使用?git

  1> 配置文件太多,不方便維護spring

  2> 配置文件通常都保存這各類明文顯示的密碼,沒法保證配置內容的安全性,也沒法作到按權限分配給我的bootstrap

  3> 更新配置項目需重啓,試想一想,在生產環境,那麼多臺機器。。。緩存

2. config介紹
config分爲Server端和Client端,實現原理以下圖所示:安全

  • Server端負責從遠端git(碼雲、GitHub等)拉取配置,並緩存在本地;
  • Client端(上圖的product和order服務)在啓動時,從Server端本地緩存中獲取配置

2、Server端配置

1. 新建config Server模塊,加載依賴app

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

2. 在啓動類上@EnableConfigServer註解,開啓configServerpost

@EnableConfigServer //開啓configServer
@SpringBootApplication
@EnableDiscoveryClient //開啓Eureka Client
public class TestConfigApplication {

    public static void main(String[] args) {
        SpringApplication.run(TestConfigApplication.class, args);
    }
}

3. 在遠端git上新建項目(這裏使用碼雲),並把配置上傳上去,具體操做略測試

說明:config語法規定,xxx.yml爲公共配置,在拉取配置時會和xxx.{}profiles}.yml合併url

4. 修改配置文件spa

spring:
  application:
    name: test-config
  profiles:
    active: dev
#配置中心 cloud: config: server: git: uri: https:
//gitee.com/wslook/test-config-repo.git search-paths: user  //配置文件目錄,多個用逗號隔開 username: xxx password: xxx default-label: master basedir: ./configRepo/  //本地緩存地址 force-pull: true  //強制拉取配置,解決手動修改本地緩存配置後,沒法拉取最新配置的問題
# 註冊中心
eureka:
instance:
prefer-ip-address: true
client:
service-url:
defaultZone: http://localhost:2181/eureka/
 

5. 測試

3、Client端配置

1. 加載依賴

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

2. 修改配置文件(把配置文件名改成bootstrap.yml)

spring:
# 配置中心
  cloud:
    config:
     name: user-config
     profile: dev
     label: master
     discovery:
        enabled: true
        serviceId: test-config
     fail-fast: true


# 註冊中心
eureka:
  instance:
    prefer-ip-address: true
  client:
    service-url:
      defaultZone: http://localhost:2181/eureka/

3. 測試

編寫測試代碼:

@RequestMapping("/test")
@RestController
public class TestController {

    @Resource
    private OSSProperties ossProperties;

    @RequestMapping("/config")
    public String test(){
        return ossProperties.getUrl();
    }
}

啓動user服務,能夠看到,已經把配置拉取下來了

使用postman驗證

 

4、高可用

對於config集羣,很簡單,由於由註冊中心(這裏使用的eureka)統一管理服務,因此不須要額外的配置,只需多啓動幾臺config Server服務便可

相關文章
相關標籤/搜索