springcloud config 提取公共参数
每个微服务都有自己的配置文件application-local.yml和bootstrap.yml, 这个两个配置文件的读取顺序是先读取bootstrap.yml文件,在读取application-local.yml文件,参数名相同,则后者覆盖前者。
提取公共参数是因为,eureka、zipkin等配置都是一样的,每一个微服务都要进行配置,很繁琐,而且配置一多,就心烦。
提取公共配置参数,要借助Spring Cloud Config,我这里是把配置文件放在了gitlab上,当然你也可以放在GitHub和其他相关的代码托管平台上。如下图
spring cloud config 官网里有这么一段话:
With file-based (git, svn, and native) repositories, resources with file names in application*
(application.properties
, application.yml
, application-*.properties
, and so on) are shared between all client applications. You can use resources with these file names to configure global defaults and have them be overridden by application-specific files as necessary.
The #_property_overrides[property overrides] feature can also be used for setting global defaults, with placeholders applications allowed to override them locally.
也就是说gitlab上的application-local.yml和application-test.yml可以作为全局的配置文件,后面的-test和-local是作为占位符一样的存在。
占位符就是运行环境,dev、test、pro等,当然也可以自己制定名字,记得在读取config文件时指定好。就是下图中profile:local的配置项。
一定要分清读取顺序:
首先会读取bootstrap.yml里面的参数,
然后会读取gitlab上application.yml上的配置,
最后读取微服务本地的application.yml文件。
参数名相同,后者覆盖前者。
我本地的配置文件如下图:
这样你就可以把通用的公共配置参数提取到gitlab上的application文件上了,根据环境指定运行时要读取的文件,也就是占位符(-test、-local)