天天看點

SpringCloud Config分布式配置中心子產品

說明

SpringCloud Config是SpringCloud團隊建立的一個全新項目,用來為分布式系統中的基礎設施和微服務應用提供集中化的外部配置支援,它分為服務端和用戶端兩個部分。其中服務端也稱為分布式配置中心,它是一個獨立的微服務應用,用來連接配接配置倉庫并為用戶端提供擷取配置資訊、加密/解密資訊等通路接口;而用戶端則是微服務架構中的各個微服務應用或基礎設施,它們通過指定的配置中心來管理應用資源與業務相關的配置内容,并在啟動的時候從配置中心擷取和加載配置資訊。Spring Cloud Config實作了對服務端和用戶端中環境變量和屬性配置的抽象映射,是以它除了适用于Spring建構的應用程式之外,也可以在任何其他語言運作的應用程式中使用。由于Spring Cloud Config實作的配置中心預設采用Git來存儲配置資訊,是以使用Spring Cloud Config建構的配置伺服器,天然就支援對微服務應用配置資訊的版本管理,并且可以通過Git用戶端工具來友善的管理和通路配置内容。當然它也提供了對其他存儲方式的支援,比如:SVN倉庫、本地化檔案系統。

目标

使用SpringCloud Config實作分布式配置設定置中心的注冊和如何讀取配置中心的資料,更新配置檔案也能更新程式讀取的資訊(本文使用的是碼雲來做代碼托管->https://gitee.com)

快速開始

準備

使用碼雲建立項目,建立了檔案夾的話服務端使用searchPaths定位即可,例如:建立檔案夾test,再在test裡建立檔案spring-config-dev.properties内容如下(中文注意轉Unicode編碼):

info=Spring-config-dev refresh
version=0.0.2
           
服務端

項目結構圖

SpringCloud Config分布式配置中心子產品

1 更新pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>yunlingfly</groupId>
	<artifactId>springcloud-config</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>springcloud-config</name>
	<description>Demo project for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.10.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
		<spring-cloud.version>Dalston.SR2</spring-cloud.version>
	</properties>

	<dependencies>
		<!-- 引入用戶端 -->
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-config-server</artifactId>
		</dependency>

		<!-- 引入Eureka将config-server注冊到注冊中心 -->
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-eureka</artifactId>
		</dependency>

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

	<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>org.springframework.cloud</groupId>
				<artifactId>spring-cloud-dependencies</artifactId>
				<version>${spring-cloud.version}</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>
           

2 更新application.yml

spring:
  http:
    encoding:
      charset: UTF-8
  application:
    name: config-server
  cloud:
    config:
      server:
        git:
          #uri例如:https://gitee.com/yunlingfly/spring-config
          uri: https://gitee.com/xxxxxx/xxxxxx/
          #設定尋找目錄,如果有檔案夾的話
          searchPaths: test
          #設定賬号和密碼(如果是私有項目的話)
          username: xxxxxx
          password: xxxxxx
server:
  port: 8763
eureka:
  client:
#    register-with-eureka: true
#    fetch-registry: true
    serviceUrl:
      defaultZone: http://xxx.xxx.xxx.xxx:8761/eureka/,http://xxx.xxx.xxx.xxx:8762/eureka/
    # 不是本機的話需要配置下面的參數
#  instance:
#    preferIpAddress: true
#    instance-id: ${spring.cloud.client.ipAddress}:${server.port}
#    hostname: ${spring.cloud.client.ipAddress}
#    ipAddress: xxx.xxx.xxx.xxx
info:
  name: config-server服務中心
  version: 0.0.1
           

3 編寫啟動類(@EnableConfigServer)

package yunlingfly.springcloudconfig;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.config.server.EnableConfigServer;

// Eureka服務提供者
@EnableDiscoveryClient
// config服務中心
@EnableConfigServer
@SpringBootApplication
public class SpringcloudConfigApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringcloudConfigApplication.class, args);
	}
}
           
