一 介绍
本篇来讨论Spring Cloud微服务如何获取配置信息。下面编写一个微服务,该微服务整合了Config Client。
二 新建项目microservice-config-client,并为项目添加以下依赖
<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启动类
package com.itmuch.cloud.study;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ConfigClientApplication {
public static void main(String[] args) {
SpringApplication.run(ConfigClientApplication.class, args);
}
}
四 编写配置文件application.yml,并在其中添加如下内容
server:
port: 8081
五 创建配置文件bootstrap.yml,并在其中添加如下内容
spring:
application:
name: microservice-foo # 对应config server所获取的配置文件的{application}
cloud:
config:
uri:http://localhost:8080/
profile: dev # profile对应config server所获取的配置文件中的{profile}
label: master # 指定Git仓库的分支,对应config server所获取的配置文件的{label}
其中:
spring.application.name:对应config server所获取的配置文件的{application}。
spring.cloud.config.uri:指定Config Server的地址,默认是
http://localhost:8888。
spring.cloud.config.profile:profile对应config server所获取的配置文件中的{profile}。
spring.cloud.config.label:指定Git仓库的分支,对应config server所获取的配置文件的{label}。
值的注意的是:以上属性应配置在bootstrap.yml,而不是application.yml。如果配置在application.yml,该部分属性就不能正常工作。例如,Config Client会连接spring.cloud.config.uri的默认值是
http://localhost:8888,而并非配置的
http://localhost:8080.
Spring Cloud有一个“引导上下文”的概念,这是主应用程序的父上下文。引导上下文负责从配置服务器加载配置属性,以及解密外部配置文件中的属性。和主应用程序加载application.yml的属性不同,引导上下文加载bootstrap.*中的属性。配置在bootstrap.*中的属性有更高的优先级,因此默认情况下它们不能被本地配置覆盖。
如需要禁用引导过程,可设置spring.cloud.bootstrap.enabled=false
六 编写Controller
package com.itmuch.cloud.study.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ConfigClientController {
@Value("${profile}")
private String profile;
@GetMapping("/profile")
public String hello() {
return this.profile;
}
}
在Controller中,通过注解@Value("${profile}"),绑定Git仓库配置文件中的profile属性。
七 测试
1 启动microservice-config-server
2 启动microservice-config-client
3 访问http://localhost:8081/profile,可获得如下结果。
dev-1.0
说明Config Client能够正常通过Config Server获得Git仓库中对应环境的配置。