nacos客户端配置刷新
上一节给大家介绍了nacos客户端(也就是我们的业务微服务)在启动的时候,怎样实现配置从nacos配置中心加载。本节为大家介绍一下当配置发生变更的时候,如何动态的通知并刷新服务的配置数据。
本文档之前已经为大家介绍过apollo、Spring Cloud config,其实nacos的客户端代码实现方法,并没有和之前的二者有很大的差异。所以本节内容就不做过多的细节说明,可以参考《apollo实例配置热更新》和《config 客户端配置刷新》进行学习。
# 一、问题:
- 哪些配置可以刷新,那些配置不能刷新?参考《apollo实例配置热更新》和《config 客户端配置刷新》进行学习
- 支持使用哪些Spring 注解来实现配置的动态刷新?
@Value
和@ConfigurationProperties
- 是不是我们讲过的所有配置管理中心平台下,
@Value
和@ConfigurationProperties
都需要配合@RefreshScope
注解才能实现动态刷新?大体上是的,但有例外。
配置管理平台 | Value | ConfigurationProperties |
---|---|---|
nacos | 需要结合RefreshScope才能生效 | 需要结合RefreshScope才能生效 |
apollo | 不需要结合RefreshScope就能生效(例外) | 需要结合RefreshScope才能生效 |
spring cloud config | 需要结合RefreshScope才能生效 | 需要结合RefreshScope才能生效 |
下面两个例子都可以将nacos配置"user.init.password"键对应的值热更新到password和defaultPwd对象上。这两个注解需要结合@RefreshScope
注解使用才能使配置动态更新生效。
@RefreshScope //这里需要加上RefreshScope注解
@ConfigurationProperties(prefix = "user.init")
public class User{
private String password;
}
2
3
4
5
下文中会针对这种@Value注解的方法为例进行讲解。
@RefreshScope //这里需要加上RefreshScope注解
public class Xxxxx{
@Value("${user.init.password}")
private String defaultPwd;
}
2
3
4
5
# 二、使微服务客户端具备配置刷新能力
# 2.1.nacos发布配置
添加一个配置:user.init.password=12345678
# 2.3.修改代码实现配置动态刷新
在需要进行配置刷新的类上使用@RefreshScope
,user.init.password对应的配置对象defaultPwd的值就具备了刷新的能力。
@Service
@RefreshScope
public class SysuserService {
@Value("${user.init.password}")
private String defaultPwd;
public void pwdreset(Integer userId){
if(userId == null){
throw new CustomException(CustomExceptionType.USER_INPUT_ERROR,
"重置密码必须带主键");
}else{
SysUser sysUser = sysUserMapper.selectByPrimaryKey(userId);
//String defaultPwd = dbLoadSysConfig.getConfigItem("user.init.password");
sysUser.setPassword(passwordEncoder.encode(defaultPwd));
sysUserMapper.updateByPrimaryKeySelective(sysUser);
smsService.send(sysUser.getPhone(),"您好,管理员已经将您的密码重置为" + defaultPwd);
}
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# 三、配置动态刷新测试
使用postman向“/sysuser/pwd/reset”接口发送请求
端点如图所示
去nacos配置中心修改
user.init.password
的值为Abcd1234,再次通过postman发送请求
在以上的过程中,我们没有重启服务,就实现了配置在nacos中修改之后,服务自动更新配置所对应的对象的数据。
# 总结:
方式一:yaml中开启 refresh-enabled=true 时(默认开启),通过applicationContext.getEnvironment.getProperty 直接获取
方式二:standalone使用,@NacosValue获取最新值nacos配置信息需要写在配置类上
方式三:结合springcloud ,@Value获取最新值一定要加@RefreshScope注解,配置文件中配置refresh: true