用戶端

首先給出項目結構

SpringCloud Config分布式配置中心子產品

1 更新pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>yunlingfly</groupId>
	<artifactId>springcloud-config-client</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>springcloud-config-client</name>
	<description>Demo project for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.10.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
		<spring-cloud.version>Dalston.SR2</spring-cloud.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-tomcat</artifactId>
			<!--<scope>provided</scope>-->
		</dependency>

		<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-config -->
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-config</artifactId>
		</dependency>

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

		<!-- Eureka服務發現 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>

		<!-- 配置retry和AOP防止因網絡波動導緻直接不能啟動連接配接config-server -->
		<dependency>
			<groupId>org.springframework.retry</groupId>
			<artifactId>spring-retry</artifactId>
		</dependency>

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

		<!-- 重新整理 -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-actuator</artifactId>
		</dependency>

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

	<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>org.springframework.cloud</groupId>
				<artifactId>spring-cloud-dependencies</artifactId>
				<version>${spring-cloud.version}</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>
           

2 更新application.yml

info:
  name: git-config-client,一個服務發現者
  version: 0.0.1
#權限安全
management:
  security:
    enabled: false
           

3 更新bootstrap.yml

server:
  port: 8764
spring:
  application:
    # 這個名字很重要,因為如果配置中心使用通配符的話,可以通過使用這個name來替換{application}
    name: spring-config
  cloud:
    config:
      # 字尾
      profile: dev
      # 标簽,預設為master分支
      label: master
      #配置下面的參數可以快速測試config-server,如果失敗直接報錯,避免前面的其他操作
#      fail-fast: true
#      #當快速失敗開啟時,使用下面的配置(可選)更新retry的參數
#      retry:
#        #最大retry次數,預設6
#        max-attempts: 3
#        #初始重試間隔時間,預設1000
#        multiplier: 1000
#        #下一個間隔的乘數,如1000ms程式設計1100ms,預設2000
#        initial-interval: 1100
#        #最大間隔時間,預設2000
#        max-interval: 2000
      #下面的方法是直接通過uri連接配接服務
#      uri: http://xxx.xxx.xxx.xxx:8763/
      discovery:
        #通過Eureka注冊中心查找config服務,通路config-server
        enabled: true
        serviceId: config-server
eureka:
  client:
    serviceUrl:
      defaultZone: http://xxx.xxx.xxx.xxx:8761/eureka/,http://xxx.xxx.xxx.xxx:8762/eureka/
           

4 編寫啟動類

package yunlingfly.springcloudconfigclient;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

@EnableDiscoveryClient
@SpringBootApplication
public class SpringcloudConfigClientApplication {

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

5 編寫Controller層

package yunlingfly.springcloudconfigclient.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

// 動态重新整理
@RefreshScope
@RestController
public class HelloController {
    @Value("${info}")
    private String info;    //通過遠端配置
    @RequestMapping(value = "/config",method = RequestMethod.GET)
    public String hello(){
        System.out.println(info);
        return "success,info:"+info;
    }
}
           
運作

啟動Eureka(沿用之前項目),啟動服務端,啟動用戶端,浏覽器通路http://localhost:8764/config/

SpringCloud Config分布式配置中心子產品

下一步我們更新配置檔案 spring-config-dev.properties

info=Spring-config-dev refresh \u66f4\u65b0\u6d4b\u8bd5
version=0.0.3
           

使用POSTMAN使用POST(注意是POST)方法通路http://localhost:8764/refresh即可重新整理配置資訊

SpringCloud Config分布式配置中心子產品

控制台:

SpringCloud Config分布式配置中心子產品

重新通路http://localhost:8764/config/發現輸出改變了

SpringCloud Config分布式配置中心子產品

注意事項:服務端使用@EnableConfigServer開啟注冊中心服務,用戶端注意security權限安全(可以使用/refresh通路重新整理),@Value直接讀取資訊

http請求位址和資源檔案映射如下:

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

繼續閱讀