Spring Cloud-config(十一)


說明

用於分布式中統一的配置管理,是一個單獨的微服務

簡單例子

准備git

1.我自己在本地環境搭建了git服務器 也可以使用github 可參考:https://www.cnblogs.com/LQBlog/p/10218798.html    可參考git命令https://www.cnblogs.com/LQBlog/p/10219959.html

2.添加一個git倉庫 當前demo git地址為:http://admin@localhost:1234/r/config.git

3在master分支增加2個配置文件

內容分別為data-source:2   data-source:1

4.再添加一個properti2.0 分支

內容分別為data-source: properti2.0-i3  data-source:properti2.0.1

服務端

1.創建一個spring-cloud-config-server項目

2.引入pom依賴

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-config-server</artifactId>
        </dependency>
    </dependencies>

3.啟動添加config服務端功能

@SpringBootApplication
@EnableConfigServer //開啟config服務端功能
public class SpringCloudConfigApplication {

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

}

4.yml配置git信息

spring:
  application:
    name: config
  cloud:
    config:
      server:
        git:
          uri: http://admin@localhost:1234/r/config.git #git地址
          search-paths: ERPApplicationConfig/ #查找git目錄
          username: admin #git用戶名
          password: admin  #git密碼
server:
  port: 7001

5.訪問配置文件的URl映射  

 /{application}/{profile}[/{label}]

{application}-{profile}.yml

/{label}/{application}-{profile}.yml

/{application}-{profile}.properties

/{label}/{application}-{profile}.properties

如訪問master dev環境的文件

http://127.0.0.1:7001/mybatis/dev/master

version為git上面的版本號   通過版本號可以知道返回的哪一次提交的配置

server啟動時會通過git clone 將配置信息復制一份到本地。然后每次訪問http://127.0.0.1:7001/mybatis/dev/master 會通過git pull  獲取最新配置。如果git 掛了 會直接返回本地的配置;如關掉git服務端再訪問http://127.0.0.1:7001/mybatis/dev/master 日志打印

雖然報錯 但是還是能正常返回配置信息  因為返回本地的原因

客戶端

1.新建一個client項目

2.配置pom依賴

 <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
        </dependency>
    </dependencies>

3.新建一個bootstrap.yml 

ps:因為讀取配置的時候是加載bootstrap.yml的時候就讀取了 如果配置到application.yml 加載的時候這個配置還沒初始化

spring:
  application:
    name: mybatis #對應{application}
  cloud:
    config:
      profile: dev #映射{profile}
      label: master #映射{label}
      uri: http://127.0.0.1:7001 #config server地址
server:
  port: 7002

4.新建一個contorller測試讀取配置

@Controller
public class ConfigInfoContorller {
    @Value("${data-source}")
    private String dataSource;
    @RequestMapping("/getDataSorce")
    @ResponseBody
    public String getDataSource(){
        return dataSource;
    }
}

或者

@Controller
public class ConfigInfoContorller {
    @Autowired
    private Environment environment;
    @RequestMapping("/getDataSorce")
    @ResponseBody
    public String getDataSource() {
        //讀取配置 如果不存在返回undefined
        return environment.getProperty("data-source", "undefined");
    }

}

 

5.啟動config servicer  configclient測試

更多配置

本地調試

當configserver服務不可用或者我們需要本地調試指定我們自己的配置文件 可以將配置git clone到本地 然后指定應用我們本地的配置

spring:
  cloud:
    config:
      server:
        git:
          uri: file:/Users/liqiang/Desktop/gitblit/config/config 
          search-paths: ERPApplicationConfig/ #查找git目錄

uri占位符

通過application自動映射倉庫地址 實現一個項目對應一個git

http://admin@localhost:1234/r/config.git

http://admin@localhost:1234/r/{application} 

當我們輸入http://127.0.0.1:7001/config/dev/master  會自動把config 映射到對應的倉庫地址  

如果使用config client 會把application.name填充到占位符

ps:不僅{application} 可以占位{profile}{label}也可以

search-paths占位

實現一個git 不同的項目對應不同的配置目錄

spring:
  application:
  cloud:
    config:
      server:
        git:
          uri: http://admin@localhost:1234/r/config #git地址   file:/Users/liqiang/Desktop/gitblit/config/config
          search-paths: '{application}/' #查找git目錄
          username: admin #git用戶名
          password: admin  #git密碼

將搜索appliction映射名字目錄下的 application-profile文件

多倉庫配置

容易造成混亂不推薦

本地文件系統

將應用本地文件 src/main/resource下的配置文件 不推薦使用 可以通過spring.cloud.config.server.native.search-locations指定搜索路

spring.profiles.active= native

健康監測

http://admin@localhost:1234/r/{application}  當我們使用占位符的方式的時候server會去檢查http://admin@localhost:1234/r/app的git地址 導致報錯以及heath健康檢查為dwon 導致分析的時候誤認為git掛了

測試

1.server引入端點pom

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

2.開啟端點配置

management:
  endpoints:
    web:
      exposure:
        include: health

3、訪問http://127.0.0.1:7001/actuator/health

4.增加配置

spring:
  application: config-server
  cloud:
    config:
      server:
        git:
          uri: http://admin@localhost:1234/r/{application} #git地址   file:/Users/liqiang/Desktop/gitblit/config/config
          search-paths: '{application}/' #查找git目錄
          username: admin #git用戶名
          password: admin  #git密碼
        health:
          repositories:
            check:
              name: config #檢查的application占位符
              lable: master #檢查的lable占位符
              profiles: default #檢查的profiles 占位符
