Spring Cloud Config(二)

Config 客户端
引入 config 客户端依赖

<!-- spring cloud config 客户端 -->
<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring-cloud-starter-config</artifactId>
</dependency>

application.properties 加上配置,指向配置中心

# spring cloud config 配置
spring.config.import=configserver:http://localhost:8080
# 必填,并且填写要正确
spring.cloud.config.name=config-server
spring.cloud.config.label=master
# 激活 config 服务的 test 配置
spring.cloud.config.profile=test

sys.user.name=defaultUserName
sys.user.age=defaultUserAge

Controller 查询配置数据

	@Value("${sys.user.name}")
	private String userName;
	
	@Value("${sys.user.age}")
	private String userAge;
	
	@RequestMapping(value = "name", method = RequestMethod.GET)
	public String getUserName() {
		return userName + " " + userAge;
	}

访问 http://localhost/name
返回结果 lao wang test 25

修改 config-server-test.yml age 改为 26,提交并pull。
刷新页面 http://localhost/name,结果没有变更。

实现自动刷新
Spring Cloud Config 是在项目启动的时候加载的配置内容,导致了它存在一个缺陷,配置文件修改后,需要重启服务才能生效。这也是我们之前说的第二个痛点。
为了解决这个痛点,它提供了一个刷新机制,但是需要我们主动出发。那就是 @RefreshScope 注解并结合 actuator 。

引入监视器

<!-- 引入监视器 -->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

加入配置,暴露端点

# display application health info
management.endpoint.health.show-details=always
management.endpoint.shutdown.enabled=false
# display all info
management.endpoints.web.exposure.include=*

Controller 加上注解 @RefreshScope

postman 用 post 请求刷新 http://localhost/actuator/refresh
刷新页面 http://localhost/name,结果变更了。

如果每次配置文件修改后,都需要我们主动发送post请求触发更新,这明显有点不太方便。而且如何客户端比较多的话,一个一个的手动刷新也比较耗时。这个时候,我们可以借助Spring Cloud Bus的广播功能,参考Spring Cloud Bus 文章。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值