Spring Cloud構(gòu)建微服務(wù)架構(gòu):分布式配置中心

Spring Cloud構(gòu)建微服務(wù)架構(gòu):分布式配置中心


簡(jiǎn)介

Spring Cloud Config是Spring Cloud團(tuán)隊(duì)創(chuàng)建的一個(gè)全新項(xiàng)目,用來(lái)為分布式系統(tǒng)中的基礎(chǔ)設(shè)施和微服務(wù)應(yīng)用提供集中化的外部配置支持,它分為服務(wù)端與客戶端兩個(gè)部分。其中服務(wù)端也稱為分布式配置中心,它是一個(gè)獨(dú)立的微服務(wù)應(yīng)用,用來(lái)連接配置倉(cāng)庫(kù)并為客戶端提供獲取配置信息、加密/解密信息等訪問(wèn)接口;而客戶端則是微服務(wù)架構(gòu)中的各個(gè)微服務(wù)應(yīng)用或基礎(chǔ)設(shè)施,它們通過(guò)指定的配置中心來(lái)管理應(yīng)用資源與業(yè)務(wù)相關(guān)的配置內(nèi)容,并在啟動(dòng)的時(shí)候從配置中心獲取和加載配置信息。Spring Cloud Config實(shí)現(xiàn)了對(duì)服務(wù)端和客戶端中環(huán)境變量和屬性配置的抽象映射,所以它除了適用于Spring構(gòu)建的應(yīng)用程序之外,也可以在任何其他語(yǔ)言運(yùn)行的應(yīng)用程序中使用。由于Spring Cloud Config實(shí)現(xiàn)的配置中心默認(rèn)采用Git來(lái)存儲(chǔ)配置信息,所以使用Spring Cloud Config構(gòu)建的配置服務(wù)器,天然就支持對(duì)微服務(wù)應(yīng)用配置信息的版本管理,并且可以通過(guò)Git客戶端工具來(lái)方便的管理和訪問(wèn)配置內(nèi)容。當(dāng)然它也提供了對(duì)其他存儲(chǔ)方式的支持,比如:SVN倉(cāng)庫(kù)、本地化文件系統(tǒng)。

在本文中,我們將學(xué)習(xí)如何構(gòu)建一個(gè)基于Git存儲(chǔ)的分布式配置中心,并對(duì)客戶端進(jìn)行改造,并讓其能夠從配置中心獲取配置信息并綁定到代碼中的整個(gè)過(guò)程。

準(zhǔn)備配置倉(cāng)庫(kù)

  • 準(zhǔn)備一個(gè)git倉(cāng)庫(kù),可以在碼云或Github上創(chuàng)建都可以。比如本文準(zhǔn)備的倉(cāng)庫(kù)示例:http://git.oschina.net/didispace/config-repo-demo

  • 假設(shè)我們讀取配置中心的應(yīng)用名為config-client,那么我們可以在git倉(cāng)庫(kù)中該項(xiàng)目的默認(rèn)配置文件config-client.yml:

info:
  profile: default
  from: git1
  
test: bbb
  • 為了演示加載不同環(huán)境的配置,我們可以在git倉(cāng)庫(kù)中再創(chuàng)建一個(gè)針對(duì)dev環(huán)境的配置文件config-client-dev.yml:
info:
  profile: dev
  from: git

構(gòu)建配置中心

通過(guò)Spring Cloud Config來(lái)構(gòu)建一個(gè)分布式配置中心非常簡(jiǎn)單,只需要三步:

  • 創(chuàng)建一個(gè)基礎(chǔ)的Spring Boot工程,命名為:config-server-git,并在pom.xml中引入下面的依賴(省略了parent和dependencyManagement部分):
<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-config-server</artifactId>
    </dependency>
</dependencies>
  • 創(chuàng)建Spring Boot的程序主類,并添加@EnableConfigServer注解,開(kāi)啟Spring Cloud Config的服務(wù)端功能。
@EnableConfigServer
@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        new SpringApplicationBuilder(Application.class).web(true).run(args);
    }

}
  • 在application.yml中添加配置服務(wù)的基本信息以及Git倉(cāng)庫(kù)的相關(guān)信息,例如:
spring
  application:
    name: config-server
  cloud:
    config:
      server:
        git:
          uri: http://git.oschina.net/didispace/config-repo-demo/
server:
  port: 1201

到這里,使用一個(gè)通過(guò)Spring Cloud Config實(shí)現(xiàn),并使用Git管理配置內(nèi)容的分布式配置中心就已經(jīng)完成了。我們可以將該應(yīng)用先啟動(dòng)起來(lái),確保沒(méi)有錯(cuò)誤產(chǎn)生,然后再嘗試下面的內(nèi)容。

如果我們的Git倉(cāng)庫(kù)需要權(quán)限訪問(wèn),那么可以通過(guò)配置下面的兩個(gè)屬性來(lái)實(shí)現(xiàn);
spring.cloud.config.server.git.username:訪問(wèn)Git倉(cāng)庫(kù)的用戶名
spring.cloud.config.server.git.password:訪問(wèn)Git倉(cāng)庫(kù)的用戶密碼

完成了這些準(zhǔn)備工作之后,我們就可以通過(guò)瀏覽器、POSTMAN或CURL等工具直接來(lái)訪問(wèn)到我們的配置內(nèi)容了。訪問(wèn)配置信息的URL與配置文件的映射關(guān)系如下:

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

項(xiàng)目啟動(dòng)部分日志如下:

/Library/Java/JavaVirtualMachines/jdk1.8.0_171.jdk/Contents/Home/bin/java -XX:TieredStopAtLevel=1 -noverify -Dspring.output.ansi.enabled=always -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=54924 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -Djava.rmi.server.hostname=127.0.0.1 -Dspring.liveBeansView.mbeanDomain -Dspring.application.admin.enabled=true s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@35047d03: startup date [Sat Aug 25 15:56:38 CST 2018]; root of context hierarchy
2018-08-25 15:56:38.543  INFO 48775 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'configurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$ca5d5115] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.5.4.RELEASE)

2018-08-25 15:56:38.834  INFO 48775 --- [           main] com.didispace.Application                : No active profile set, falling back to default profiles: default
2018-08-25 15:56:38.844  INFO 48775 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@fade1fc: startup date [Sat Aug 25 15:56:38 CST 2018]; parent: org.springframework.context.annotation.AnnotationConfigApplicationContext@35047d03
2018-08-25 15:56:39.279  INFO 48775 --- [           main] o.s.cloud.context.scope.GenericScope     : BeanFactory id=58679be8-7007-3093-ab36-a79a968ce72d
2018-08-25 15:56:39.334  INFO 48775 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$ca5d5115] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2018-08-25 15:56:39.557  INFO 48775 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 1201 (http)
2018-08-25 15:56:39.562  INFO 48775 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2018-08-25 15:56:39.563  INFO 48775 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.15
2018-08-25 15:56:39.633  INFO 48775 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2018-08-25 15:56:39.633  INFO 48775 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 789 ms
2018-08-25 15:56:40.963  INFO 48775 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 1201 (http)
2018-08-25 15:56:40.968  INFO 48775 --- [           main] com.didispace.Application                : Started Application in 2.853 seconds (JVM running for 3.422)
2018-08-25 15:56:43.115  INFO 48775 --- [on(2)-127.0.0.1] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@3514843f: startup date [Sat Aug 25 15:56:43 CST 2018]; root of context hierarchy
2018-08-25 15:56:43.135  INFO 48775 --- [on(2)-127.0.0.1] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@3514843f: startup date [Sat Aug 25 15:56:43 CST 2018]; root of context hierarchy

上面的url會(huì)映射{application}-{profile}.properties對(duì)應(yīng)的配置文件,其中{label}對(duì)應(yīng)Git上不同的分支,默認(rèn)為master。我們可以嘗試構(gòu)造不同的url來(lái)訪問(wèn)不同的配置內(nèi)容,比如,要訪問(wèn)master分支,config-client應(yīng)用的dev環(huán)境,就可以訪問(wèn)這個(gè)url:http://localhost:1201/config-client-dev/dev/master ,并獲得如下返回:

{
    "name": "config-client-dev", 
    "profiles": [
        "dev"
    ], 
    "label": "master", 
    "version": null, 
    "state": null, 
    "propertySources": [
        {
            "name": "http://git.oschina.net/didispace/config-repo-demo/config-client-dev.yml", 
            "source": {
                "info.profile": "dev", 
                "info.from": "git"
            }
        }
    ]
}

我們可以看到該Json中返回了應(yīng)用名:config-client,環(huán)境名:dev,分支名:master,以及default環(huán)境和dev環(huán)境的配置內(nèi)容。

構(gòu)建客戶端