server:
  port: 7001
management:
  endpoints:
    web:
      exposure:
        include: health

訪問

也可以通過

spring.cloud.config. server.health.enabled=false關閉健康檢查

屬性覆蓋

spring.cloud.config.server.overrides.{propertyname}={value} config-server通過此配置配置的屬性將不可被客戶端覆蓋

安全保護

身份認證

1.serverconfig增加pom依賴

  <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>

2.serverconfig配置

spring:
  security:
    user:
      name: liqiang
      password: liqiang

3.訪問http://127.0.0.1:7001/config/dev/master

 4.config-client客戶端則需要配置

spring:
  cloud:
    config:
      username: liqiang
      password: liqiang

配置加密(對稱加密)

1.下載需要更換的jar http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html

2.執行java -verbose查看jdk安裝 

3.將下載下來的jar 覆蓋$JAVA HOME/jre/lib/security 原來的jar

4.server配置秘鑰

encrypt:
  key: ffff

ps:必須在bootstrap下配置

5.相關端點

http://127.0.0.1:7001/encrypt/status(get請求) 返回ok表示配置成功

http://127.0.0.1:7001/key(get請求) 返回秘鑰

http://127.0.0.1:7001/encrypt(post請求) 將body文件加密

http://127.0.0.1:7001/decrypt(post請求) 將body文件解密

6.使用posmanpost訪問/encrypt 將加密數據放到body進行加密

7.將配置信息的放入加密字符串並加上{cipher}前綴

8.當客戶端訪通過config-server訪問配置文件 cipher前綴的標識着加密數據 將自動解密

配置中心集群

傳統方式

服務端集群通過nginx代理

注冊中心服務化

服務端

1.pom增加eureka依賴

  <!--使用eureka來實現配置中心的高可用-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>

2.application增加注解開啟服務注冊功能

@SpringBootApplication
@EnableConfigServer //開啟config服務端功能
@EnableDiscoveryClient //開啟將服務注冊到注冊中心
public class SpringCloudConfigServerApplication {

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

}

3.yml文件配置注冊中心地址並開啟info端點

management:
  endpoints:
    web:
      exposure:
        include: health,info
eureka:
  instance:
    hostname: localhost #當前實例的主機名字
  client:
    serviceUrl:
      defaultZone: http://peer1:1111/eureka/, http://peer2:1112/eureka/

4.測試

 

客戶端 

1.增加eurekapom依賴 用於服務發現

     <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>

2.application開啟服務發現的注解

@SpringBootApplication
@EnableDiscoveryClient //開啟服務發現
public class SpringCloudConfigClientApplication {

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

}

3.yml配置

spring:
  application:
    name: config #對應{application}
  cloud:
    config:
      profile: dev #映射{profile}
      label: master #映射{label}
      #uri: http://127.0.0.1:7001 #config server地址
      username: liqiang #configserver身份認證用戶名
      password: liqiang #configserver身份認證密碼
      discovery:
        service-id: CONFIG-SERVER #configserver的服務名
        enabled: true #開啟通過服務訪問configserver的功能
server:
  port: 7002
eureka:
  instance:
    hostname: localhost #當前實例的主機名字
  client:
    serviceUrl:
      defaultZone: http://peer1:1111/eureka/, http://peer2:1112/eureka/

將原來的url注釋改為spring.cloud.discovery.service-id 指定configserver是那個服務  spring.coud.discovery.enabled=true 表示開啟通過服務訪問configserver

快速響應與重試

快速響應

我們比較大的項目的時候剛開始啟動會初始化一系列配置可能耗時5分鍾。但是前面都沒問題 當加載config的時候出現異常 前面的初始化就沒有意義了。

可以通過配置 如果config-server不通的時候能夠馬上拋出異常

只需要通過配置

spring.cloud.config.fail-fast=true

重試

當我們通過config-server加載失敗的時候可以通過設定重試時間以及間隔,避免config-server出現網絡占時不通而導致失敗

1.spring.cloud.config.fail-fast=true 增加了快速響應配置

2.pom依賴

 <!--連接服務端重試的功能 依賴 前提 必須確保開啟了fail-fast 默認6秒重試一次-->
        <dependency>
            <groupId>org.springframework.retry</groupId>
            <artifactId>spring-retry</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>

3.我們再不啟動config.server的時候啟動client

重試6此失敗

相關配置

spring:
  cloud:
    config:
      retry:
        multiplier: 1.1 #默認間隔乘數  如果間隔是1000  下一次間隔是1100
        max-interval: 2000 #默認最大間隔數(毫秒)
        max-attempts: 6 #默認重試次數
        initial-interval: 1000 #默認間隔數 

動態刷新配置 

1.client pom增加依賴用於端點

<!--開啟端點  用於端點模塊提供的 動態刷新配置 /refresh-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

2.client yml開啟/refresh端點

management:
  endpoints:
    web:
      exposure:
        include: refresh

3.post請求訪問http://127.0.0.1:7002/actuator/refresh 刷新配置

 ps:需要刷新配置的地方需要打上@RefreshScope注解,如:
@Controller
@RefreshScope
public class ConfigInfoContorller {
    @Autowired
    private Environment environment;
    @RequestMapping("/getDataSorce")
    @ResponseBody
    public String getDataSource() {
        //讀取配置 如果不存在返回undefined
        return environment.getProperty("data-source", "undefined");
    }
    @RequestMapping("/getEncryptionDataSource")
    @ResponseBody
    public String getEncryptionDataSource(){
        return environment.getProperty("dbdatasource", "undefined");
    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM