Eureka配置客户端

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

配套代码

参考博客

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值