本文内容导航:

一、搭建配置服务中心(config server)

  1.1.git方式

  1.2.svn方式

  1.3.本地文件方式

  1.4.解决配置中包含中文内容返回乱码问题

二、搭建配置消费客户端(config client)

  2.1.通过@value方式获取配置信息

  2.2.通过创建一个映射远程配置信息的Bean(RemoteConfigProperties) 方式获取配置信息

  2.3.通过Environment来直接获取配置信息

  2.4.实现配置信息自动刷新

  2.5.加入到注册中心配置成高可用集群环境

上篇总结了熔断降级(Hystrix)与监控的使用方式,里面涉及到的一些重点的知识细节我都有说明,网上很多的spring cloud教程只是简单的贴代码、简单描述,而我的文章是要体现知识的积累与开发时的参考,故花了一些时间描述了一些细节,这些细节能帮助我自己(梦在旅途)以及大家少走弯路,本文仍然围绕这个中心思想来总结描述关于配置中心的搭建与使用,实现了多种搭建配置服务中心(config server),也实现了多种配置消费客户端的实现方式。(多种配置消费方式目前很少有人总结,而我在本文中有特别介绍,不一定都用得上,但应该要了解,以便举一反三灵活运用),好了废话不多说,直接开始本文主题。

首先我们要了解,为什么需要配置中心?配置中心能解决什么问题?回答这些问题可以参见:https://www.cnblogs.com/xiaoqi/p/configserver-compair.html,我这里简要说明一下:JAVA应用一般常用的配置文件是:xxx.Properties 或 xxx.yml文件,.NET(.NET CORE)一般常用的配置文件是:xxx.config 或 xxx.json 甚至是xxx.ini,它们都能够很好的应对单机本地配置的需求(可以多个应用共用同一个目录位置的配置文件),但如果是分布式应用,那么本地配置文件在某些场景下就显得不那么合适了,因为一是存在配置冗余(不同机器上配置相同的配置信息),二是无法快速同步配置信息(如果要更改配置信息,就得每台服务器一台一台的更改,或使用文件同步机制稍微能保证尽快同步),三是没有多版本管理,出现更新配置后有问题无法快速回滚(如有问题,需重新配置或人为将之前的备份的配置文件一台台服务器更新或文件同步到多台服务器),比如:数据库连接字符串,如果使用本地配置就存在如上说的三点问题,正因为存在这些问题,所以才有了分布式配置中心框架来解决这些问题。

分布式配置中心的主流框架有很多,由于本文是总结spring cloud系列的文章,故这里通过DEMO来实现分布式配置中心Server端及Client消费端(读取配置),并确保高可用。

