分布式配置中心(SpringCloud Config)
Server
pom文件依赖
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-config-server</artifactId> </dependency>
启用ConfigServer
import org.springframework.cloud.config.server.EnableConfigServer; @SpringBootApplication @EnableConfigServer public class ConfigserverApplication
配置application.properties
spring.application.name=config-server server.port=8888 spring.cloud.config.server.git.uri=http://xxx.com/xxx/springcloudConfig.git //如果能访问GitHub,可以使用GitHub地址,这里使用私有仓地址 spring.cloud.config.server.git.searchPaths=repo //配置文件存放路径 spring.cloud.config.label=master //配置仓库的分支 spring.cloud.config.server.git.username=xxx //访问Git仓库的用户名 spring.cloud.config.server.git.password=xxx //访问Git仓库的密码
在仓库中存在/repo/config-client-dev.properties,内容为:
foo=foo version 2 //注意这里=号前后不能有空格,否则如果文件编码错误,会导致foo键乱码,后面因无法找到foo而使用@Value注入异常
浏览器访问http://localhost:8888/foo/dev
http请求地址和资源文件映射为:
/{application}-{profile}.properties
/{application}-{profile}.yml
/{label}/{application}-{profile}.properties
/{label}/{application}-{profile}.yml
/{application}/{profile}[/{label}]
Client
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>
配置文件bootstrap.properties
spring.application.name=config-client
server.port=8881
spring.cloud.config.label=master
spring.cloud.config.profile=dev
spring.cloud.config.uri=http://localhost:8888/
提供接口显示注入的配置属性
@SpringBootApplication @RestController public class ConfigClientApplication { public static void main(String[] args) { SpringApplication.run(ConfigClientApplication.class, args); } @Value("${foo}") String foo; @RequestMapping(value = "/hi") public String hi(){ return foo; } }
启动config-client报@Value("$foo")注入有问题的,折腾了一下午加一晚上,终于找到问题了。
最坑的地方在于config-client-dev.properties里foo = foo version 2带空格,而且这个properties文件还是ISO-8859-1编码,导致访问http://localhost:8888/foo/dev的时候,显示{"name":"foo","profiles":["dev"],"label":null,"version":"83864280731a50d4cc9c6bdbcf42b70dd60e1616","state":null,"propertySources":[]},看着是正常的,但实际上访问http://localhost:8888/config-client/dev时,就会把变量名称和变量值也显示出来,发现foo是带乱码的,当然@Value注入就找不到foo啦。解决办法是把空格去掉就好了。最好是把properties改成UTF-8编码。

浙公网安备 33010602011771号