天天看點

Spring Cloud Config 分布式配置中心使用一、簡介 

一、簡介

為了友善統一管理配置檔案管理,使用spring cloud config作為分布式配置中心,國産比較好的有百度的disconf,攜程的apollo,這裡我們介紹使用spring cloud config。它支援配置服務放在配置服務的記憶體中(即本地),也支援放在遠端Git、SVN等倉庫中。在spring cloud config 元件中,分兩個角色,一是config server,二是config client。

二、建立Config Server

建立一個spring-cloud項目,取名為config-server,支援maven和gradle,這裡配置中心使用svn遠端庫上的配置:

1.maven的pom.xml中引入依賴:

<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>config-server</groupId>
	<artifactId>config-server</artifactId>
	<packaging>jar</packaging>
	<name>dmw-config</name>
	<description>配置中心</description>
        <!--使用最新版的spring-boot ->
	 <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>Edgware.SR1</spring-cloud.version>
	</properties>


	<dependencies>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-config-server</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
			<exclusions>
				<exclusion>
					<groupId>org.springframework.boot</groupId>
					<artifactId>spring-boot-starter-tomcat</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.tmatesoft.svnkit</groupId>
			<artifactId>svnkit</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-undertow</artifactId>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.cloud</groupId>
			<artifactId>spring-cloud-starter-eureka</artifactId>
		</dependency>
	</dependencies>
   <!--依賴管理,用于管理spring-cloud的依賴,其中Edgware.SR1是版本号-->
	<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>
		<finalName>dmw-config</finalName>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>
           

 2.gradle build.gradle依賴:

buildscript {
	ext {
		springBootVersion = '1.5.10.RELEASE'
	}
	repositories {
		mavenCentral()
	}
	dependencies {
		classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
	}
}

apply plugin: 'java'
apply plugin: 'eclipse-wtp'
apply plugin: 'org.springframework.boot'

group = 'com.config'
version = ''
sourceCompatibility = 1.8

repositories {
    maven {url 'http://maven.aliyun.com/nexus/content/groups/public/'}
	mavenCentral()
}

configurations {
	providedRuntime
}

ext {
	springCloudVersion = 'Edgware.SR1'
	if(!project.hasProperty("profile")){
		profile='test'
	}
}
sourceSets {
	main {
		resources {
			srcDir "env/${profile}"
		}
	}
}
dependencies {
	compile('org.springframework.cloud:spring-cloud-config-server'){
	 exclude module: 'spring-boot-starter-tomcat'
	}
	compile('org.springframework.cloud:spring-cloud-starter-eureka')
	runtime('org.springframework.boot:spring-boot-starter-undertow')
	testCompile('org.springframework.boot:spring-boot-starter-test')
	compile('org.tmatesoft.svnkit:svnkit')
	compile('org.springframework.boot:spring-boot-starter-actuator')
}

dependencyManagement {
	imports {
		mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
	}
}
           

建立入口類BootApplication:

mport org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.config.server.EnableConfigServer;


@SpringBootApplication
@EnableConfigServer
public class ConfigServerApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConfigServerApplication .class, args);
    }
}
           

 application.yml:

spring:
  profiles:
    #使用svn這裡必須指定為subversion,否則會報錯,因為config預設配置的git
    active: subversion
  cloud:
    config:
      server:
        svn:
          # 配置svn倉庫位址
          uri: svn://192.168.1.1/config-repo
          # 配置svn通路賬号
          username: test
          # 配置svn通路密碼
          password: test
          #配置svn項目配置檔案所在目錄
          default-label: profiles
           

 服務端完成,如果在svn上的config-repo的profiel目錄下有一個application-dev.yml配置檔案,則可以通過http://loalhost:8080/application-dev.yml通路獲得配置資訊,該項目沒有指定端口,是以預設8080,

三、建構Config Client

重新建立一個springboot項目,取名為config-client

 1.maven 的pom檔案引入依賴:

<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>

        <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>
           

 2. gradle gruadle.build

buildscript {
	ext {
		springBootVersion = '1.5.10.RELEASE'
	}
	repositories {
		mavenCentral()
	}
	dependencies {
		classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
	}
}

apply plugin: 'java'
apply plugin: 'eclipse-wtp'
apply plugin: 'org.springframework.boot'
apply plugin: 'war'

group = 'com.config'
version = ''
sourceCompatibility = 1.8

repositories {
    maven {url 'http://maven.aliyun.com/nexus/content/groups/public/'}
	mavenCentral()
}

configurations {
	providedRuntime
}
ext{
    springCloudVersion = 'Edgware.SR1'
	if(!project.hasProperty("profile")){
		profile='demo'
	}
}

sourceSets {
	main {
		resources {
			srcDir "profiles/${profile}"
		}
	}
}
dependencies {
	compile('org.springframework.boot:spring-boot-starter-actuator')
	compile('org.springframework.boot:spring-boot-starter-web')
	compile('org.springframework.cloud:spring-cloud-config-client')
	providedRuntime('org.springframework.boot:spring-boot-starter-tomcat')
	testCompile('org.springframework.boot:spring-boot-starter-test')
}
dependencyManagement {
	imports {
		mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
	}
}
           

 其配置檔案bootstrap.yml:

spring:
  profiles:
    active: dev
  application:
    name: config-client
  cloud:
    config:
      enabled: true
      profile: ${spring.profiles.active}
      uri: http://${spring.cloud.client.ipAddress}:8080
     #如果config-server配置了賬号跟密碼
      username: test
      password: test
     #重試機制
      fail-fast: true
      retry:
        initial-interval: 2000
        max-interval: 10000
        multiplier: 2
        max-attempts: 10
           

程式的入口類,寫一個API接口“/hello”,傳回從如果配置中心的有foo變量的值,則可以擷取,代碼如下:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


@SpringBootApplication
@RestController
public class ConfigClientApplication {
    public static void main(String[] args) {
        SpringApplication.run(ConfigClientApplication .class, args);
    }
    
    @Value("${foo}") // svn配置檔案裡的key
    String foo;
    
    @RequestMapping(value = "/hello")
    public String hi(){
        return foo;
    }
    
}
           

繼續閱讀