一、搭建配置服务中心(config server)

  首先通过IDEA spring initializer(或直接通过https://start.spring.io/)创建一个spring boot项目(demo项目命名:configserver),创建过程中选择:config server依赖,生成项目后的POM XML文件如下:(如果缺少依赖请自行手动添加)

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <parent>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-parent</artifactId>
  8. <version>2.1.3.RELEASE</version>
  9. <relativePath/> <!-- lookup parent from repository -->
  10. </parent>
  11.  
  12. <groupId>cn.zuowenjun.cloud</groupId>
  13. <artifactId>configserver</artifactId>
  14. <version>0.0.1-SNAPSHOT</version>
  15. <name>configserver</name>
  16. <url>http://www.zuowenjun.cn</url>
  17. <description>Demo project for Spring Boot</description>
  18.  
  19. <properties>
  20. <java.version>1.8</java.version>
  21. <spring-cloud.version>Greenwich.RELEASE</spring-cloud.version>
  22. </properties>
  23.  
  24. <dependencies>
  25. <!--spring cloud配置中心依赖[默认GIT]-->
  26. <dependency>
  27. <groupId>org.springframework.cloud</groupId>
  28. <artifactId>spring-cloud-config-server</artifactId>
  29. </dependency>
  30. <dependency>
  31. <groupId>org.springframework.boot</groupId>
  32. <artifactId>spring-boot-starter-test</artifactId>
  33. <scope>test</scope>
  34. </dependency>
  35. </dependencies>
  36.  
  37. <dependencyManagement>
  38. <dependencies>
  39. <dependency>
  40. <groupId>org.springframework.cloud</groupId>
  41. <artifactId>spring-cloud-dependencies</artifactId>
  42. <version>${spring-cloud.version}</version>
  43. <type>pom</type>
  44. <scope>import</scope>
  45. </dependency>
  46. </dependencies>
  47. </dependencyManagement>
  48.  
  49. <build>
  50. <plugins>
  51. <plugin>
  52. <groupId>org.springframework.boot</groupId>
  53. <artifactId>spring-boot-maven-plugin</artifactId>
  54. <configuration>
  55. <jvmArguments>-Dfile.encoding=UTF-8</jvmArguments>
  56. </configuration>
  57. </plugin>
  58. </plugins>
  59. </build>
  60.  
  61. <repositories>
  62. <repository>
  63. <id>spring-milestones</id>
  64. <name>Spring Milestones</name>
  65. <url>https://repo.spring.io/milestone</url>
  66. </repository>
  67. </repositories>
  68.  
  69. </project>

  然后下面分别介绍通过三种方式来实现配置中心:(注意三种方式均使用上面的项目初始环境,下面不再介绍)

  1.1.git方式(即:将GIT仓库【GITHUB、GITLAB、 GITEE等】作为配置集中存储的介质)

    前提工作:既然是使用GIT仓库作为配置存储,那我们首先就得在相关的GIT站点上创建用于存放config信息的仓库,如我(梦在旅途)在自己的github上创建了一个learning-demos/config仓库目录,然后在config目录下分别创建两个环境的配置文件(http://configclient-dev.properties、http://configclient-prod.properties),配置文件命名规则应尽可能使用:{application}-{profile}.{properties|yml},如下是GIT中两个文件配置的演示内容:(演示仓库地址:https://github.com/zuowj/learning-demos

  1. --configclient-dev.properties内容:测试环境
  2.  
  3. demo-config-profile-env=dev
  4. zuowenjun.site=http://www.zuowenjun.cn,http://zuowj.cnblogs.com--20190226.AAAXX66
  5. zuowenjun.skills=.net,java,html,js,css,sql,python,vb--20190226.BBBXX66
  6. zuowenjun.motto=Learning is endless; Opportunity is for the prepared mind;--20190226.CCCXX1
  7.  
  8. --configclient-prod.properties内容:生产环境
  9.  
  10. demo-config-profile-env=prod
  11. zuowenjun.site=http://www.zuowenjun.cn,http://zuowj.cnblogs.com,http://github.com/zuowj
  12. zuowenjun.skills=.net,java,html,js,css,sql,python,vb
  13. zuowenjun.motto=Learning is endless; Opportunity is for the prepared mind;学无止境;机会是留给有准备的人

  1.1.1.在spring boot启动类(ConfigserverApplication)上添加@EnableConfigServer注解,代码如下:

  1. package cn.zuowenjun.cloud;
  2.  
  3. import org.springframework.boot.SpringApplication;
  4. import org.springframework.boot.autoconfigure.SpringBootApplication;
  5. import org.springframework.cloud.config.server.EnableConfigServer;
  6.  
  7. @EnableConfigServer
  8. @SpringBootApplication
  9. public class ConfigserverApplication {
  10.  
  11. public static void main(String[] args) {
  12. SpringApplication.run(ConfigserverApplication.class, args);
  13. }
  14.  
  15. }

  1.1.2.在配置文件(application.yml,当然也可以是application.properties看个人喜好,本系列均采用yml)中进行如下配置,重点关注spring.cloud.config节点,相关配置参数有注释说明:

  1. spring:
  2. application:
  3. name: configserver
  4. profiles:
  5. active: git #设置使用本地配置(默认是git,可以设置:subversion(SVN),native(本地))
  6. cloud:
  7. config:
  8. server:
  9. #如下是GIT配置
  10. git:
  11. uri: https://github.com/zuowj/learning-demos # 配置git仓库的地址(最后不需要带/,否则会出现:No custom http config found for URL: XXX)
  12. search-paths: config # git仓库地址下的相对搜索地址(可用使用通配符),可以配置多个,用,分割。可以{application}实现按应用查配置
  13. username: # git仓库的账号(公开仓库无需账号信息)
  14. password: # git仓库的密码(公开仓库无需账号信息)
  15. default-label: master #git默认分支

  通过上述简单的两步即完成搭建基于GIT的配置服务中心,启动运行项目,GIT仓库中的配置文件会被自动转换成当前项目的web api,若需访问查看远程配置数据可以参照以下的规则:

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

  规则简单说明:{application}=配置消费方应用名称(即:config client的项目名,通俗讲:就是谁用这个配置就是谁的名字),{profile}=配置环境(如:dev开发环境,test测试环境,prod生产环境),{label}=仓库分支名(git或svn方式指定,native本地方式无需指定),.yml|.properties|.json表示指定的响应返回格式,{}表示必需,[]表示可选,|表示或的关系,例如本Demo项目访问:

  http://localhost:8866/configclient/dev 、http://localhost:8866/configclient/dev/master

  http://localhost:8866/configclient-dev.yml、http://localhost:8866/configclient-dev.properties、http://localhost:8866/configclient-dev.json、http://localhost:8866/master/configclient-dev.yml

  最终可以根据访问URL规则返回相应的内容,类似如下:

  1. //request: http://localhost:8866/configclient-dev.yml
  2.  
  3. demo-config-profile-env: dev
  4. zuowenjun:
  5. motto: Learning is endless; Opportunity is for the prepared mind;--20190226.CCCXX1
  6. site: http://www.zuowenjun.cn,http://zuowj.cnblogs.com--20190226.AAAXX66
  7. skills: .net,java,html,js,css,sql,python,vb--20190226.BBBXX66
  8.  
  9. //request: http://localhost:8866/configclient-dev.properties
  10.  
  11. demo-config-profile-env: dev
  12. zuowenjun.motto: Learning is endless; Opportunity is for the prepared mind;--20190226.CCCXX1
  13. zuowenjun.site: http://www.zuowenjun.cn,http://zuowj.cnblogs.com--20190226.AAAXX66
  14. zuowenjun.skills: .net,java,html,js,css,sql,python,vb--20190226.BBBXX66
  15.  
  16. //request: http://localhost:8866/configclient-dev.json
  17. {"demo-config-profile-env":"dev","zuowenjun":{"motto":"Learning is endless; Opportunity is for the prepared mind;--20190226.CCCXX1","site":"http://www.zuowenjun.cn,http://zuowj.cnblogs.com--20190226.AAAXX66","skills":".net,java,html,js,css,sql,python,vb--20190226.BBBXX66"}}
  18.  
  19. //request: http://localhost:8866/configclient/dev
  20.  
  21. {"name":"configclient","profiles":["dev"],"label":null,"version":"d4616a65c8429b9dd3a67ff226b125ae6a0959bb","state":null,"propertySources":[{"name":"https://github.com/zuowj/learning-demos/config/configclient-dev.properties","source":{"zuowenjun.skills":".net,java,html,js,css,sql,python,vb--20190226.BBBXX66","zuowenjun.site":"http://www.zuowenjun.cn,http://zuowj.cnblogs.com--20190226.AAAXX66","demo-config-profile-env":"dev","zuowenjun.motto":"Learning is endless; Opportunity is for the prepared mind;--20190226.CCCXX1"}}]}

  可以看到GIT中的配置信息通过config server的API能够正常返回,表示搭建成功,另外需要注意的是如果配置文件中包含中文,那么可能中文返回的就是乱码了,上面如果浏览prod生产环境【生产环境我特意配置了中文】,如:http://localhost:8866/configclient/prod,那么中文就会乱码,解决方案后面会说明,此处了解有这个情况即可。

  1.2.svn方式(即:将SVN仓库作为配置集中存储的介质)

    前提工作:如同GIT方式一样,要使用SVN仓库作为配置存储,那就需要SVN服务器,将创建用于存放config信息的仓库,如我(梦在旅途)在SVN服务器创建了app-config仓库目录,然后在trunk主干中仍然添加两个配置文件(dev,prod)与GIT方式文件名相同,内容如下(内容与GIT方式也基本相同,只是稍微改变内容以便区分):(演示仓库地址:http://svnhost:port/svn/app-config/trunk)

  1. --configclient-dev.properties内容:
  2.  
  3. demo-config-profile-env=dev-svn
  4. zuowenjun.site=http://www.zuowenjun.cn,http://zuowj.cnblogs.com--20190227
  5. zuowenjun.skills=.net,java,html,js,css,sql,python,vb--20190227
  6. zuowenjun.motto=Learning is endless; Opportunity is for the prepared mind;--20190227
  7.  
  8. --configclient-prod.properties内容:
  9.  
  10. demo-config-profile-env=prod-svn
  11. zuowenjun.site=http://www.zuowenjun.cn,http://zuowj.cnblogs.com,http://github.com/zuowj
  12. zuowenjun.skills=.net,java,html,js,css,sql,python,vb
  13. zuowenjun.motto=Learning is endless; Opportunity is for the prepared mind;学无止境;机会是留给有准备的人

  1.2.1.由于GIT是默认的实现方式,当引入spring-cloud-config-server时,它就具备了相关的框架处理能力,而这里使用SVN,就需要在POM XML中除了添加config-server依赖外还需单独添加SVN实现方式的依赖,配置如下:

  1. <!--spring cloud配置中心依赖[默认GIT]-->
  2. <dependency>
  3. <groupId>org.springframework.cloud</groupId>
  4. <artifactId>spring-cloud-config-server</artifactId>
  5. </dependency>
  6. <!--使用SVN作为配置中心依赖-->
  7. <dependency>
  8. <groupId>org.tmatesoft.svnkit</groupId>
  9. <artifactId>svnkit</artifactId>
  10. </dependency>

  1.2.2.在配置文件(application.yml)中进行如下配置,仍然重点关注spring.cloud.config节点,相关配置参数有注释说明:

  1. server:
  2. port: 8866
  3.  
  4. spring:
  5. application:
  6. name: configserver
  7. profiles:
  8. active: subversion #设置使用本地配置(默认是git,可以设置:subversion(SVN),native(本地))
  9. cloud:
  10. config:
  11. server:
  12. #如下是SVN配置
  13. svn:
  14. uri: http://svnhost:port/svn/app-config #SVN仓库地址
  15. username: svnuser #SVN账号(如果没有权限可为空)
  16. password: svnpassword #SVN密码(如果没有权限可为空)
  17. default-label: trunk #默认SVN分支

  通过上述简单的两步即完成搭建基于SVN的配置服务中心,启动运行项目,SVN仓库中的配置文件会被自动转换成当前项目的web api,访问路径与GIT方式完全相同在此不重述。(参照1.1.2访问URL,可以得到SVN仓库trunk分支里配置文件配置信息的内容)

  1.3.本地文件方式(即:将config server项目所有服务器的本地文件存放目录作为配置集中存储的介质)

  1.3.1.先在config server项目文件服务器创建指定存放配置的目录,如本demo是直接创建在项目的resources/configs目录,仍然是创建与GIT相同的两个配置文件(dev、prod),配置内容如下:

  1. --configclient-dev.properties内容:
  2.  
  3. demo-config-profile-env=dev-native
  4. zuowenjun.site=http://www.zuowenjun.cn,http://zuowj.cnblogs.com--20190227
  5. zuowenjun.skills=.net,java,html,js,css,sql,python,vb--20190227
  6. zuowenjun.motto=Learning is endless; Opportunity is for the prepared mind;--20190227
  7.  
  8. --configclient-prod.properties内容:
  9.  
  10. demo-config-profile-env=prod-native
  11. zuowenjun.site=http://www.zuowenjun.cn,http://zuowj.cnblogs.com,http://github.com/zuowj
  12. zuowenjun.skills=.net,java,html,js,css,sql,python,vb
  13. zuowenjun.motto=Learning is endless; Opportunity is for the prepared mind;学无止境;机会是留给有准备的人

  1.3.2.在配置文件(application.yml)中进行如下配置,仍然重点关注spring.cloud.config节点,相关配置参数有注释说明:(很简单,只需要设置profiles.active=native,然后在native节点设置查找配置的存放目录即可)

  1. server:
  2. port: 8866
  3.  
  4. spring:
  5. application:
  6. name: configserver
  7. profiles:
  8. active: native #设置使用本地配置(默认是git,可以设置:subversion(SVN),native(本地))
  9. cloud:
  10. config:
  11. server:
  12. #如下是本地文件配置
  13. native:
  14. search-locations: classpath:/configs #配置文件存放的目录

  通过上述简单的两步即完成搭建基于本地文件的配置服务中心,启动运行项目,存放的配置文件会被自动转换成当前项目的web api,访问路径与GIT方式完全相同在此不重述。(参照1.1.2访问URL,可以得到本地文件配置信息的内容)

  1.4.解决配置中包含中文内容返回乱码问题(此处实现方式参照网上说明,在此只是集中说明,便于大家理解)--均适用于以上三种方式

  乱码原因及解决方案思路可参见:https://blog.csdn.net/sinat_38843093/article/details/79960777?utm_source=blogxgwz4,但由于最新版本的spring boot的PropertySourceLoader接口定义有些不同故我这里参照该文进行完善并最终解决乱码。

  首先自定义一个实现了PropertySourceLoader的类:MyPropertySourceLoader,并实现接口的方法逻辑,具体代码如下:(最重要的代码是:properties.load(new InputStreamReader(inputStream, StandardCharsets.UTF_8));即表示使用UTF8的字符集来读取配置文件流信息)

  1. package cn.zuowenjun.cloud;
  2.  
  3. import org.slf4j.Logger;
  4. import org.slf4j.LoggerFactory;
  5. import org.springframework.boot.env.PropertySourceLoader;
  6. import org.springframework.core.env.PropertiesPropertySource;
  7. import org.springframework.core.env.PropertySource;
  8. import org.springframework.core.io.Resource;
  9.  
  10. import java.io.IOException;
  11. import java.io.InputStream;
  12. import java.io.InputStreamReader;
  13. import java.nio.charset.StandardCharsets;
  14. import java.util.ArrayList;
  15. import java.util.List;
  16. import java.util.Properties;
  17.  
  18. public class MyPropertySourceLoader implements PropertySourceLoader {
  19. private Logger logger= LoggerFactory.getLogger(MyPropertySourceLoader.class);
  20.  
  21. @Override
  22. public String[] getFileExtensions() {
  23. return new String[]{"properties", "xml"};
  24. }
  25.  
  26. @Override
  27. public List<PropertySource<?>> load(String name, Resource resource) throws IOException {
  28. Properties properties=new Properties();
  29. InputStream inputStream=null;
  30. try{
  31. inputStream=resource.getInputStream();
  32. properties.load(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
  33. }catch (IOException ioEx){
  34. logger.error("load inputStream failed",ioEx);
  35. throw ioEx;
  36. }
  37. catch (Exception e){
  38. logger.error("load inputStream failed",e);
  39. }finally {
  40. if(inputStream!=null){
  41. inputStream.close();
  42. }
  43. }
  44.  
  45. List<PropertySource<?>> propertySourceList=null;
  46. if (!properties.isEmpty()) {
  47.  
  48. PropertiesPropertySource propertiesPropertySource = new PropertiesPropertySource(name, properties);
  49. propertySourceList= new ArrayList<>();
  50. propertySourceList.add(propertiesPropertySource);
  51. }
  52. return propertySourceList;
  53.  
  54. }
  55.  
  56. }

  然后在resources目录下创建META-INF目录,然后在该目录中创建spring.factories文件(这里spring boot的扩展配置文件),在该文件中输入如下内容即可:

  1. org.springframework.boot.env.PropertySourceLoader=cn.zuowenjun.cloud.MyPropertySourceLoader

若想了解spring.factories相关信息,可参考:https://blog.csdn.net/lvoyee/article/details/82017057 、 https://blog.csdn.net/boling_cavalry/article/details/83048588

 通过上述步骤,现在无论是哪种方式访问配置中心的API,若涉及中文都能正常返回不会乱码,如下图所示:(当然如果使用[/{label}]/{application}-{profile}{.yml|.properties|.json}这种方式访问可能还会出现乱码,具体原因我还未了解,求大神们指点,但目前已不影响配置消费【即:配置消费方获取到的中文信息均是正常不会乱码】)

  

二、搭建配置消费客户端(config client)

  首先通过IDEA spring initializer(或直接通过https://start.spring.io/)搭建spring boot + spring MVC(Rest API)空项目,创建过程中选择:web、config client依赖,最后生成的POM XML文件如下:(如果缺少依赖请自行手动添加)

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <parent>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-parent</artifactId>
  8. <version>2.1.3.RELEASE</version>
  9. <relativePath/> <!-- lookup parent from repository -->
  10. </parent>
  11. <groupId>cn.zuowenjun.cloud</groupId>
  12. <artifactId>configclient</artifactId>
  13. <version>0.0.1-SNAPSHOT</version>
  14. <name>configclient</name>
  15. <description>Demo project for Spring Boot</description>
  16.  
  17. <properties>
  18. <java.version>1.8</java.version>
  19. <spring-cloud.version>Greenwich.RELEASE</spring-cloud.version>
  20. </properties>
  21.  
  22. <dependencies>
  23. <!--spring MVC依赖-->
  24. <dependency>
  25. <groupId>org.springframework.boot</groupId>
  26. <artifactId>spring-boot-starter-web</artifactId>
  27. </dependency>
  28. <!--config client依赖-->
  29. <dependency>
  30. <groupId>org.springframework.cloud</groupId>
  31. <artifactId>spring-cloud-starter-config</artifactId>
  32. </dependency>
  33.  
  34. <!--ConfigurationProperties类所需依赖,手动添加的-->
  35. <dependency>
  36. <groupId>org.springframework.boot</groupId>
  37. <artifactId>spring-boot-configuration-processor</artifactId>
  38. <optional>true</optional>
  39. </dependency>
  40.  
  41. <dependency>
  42. <groupId>org.springframework.boot</groupId>
  43. <artifactId>spring-boot-starter-test</artifactId>
  44. <scope>test</scope>
  45. </dependency>
  46. </dependencies>
  47.  
  48. <dependencyManagement>
  49. <dependencies>
  50. <dependency>
  51. <groupId>org.springframework.cloud</groupId>
  52. <artifactId>spring-cloud-dependencies</artifactId>
  53. <version>${spring-cloud.version}</version>
  54. <type>pom</type>
  55. <scope>import</scope>
  56. </dependency>
  57. </dependencies>
  58. </dependencyManagement>
  59.  
  60. <build>
  61. <plugins>
  62. <plugin>
  63. <groupId>org.springframework.boot</groupId>
  64. <artifactId>spring-boot-maven-plugin</artifactId>
  65. </plugin>
  66. </plugins>
  67. </build>
  68.  
  69. <repositories>
  70. <repository>
  71. <id>spring-milestones</id>
  72. <name>Spring Milestones</name>
  73. <url>https://repo.spring.io/milestone</url>
  74. </repository>
  75. </repositories>
  76.  
  77. </project>

  然后在resources目录下创建bootstrap.yml文件,并在配置文件中添加如下内容:(如果想了解bootstrap与application配置文件两者的区别,请参见:https://www.cnblogs.com/BlogNetSpace/p/8469033.html

  1. server:
  2. port: 8008
  3.  
  4. spring:
  5. application:
  6. name: configclient
  7.  
  8. cloud:
  9. config:
  10. name: configclient #对应config server Url中的{application}
  11. profile: prod #配置环境,对应config server Url中的{profile}
  12. #label: trunk #配置分支(不配置则默认:git则是master,svn则是trunk),
  13. uri: http://localhost:8866 #配置中心地址

  最后下面分别介绍实现各种不同的配置消费(读取配置)方式:(注意均使用上面的项目初始环境,同时以下的几种服务配置消费方式均可同时并存在一个项目中)

  2.1.通过@value方式获取配置信息

    这种最为简单,网上也大部份是这种,我这里为了便于区分配置属性与controller本身使用了继承的方式(注意,我这里用继承而没有使用单独定义一个RemoteConfig配置类+Value,是因为经我验证发现将会影响配置自动刷新,具体原因还未查清,初步判断与加上@RefreshScope注解上生成的代理类有关系),代码结构更清晰,实现代码如下:

  1. package cn.zuowenjun.cloud.model;
  2.  
  3. import org.springframework.beans.factory.annotation.Value;
  4. import org.springframework.cloud.context.config.annotation.RefreshScope;
  5.  
  6. public abstract class RemoteConfig {
  7.  
  8. @Value("${demo-config-profile-env}")
  9. public String profileEnv;
  10.  
  11. @Value("${zuowenjun.site}")
  12. public String zwjSite;
  13.  
  14. @Value("${zuowenjun.skills}")
  15. public String zwjSkills;
  16.  
  17. @Value("${zuowenjun.motto}")
  18. public String zwjMotto;
  19. }
  20.  
  21. package cn.zuowenjun.cloud.Controller;
  22.  
  23. import cn.zuowenjun.cloud.model.RemoteConfig;
  24. import org.springframework.beans.factory.annotation.Autowired;
  25. import org.springframework.web.bind.annotation.RequestMapping;
  26. import org.springframework.web.bind.annotation.RestController;
  27.  
  28. import java.util.HashMap;
  29. import java.util.Map;
  30.  
  31. @RestController
  32. @RequestMapping("/demo")
  33. public class DemoController extends RemoteConfig {
  34.  
  35. @RequestMapping("/config/byval")
  36. public Object getRemoteConfigByValue(){
  37. Map<String,Object> model=new HashMap<>();
  38. model.put("getMode","@Value");
  39.  
  40. Map<String,String> remoteCgfMap=new HashMap<>();
  41. remoteCgfMap.put("profileEnv", this.profileEnv);
  42. remoteCgfMap.put("zwjSite", this.zwjSite);
  43. remoteCgfMap.put("zwjSkills",this.zwjSkills);
  44. remoteCgfMap.put("zwjMotto", this.zwjMotto);
  45.  
  46. model.put("remoteConfig",remoteCgfMap);
  47.  
  48. return model;
  49. }
  50.  
  51. }

  如上代码所示,我们只需在类成员字段上标记@Value注解,并指定要获取的配置中心上配置项的名称即可。运行项目,访问:http://localhost:8008/demo/config/byval,即可响应返回获取到的config信息,如下图示:

  2.2.通过创建一个映射远程配置信息的Bean(RemoteConfigProperties) 方式获取配置信息

  首先定义一个映射远程配置信息的Bean类:RemoteConfigProperties,该类中所有的属性名均需与配置中心上配置文件的配置内容相同(名字以及层级都需相同,若配置项名称有-,则配置类中请忽略直接拼接命名即可但需符合lowerCamelCase,如:demo-config-profile-env,则字段名为:demoConfigProfileEnv,如果属性中有点( . ),则应视为点后面的部分为下级,应再定义相关的配置映射类),该类完整代码如下:

  1. package cn.zuowenjun.cloud.model;
  2.  
  3. import org.springframework.boot.context.properties.ConfigurationProperties;
  4. import org.springframework.stereotype.Component;
  5.  
  6. @Component
  7. @ConfigurationProperties()//如果有前缀,则可以设置prefix=XXX
  8. public class RemoteConfigProperties {
  9.  
  10. private String demoConfigProfileEnv;
  11. private Zuowenjun zuowenjun;
  12.  
  13. public String getDemoConfigProfileEnv() {
  14. return demoConfigProfileEnv;
  15. }
  16.  
  17. public void setDemoConfigProfileEnv(String demoConfigProfileEnv) {
  18. this.demoConfigProfileEnv = demoConfigProfileEnv;
  19. }
  20.  
  21. public Zuowenjun getZuowenjun() {
  22. return zuowenjun;
  23. }
  24.  
  25. public void setZuowenjun(Zuowenjun zuowenjun) {
  26. this.zuowenjun = zuowenjun;
  27. }
  28.  
  29. public static class Zuowenjun {
  30.  
  31. private String site;
  32. private String skills;
  33. private String motto;
  34.  
  35. public String getSite() {
  36. return site;
  37. }
  38.  
  39. public void setSite(String site) {
  40. this.site = site;
  41. }
  42.  
  43. public String getSkills() {
  44. return skills;
  45. }
  46.  
  47. public void setSkills(String skills) {
  48. this.skills = skills;
  49. }
  50.  
  51. public String getMotto() {
  52. return motto;
  53. }
  54.  
  55. public void setMotto(String motto) {
  56. this.motto = motto;
  57. }
  58.  
  59. }
  60.  
  61. }

如上代码所示,属性字段名与配置项的命名保持一致,若有下级则定义下级的配置类,这里下级配置类(Zuowenjun)采用了内部静态类的方式(注意这里如果是内部类,一定是static,而不能是普通的class,因为内部普通类与内部静态类是有区别的,具体可参见:java 内部类和静态内部类的区别),也可以单独定义一个类,同时在配置类上标记了@ConfigurationProperties(这指明了该类是配置映射类),@Component这个不用说了吧就是表示能自动被spring IOC容器扫描并注册。

  然后在DemoController中增加字段注入该类:RemoteConfigProperties,并添加用于读取RemoteConfigProperties类中的配置信息的方法(getRemoteConfigByPropertiesBean),具体代码如下:(这里保留了@Value方式的代码)

  1. package cn.zuowenjun.cloud.Controller;
  2.  
  3. import cn.zuowenjun.cloud.model.RemoteConfig;
  4. import cn.zuowenjun.cloud.model.RemoteConfigProperties;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.cloud.context.config.annotation.RefreshScope;
  7. import org.springframework.core.env.Environment;
  8. import org.springframework.web.bind.annotation.RequestMapping;
  9. import org.springframework.web.bind.annotation.RestController;
  10.  
  11. import java.util.HashMap;
  12. import java.util.Map;
  13.  
  14. @RestController
  15. @RequestMapping("/demo")
  16. public class DemoController extends RemoteConfig {
  17.  
  18. @Autowired
  19. private RemoteConfigProperties remoteConfigProperties;
  20.  
  21. @RequestMapping("/config/byval")
  22. public Object getRemoteConfigByValue(){
  23. Map<String,Object> model=new HashMap<>();
  24. model.put("getMode","@Value");
  25.  
  26. Map<String,String> remoteCgfMap=new HashMap<>();
  27. remoteCgfMap.put("profileEnv", this.profileEnv);
  28. remoteCgfMap.put("zwjSite", this.zwjSite);
  29. remoteCgfMap.put("zwjSkills",this.zwjSkills);
  30. remoteCgfMap.put("zwjMotto", this.zwjMotto);
  31.  
  32. model.put("remoteConfig",remoteCgfMap);
  33.  
  34. return model;
  35. }
  36.  
  37. @RequestMapping("/config/byprops")
  38. public Object getRemoteConfigByPropertiesBean(){
  39. Map<String,Object> model=new HashMap<>();
  40. model.put("getMode","Properties Bean");
  41. model.put("remoteConfig",remoteConfigProperties);
  42. return model;
  43. }
  44.  
  45. }

  最后启动运行项目,访问:http://localhost:8008/demo/config/byprops,即可响应返回获取到的config信息,如下图示:

  2.3.通过Environment来直接获取配置信息

    其实上面2种方式底层都是使用这种方式来获取配置信息的只是包装了后大家无需关心而矣,核心是通过environment.getProperty方法来获取对应的配置信息的,这种方式只需在DemoController增加字段注入Environment的实例,然后添加一个从Environment获取配置信息的方法即可(getRemoteConfigByEnv),具体代码如下:(保留@Value方式、映射远程配置信息的Bean(RemoteConfigProperties) 方式)

  1. package cn.zuowenjun.cloud.Controller;
  2.  
  3. import cn.zuowenjun.cloud.model.RemoteConfig;
  4. import cn.zuowenjun.cloud.model.RemoteConfigProperties;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.cloud.context.config.annotation.RefreshScope;
  7. import org.springframework.core.env.Environment;
  8. import org.springframework.web.bind.annotation.RequestMapping;
  9. import org.springframework.web.bind.annotation.RestController;
  10.  
  11. import java.util.HashMap;
  12. import java.util.Map;
  13.  
  14. @RestController
  15. @RequestMapping("/demo")
  16. public class DemoController extends RemoteConfig {
  17.  
  18. @Autowired
  19. private Environment environment;
  20.  
  21. @Autowired
  22. private RemoteConfigProperties remoteConfigProperties;
  23.  
  24. @RequestMapping("/config/byval")
  25. public Object getRemoteConfigByValue(){
  26. Map<String,Object> model=new HashMap<>();
  27. model.put("getMode","@Value");
  28.  
  29. Map<String,String> remoteCgfMap=new HashMap<>();
  30. remoteCgfMap.put("profileEnv", this.profileEnv);
  31. remoteCgfMap.put("zwjSite", this.zwjSite);
  32. remoteCgfMap.put("zwjSkills",this.zwjSkills);
  33. remoteCgfMap.put("zwjMotto", this.zwjMotto);
  34.  
  35. model.put("remoteConfig",remoteCgfMap);
  36.  
  37. return model;
  38. }
  39.  
  40. @RequestMapping("/config/byprops")
  41. public Object getRemoteConfigByPropertiesBean(){
  42. Map<String,Object> model=new HashMap<>();
  43. model.put("getMode","Properties Bean");
  44. model.put("remoteConfig",remoteConfigProperties);
  45. return model;
  46. }
  47.  
  48. @RequestMapping("/config/byenv")
  49. public Object getRemoteConfigByEnv(){
  50. Map<String,Object> model=new HashMap<>();
  51. model.put("getMode","Environment");
  52.  
  53. Map<String,String> remoteCgfMap=new HashMap<>();
  54. remoteCgfMap.put("profileEnv", environment.getProperty("demo-config-profile-env"));
  55. remoteCgfMap.put("zwjSite", environment.getProperty("zuowenjun.site"));
  56. remoteCgfMap.put("zwjSkills", environment.getProperty("zuowenjun.skills"));
  57. remoteCgfMap.put("zwjMotto", environment.getProperty("zuowenjun.motto"));
  58.  
  59. model.put("remoteConfig",remoteCgfMap);
  60. return model;
  61. }
  62.  
  63. }

最后启动运行项目,访问:http://localhost:8008/demo/config/byenv,即可响应返回获取到的config信息,如下图示:

如上三种方式配置文件均不需要改变,如果需要访问不同的环境,不同的分支,则可以修改项目配置文件bootstrap.yml中对应的属性:profile、label等,至于配置中心(config server)使用的是哪种方式存储配置,配置消费端(config client)无需关心,只管用即可。

  2.4.实现配置信息自动刷新(可参见:)

  2.4.1.在controller类(DemoController)上添加@RefreshScope注解,简单就不贴代码

  2.4.2.在POM XML中添加actuator依赖,配置如下:

  1. <!--actuator监控功能所需依赖(内部包含refresh,动态刷新配置信息需要)-->
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-actuator</artifactId>
  5. </dependency>

  2.4.3.在项目配置文件(bootstrap.yml或application.yml都可以)添加如下配置内容:

  1. management:
  2. endpoints:
  3. web:
  4. exposure:
  5. include: "*" #暴露所有端口,也可以指定某一个环境(先management.endpoint.{profile}.enabled=true,然后这里指定这个{profile},多个用,分隔)

  通过上述两步即完成config client端的自动监听与刷新机制(刷新原理参见:https://blog.csdn.net/cml_blog/article/details/78411312

  这时可以启动运行项目,然后POST请求访问:http://localhost:8008/actuator/refresh,如果能正常响应结果没有报404就OK了,响应内容为空?没关系,因为只有当config server端的配置文件有更新,这时POST这个API时,即会检测并响应返回更新的配置项信息,这样config client内部即可进行配置的刷新工作。到目前还没有实现全自动刷新配置,因为config server端配置文件有更新,config client端并不会第一时间感知到,如果不去POST请求refresh API则不会更新,所以自动更新的关键是如何能够实现配置中心的配置文件一旦更改就能通知所有的配置消费端(config client)自动更新配置信息。如果采用github的方式,那么可以使用github仓库的Webhooks功能,具体操作位置如下图示:

设置webhooks后,只要这个存配置的GIT仓库发生改变,将针触发事件并回调refresh接口(当然可以封装一个通用接口,然后里面把所有的 config client都调refresh接口),config client端收到刷新请求后就会重新从config server中获取配置信息。

虽然webhooks能够解决自动刷新问题,但仍不够优美,比较好的实现方式是再结合spring cloud bus、mq实现更好的自动刷新所有config client,具体可参见:https://www.cnblogs.com/willpan-z/p/9483674.html 、 https://blog.csdn.net/wtdm_160604/article/details/83720391

  另外actuator还默认集成了健康检查功能,可访问:http://localhost:8866/actuator/health,即可看到响应结果,正常则为status=UP,否则可能是DOWN

  2.5.加入到注册中心配置成高可用集群环境

  思路:我们可以把服务配置中心(config server)与服务消费客户端(config client)均作为服务加入到注册中心里面,然后服务消费客户端(config client)通过注册中心根据服务配置中心(config server)的服务ID(应用名称)找到config server IP,然后请求该IP即可。

  前提:先把之前文章《玩转Spring Cloud之服务注册发现(eureka)及负载均衡消费(ribbon、feign)》中的eureka server项目正常启动;

  2.5.1.改造服务配置中心(config server),集成eureka client(这个我之前文章有说明)【操作步骤简要重述:先在POM XML中添加spring-cloud-starter-netflix-eureka-client依赖,然后在spring boot启动类上添加@EnableDiscoveryClient注解以便启用服务发现,最后在application.yml中添加eureka client的配置信息】,让其能够加入到注册中心中,如下是改造后的配置文件:(注释掉的是多种方式配置)--eureka 配置节点为新增

  1. server:
  2. port: 8866
  3.  
  4. spring:
  5. application:
  6. name: configserver
  7. profiles:
  8. active: native #设置使用本地配置(默认是git,可以设置:subversion(SVN),native(本地))
  9. cloud:
  10. config:
  11. server:
  12. #如下是GIT配置
  13. # git:
  14. # uri: https://github.com/zuowj/learning-demos # 配置git仓库的地址(最后不需要带/,否则会出现:No custom http config found for URL: XXX)
  15. # search-paths: config # git仓库地址下的相对搜索地址(可用使用通配符),可以配置多个,用,分割。可以{application}实现按应用查配置
  16. # username: # git仓库的账号(公开仓库无需账号信息)
  17. # password: # git仓库的密码(公开仓库无需账号信息)
  18. # default-label: master #git默认分支
  19.  
  20. #如下是SVN配置
  21. # svn:
  22. # uri: http://svnhost:port/svn/app-config #SVN仓库地址
  23. # username: svnuser #SVN账号(如果没有权限可为空)
  24. # password: svnpassword#SVN密码(如果没有权限可为空)
  25. # default-label: trunk #默认SVN分支
  26.  
  27. #如下是本地文件配置
  28. native:
  29. search-locations: classpath:/configs #配置文件存放的目录
  30.  
  31. eureka:
  32. client:
  33. serviceUrl:
  34. defaultZone: http://localhost:8800/eureka/

  2.5.2.改造服务消费客户端(config client),集成eureka client(同2.5.1的服务配置中心(config server),集成eureka client步骤),让其能够加入到注册中心中,以便可以通过注册中心根据服务配置中心(config server)的服务ID(应用名称)找到config server IP,这里的eureka相关配置应统一在bootstrap.yml中,完整配置如下:

  1. server:
  2. port: 8008
  3.  
  4. spring:
  5. application:
  6. name: configclient
  7.  
  8. cloud:
  9. config:
  10. name: configclient #对应config server Url中的{application}
  11. profile: prod #配置环境,对应config server Url中的{profile}
  12. #label: trunk #配置分支(不配置则默认:git则是master,svn则是trunk),
  13. #uri: http://localhost:8866 #配置中心地址
  14. discovery:
  15. enabled: true #启用服务发现
  16. service-id: configserver #指定要从eureka获取的config server的服务ID(即:configserverr的applicationName)
  17.  
  18. eureka:
  19. client:
  20. serviceUrl:
  21. defaultZone: http://localhost:8800/eureka/

如上配置,重点是spring.cloud.config.uri不再指定固定的config server IP,而是改成配置spring.cloud.config.discovery【服务发现】,eureka配置节点与所有eureka client基本相同不再重述。

都改造完成后,信次先后启动运行:服务配置中心(config server)【可以运多个实例以不同的端口号】、服务消费客户端(config client),发现一切都正常,当服务配置中心(config server)某个实例断开仍不影响服务消费客户端(config client),这样就实现了高可用了。

好了,有关spring cloud config 总结就写到这里了,很多细节若需深究的话还有很多,后面项目中有实际用到再补充总结吧。文中若有不足,欢迎指出,码字不易,请多支持,谢谢!  

分享可参考链接:

https://springcloud.cc/spring-cloud-config.html

https://blog.csdn.net/qq_20597727/article/details/82465069

提示:本文相关示例项目代码均已上传到GITHUB,地址如下:

https://github.com/zuowj/learning-demos/tree/master/java/demo-configserver

https://github.com/zuowj/learning-demos/tree/master/java/demo-configclient

玩转Spring Cloud之配置中心(config server &config client)的更多相关文章

  1. Spring Cloud之配置中心搭建

    一.配置中心服务端搭建 1)引入相关Maven坐标 <dependency> <groupId>org.springframework.cloud</groupId> ...

  2. spring cloud分布式配置中心案例

    这里仍然以Windows.jdk和idea为开发环境,按照下面的步骤打包-运行-访问就能看到效果:启动注册中心:java -jar F:\jars-config\register-0.0.1-SNAP ...

  3. spring cloud 加入配置中心后的 部分 配置文件优先级

    经过一个小时的实验,得出部分配置优先级如下: bootstrap.properties:位于jar包外的优先级最高 application.properties:配置中心的文件 > 命令行配置 ...

  4. 玩转Spring Cloud之服务注册发现(eureka)及负载均衡消费(ribbon、feign)

    如果说用Spring Boot+Spring MVC是开发单体应用(或单体服务)的利器,那么Spring Boot+Spring MVC+Spring Cloud将是开发分布式应用(快速构建微服务)的 ...

  5. 玩转Spring Cloud之API网关(zuul)

    最近因为工作原因,一直没有空写文章,所以都是边忙项目,边利用空闲时间,周末时间学习总结,最终在下班回家后加班加点写完本篇文章,若有不足之处,还请谅解,谢谢! 本文内容导航: 一.网关的作用 二.网关与 ...

  6. Spring Cloud Eureka 注册中心集群搭建,Greenwich 最新版!

    Spring Cloud 的注册中心可以由 Eureka.Consul.Zookeeper.ETCD 等来实现,这里推荐使用 Spring Cloud Eureka 来实现注册中心,它基于 Netfl ...

  7. 玩转Spring Cloud之熔断降级(Hystrix)与监控

    本文内容导航目录: 前言:解释熔断降级一.搭建服务消费者项目,并集成 Hystrix环境 1.1.在POM XML中添加Hystrix依赖(spring-cloud-starter-netflix-h ...

  8. spring cloud 2.x版本 Eureka Server服务注册中心教程

    本文采用Spring cloud本文为2.1.8RELEASE,version=Greenwich.SR3 1.创建服务注册中心 1.1 新建Spring boot工程:eureka-server 1 ...

  9. 玩转Spring Boot 自定义配置、导入XML配置与外部化配置

    玩转Spring Boot 自定义配置.导入XML配置与外部化配置       在这里我会全面介绍在Spring Boot里面如何自定义配置,更改Spring Boot默认的配置,以及介绍各配置的优先 ...

随机推荐

  1. [Noi2015]软件包管理器 BZOJ4196

    分析:水题 每次安装的时候和根节点求lca的过程中区间覆盖+区间查询 每次删除的时候查询子树中安装的数量+区间覆盖 附上代码: #include <cstdio> #include < ...

  2. 三元运算符 与 return

    有三元运算符可以很好的代替if else简单语句 但是在使用的时候发现 与 return使用的时候 需要用这种形式 错误形式: $a ? return 1 ? return 0; 正确形式: retu ...

  3. 如何将markdown转换为wxml

    话说我要为技术博客写一个小程序版,我的博客解决方案是 hexo + github-page,格式当然是技术控们喜欢的 markdown 了 .但小程序使用的却是独有的模版语言 WXML.我总不能把之前 ...

  4. 我是庖丁,<肢解IOT平台>之物模型

    前言 物模型是对设备在云端的功能描述,包括设备的属性,数据,服务和事件. 物联网平台通过定义一种物的描述语言来描述物模型,称之为 TSL(即 Thing Specification Language) ...

  5. API 测试的具体实现

    目录 API 测试的具体实现 基于 Spring Boot 构建的 API 使用 cURL 命令行工具进行测试 使用图形界面工具 Postman 进行测试 如何应对复杂场景的 API 测试? 总结 A ...

  6. Bagging之随机森林

    随机森林(Random Forest)是一种Bagging(Bootstrap Aggregating)集成算法,在样本随机(样本扰动)的基础上,进一步运用特征随机(属性扰动)的机制,得到比一般的Ba ...

  7. 从git仓库导入idea的gradle项目无法添加依赖包问题

    引言 之前将项目导入到git仓库,后来同事从git仓库将项目导入到本地,发现无法导入依赖包. 解决方法 这个勾idea是默认勾上的,意思是idea将默认使用本地离线工作模式,使用的是本地仓库,每次依赖 ...

  8. Dubbo Mesh 在闲鱼生产环境中的落地实践

    本文作者至简曾在 2018 QCon 上海站以<Service Mesh 的本质.价值和应用探索>为题做了一次分享,其中谈到了 Dubbo Mesh 的整体发展思路是“借力开源.反哺开源” ...

  9. Docker最全教程之Go实战,墙裂推荐(十八)

    前言 与其他语言相比,Go非常值得推荐和学习,真香!为什么?主要是可以直接编译成机器代码(性能优越,体积非常小,可达10来M,见实践教程图片)而且设计良好,上手门槛低.本篇主要侧重于讲解了Go语言的优 ...

  10. Spring Cloud Alibaba基础教程:Nacos的集群部署

    继续说说生产环境的Nacos搭建,通过上一篇<Spring Cloud Alibaba基础教程:Nacos的数据持久化>的介绍,我们已经知道Nacos对配置信息的存储原理,在集群搭建的时候 ...