继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

Spring Cloud构建微服务架构:分布式配置中心

海绵宝宝撒
关注TA
已关注
手记 270
粉丝 39
获赞 123

Spring Cloud构建微服务架构:分布式配置中心


简介

Spring Cloud Config是Spring Cloud团队创建的一个全新项目,用来为分布式系统中的基础设施和微服务应用提供集中化的外部配置支持,它分为服务端与客户端两个部分。其中服务端也称为分布式配置中心,它是一个独立的微服务应用,用来连接配置仓库并为客户端提供获取配置信息、加密/解密信息等访问接口;而客户端则是微服务架构中的各个微服务应用或基础设施,它们通过指定的配置中心来管理应用资源与业务相关的配置内容,并在启动的时候从配置中心获取和加载配置信息。Spring Cloud Config实现了对服务端和客户端中环境变量和属性配置的抽象映射,所以它除了适用于Spring构建的应用程序之外,也可以在任何其他语言运行的应用程序中使用。由于Spring Cloud Config实现的配置中心默认采用Git来存储配置信息,所以使用Spring Cloud Config构建的配置服务器,天然就支持对微服务应用配置信息的版本管理,并且可以通过Git客户端工具来方便的管理和访问配置内容。当然它也提供了对其他存储方式的支持,比如:SVN仓库、本地化文件系统。

在本文中,我们将学习如何构建一个基于Git存储的分布式配置中心,并对客户端进行改造,并让其能够从配置中心获取配置信息并绑定到代码中的整个过程。

准备配置仓库

  • 准备一个git仓库,可以在码云或Github上创建都可以。比如本文准备的仓库示例:http://git.oschina.net/didispace/config-repo-demo

  • 假设我们读取配置中心的应用名为config-client,那么我们可以在git仓库中该项目的默认配置文件config-client.yml:

info:
  profile: default
  from: git1
  
test: bbb
  • 为了演示加载不同环境的配置,我们可以在git仓库中再创建一个针对dev环境的配置文件config-client-dev.yml:

info:
  profile: dev  from: git

构建配置中心

通过Spring Cloud Config来构建一个分布式配置中心非常简单,只需要三步:

  • 创建一个基础的Spring Boot工程,命名为:config-server-git,并在pom.xml中引入下面的依赖(省略了parent和dependencyManagement部分):

<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-config-server</artifactId>
    </dependency></dependencies>
  • 创建Spring Boot的程序主类,并添加@EnableConfigServer注解,开启Spring Cloud Config的服务端功能。

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

}
  • 在application.yml中添加配置服务的基本信息以及Git仓库的相关信息,例如:

spring  application:
    name: config-server  cloud:
    config:
      server:
        git:
          uri: http://git.oschina.net/didispace/config-repo-demo/server:
  port: 1201

到这里,使用一个通过Spring Cloud Config实现,并使用Git管理配置内容的分布式配置中心就已经完成了。我们可以将该应用先启动起来,确保没有错误产生,然后再尝试下面的内容。

如果我们的Git仓库需要权限访问,那么可以通过配置下面的两个属性来实现;spring.cloud.config.server.git.username:访问Git仓库的用户名spring.cloud.config.server.git.password:访问Git仓库的用户密码

完成了这些准备工作之后,我们就可以通过浏览器、POSTMAN或CURL等工具直接来访问到我们的配置内容了。访问配置信息的URL与配置文件的映射关系如下:

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

  • /{application}-{profile}.yml

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

  • /{application}-{profile}.properties

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

项目启动部分日志如下:

/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 hierarchy2018-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会映射{application}-{profile}.properties对应的配置文件,其中{label}对应Git上不同的分支,默认为master。我们可以尝试构造不同的url来访问不同的配置内容,比如,要访问master分支,config-client应用的dev环境,就可以访问这个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中返回了应用名:config-client,环境名:dev,分支名:master,以及default环境和dev环境的配置内容。

构建客户端

在完成了上述验证之后,确定配置服务中心已经正常运作,下面我们尝试如何在微服务应用中获取上述的配置信息。

  • 创建一个Spring Boot应用,命名为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>
  • 创建Spring Boot的应用主类,具体如下:

@SpringBootApplication@RestControllerpublic 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);

    }
}
  • 创建bootstrap.yml配置,来指定获取配置文件的config-server-git位置,例如:

spring:
  application:
    name: config-client
  cloud:
    config:
      uri: http://localhost:1201/
      profile: default
      label: master

server:
  port: 2001

上述配置参数与Git中存储的配置文件中各个部分的对应关系如下:

  • spring.application.name:对应配置文件规则中的{application}部分

  • spring.cloud.config.profile:对应配置文件规则中的{profile}部分

  • spring.cloud.config.label:对应配置文件规则中的{label}部分

  • spring.cloud.config.uri:配置中心config-server的地址

这里需要格外注意:上面这些属性必须配置在bootstrap.properties中,这样config-server中的配置信息才能被正确加载。

启动项目,打印部分日志如下:

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

在完成了上面你的代码编写之后,读者可以将config-server-git、config-client都启动起来,然后访问http://localhost:2001/info ,我们可以看到该端点将会返回从git仓库中获取的配置信息:

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

webp

访问helloInfo接口,看到打印日志如下:

info:defaulttest:bbb

webp



作者:it_zzy
链接:https://www.jianshu.com/p/7e05fe45ac0e


打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP