SpringCloud Greenwich
版本集成 Config Client
(注册到Eureka Serever
)
添加相关依赖
- 加依赖
<!-- 注册到 Eureka Server 时需要添加的依赖 start -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!-- 注册到 Eureka Server 时需要添加的依赖 end -->
<!-- ConfigClient start -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<!-- ConfigClient end -->
注: 需要添加 spring-boot-starter-web
否则启动会失败
添加配置文件
- 配置
application.yml
server:
port: 3011
- 新建
bootstrap.yml
spring:
application:
name: microservice-foo # 对应 config server 所获取的配置文件的 {application}
cloud:
config:
uri: http://localhost:3001/ # profile 对应 config server 所获取的配置文件中的 {profile}
profile: dev # profile 对应 config 所获取的配置文件中的 {profile}
label: master # 指定Git 仓库的分支,对应 config server 所获取的配置文件的 {label}
# discovery:
# enabled: true # 是否从配置中心读取文件
# service-id: microservice-config-server # 服务名
eureka:
client:
serviceUrl:
defaultZone: http://localhost:1001/eureka/
yml
spring.application.name
: 对应的config server
所获取的配置文件的{application}
spring.cloud.uri
: 指定Config Server
的地址,默认是http://localhost:8888
spring.cloud.config.profile
:profile
对应Config Server
所获取配置文件的{profile}
spring.cloud.config.label
:指定Git
仓库的分支,对应Config Server
所获取配置文件的{label}
[KEY POINT]:
-
注意属性配置文件,以上属性为
bootstrap.yml
文件内容而不是application.yml
文件.如果配置在application.yml
中,改部分配置就不能获取配置的正确值.例如:applicaiton.yml
默认spring.cloud.config.uri
的默认值是http://localhost:8888
,而并非是http://localhost:3011
-
SpringCloud
有一个 "引导上下文" 的概念,这是主应用程序上下文(Application Context) 的父上下文。引导上下文负责从配置服务器加载配置属性,一级解密外部配置文件中的属性。和主应用程序加载application.*
(yml或properties)中的属性不同,引导上下文加载bootstrap.*
中的属性。配置在bootstrap.*
中的属性优先级更高,因此默认情况下他们不能被而本地配置覆盖
从API
接口验证是否能够正确获取自定义配置
@RestController
public class ConfigClientConfigController {
// 获取 Config Server 配置文件中的 spring.cloud.config.profile属性值
@Value("${spring.cloud.config.profile}")
private String profile;
@GetMapping("/profile")
public String getProfile(){
return this.profile;
}
}
注: 如果需要注册到Eureka
,需要在启动类SpringcloudConfigClientApplication
上添加@EnableEurekaClient
注解(注册到Eureka Server
)
测试
访问地址: http://localhost:3011/profile