在完成了上述驗(yàn)證之后,確定配置服務(wù)中心已經(jīng)正常運(yùn)作,下面我們嘗試如何在微服務(wù)應(yīng)用中獲取上述的配置信息。

  • 創(chuàng)建一個(gè)Spring Boot應(yīng)用,命名為config-client,并在pom.xml中引入下述依賴:
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-config</artifactId>
    </dependency>
</dependencies>
  • 創(chuàng)建Spring Boot的應(yīng)用主類,具體如下:
@SpringBootApplication
@RestController
public class Application {

    @Value("${info.profile}")
    private String infoProfile;

    @Value("${test}")
    private String test;

    @RequestMapping(value = "/helloInfo")
    public void helloInfo(){
        System.out.println("info:" + infoProfile);
        System.out.println("test:" + test);
    }

    public static void main(String[]args) {

        new SpringApplicationBuilder(Application.class).web(true).run(args);

    }
}

  • 創(chuàng)建bootstrap.yml配置,來(lái)指定獲取配置文件的config-server-git位置,例如:
spring:
  application:
    name: config-client
  cloud:
    config:
      uri: http://localhost:1201/
      profile: default
      label: master

server:
  port: 2001

上述配置參數(shù)與Git中存儲(chǔ)的配置文件中各個(gè)部分的對(duì)應(yīng)關(guān)系如下:

  • spring.application.name:對(duì)應(yīng)配置文件規(guī)則中的{application}部分
  • spring.cloud.config.profile:對(duì)應(yīng)配置文件規(guī)則中的{profile}部分
  • spring.cloud.config.label:對(duì)應(yīng)配置文件規(guī)則中的{label}部分
  • spring.cloud.config.uri:配置中心config-server的地址

這里需要格外注意:上面這些屬性必須配置在bootstrap.properties中,這樣config-server中的配置信息才能被正確加載。

啟動(dòng)項(xiàng)目,打印部分日志如下:

2018-08-25 16:06:13.948  INFO 48793 --- [           main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@6f1de4c7: startup date [Sat Aug 25 16:06:13 CST 2018]; root of context hierarchy
2018-08-25 16:06:14.200  INFO 48793 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'configurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$fd4df81e] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.5.4.RELEASE)

2018-08-25 16:06:14.416  INFO 48793 --- [           main] c.c.c.ConfigServicePropertySourceLocator : Fetching config from server at: http://localhost:1201/
2018-08-25 16:06:15.335  INFO 48793 --- [           main] c.c.c.ConfigServicePropertySourceLocator : Located environment: name=config-client, profiles=[default], label=master, version=null, state=null
2018-08-25 16:06:17.132  INFO 48793 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Located managed bean 'refreshScope': registering with JMX server as MBean [org.springframework.cloud.context.scope.refresh:name=refreshScope,type=RefreshScope]
2018-08-25 16:06:17.137  INFO 48793 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Located managed bean 'configurationPropertiesRebinder': registering with JMX server as MBean [org.springframework.cloud.context.properties:name=configurationPropertiesRebinder,context=112f364d,type=ConfigurationPropertiesRebinder]
2018-08-25 16:06:17.141  INFO 48793 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Located managed bean 'refreshEndpoint': registering with JMX server as MBean [org.springframework.cloud.endpoint:name=refreshEndpoint,type=RefreshEndpoint]
2018-08-25 16:06:17.243  INFO 48793 --- [           main] o.s.c.support.DefaultLifecycleProcessor  : Starting beans in phase 0
2018-08-25 16:06:17.388  INFO 48793 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 2001 (http)
2018-08-25 16:06:17.392  INFO 48793 --- [           main] com.didispace.Application                : Started Application in 3.809 seconds (JVM running for 4.46)
2018-08-25 16:06:17.601  INFO 48793 --- [on(9)-127.0.0.1] c.c.c.ConfigServicePropertySourceLocator : Fetching config from server at: http://localhost:1201/
2018-08-25 16:06:17.809  INFO 48793 --- [on(9)-127.0.0.1] c.c.c.ConfigServicePropertySourceLocator : Located environment: name=config-client, profiles=[default], label=master, version=null, state=null

在完成了上面你的代碼編寫(xiě)之后,讀者可以將config-server-git、config-client都啟動(dòng)起來(lái),然后訪問(wèn)http://localhost:2001/info ,我們可以看到該端點(diǎn)將會(huì)返回從git倉(cāng)庫(kù)中獲取的配置信息:

{"profile":"default","from":"git1"}

訪問(wèn)helloInfo接口,看到打印日志如下:

info:default
test:bbb

參考:
http://blog.didispace.com/spring-cloud-starter-dalston-3/

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容