现象
某某公司希望在nacos中可以动态配置黑白名单,例如域名白名单,对在白名单的允许从本站跳转,不在白名单的不允许从本站跳转。
WhiteListConfig类@PostConstruct标记的init方法就是希望只在项目启动时执行,后续不执行。以后改动配置被触发的是onEventChange方法,从而近实时的加载白名单。
But,事与愿违。
在每次修改nacos配置后,onEventChange方法被调用,init方法同样会被调用。
代码示例如下:
@Slf4j
@Data
@Component
@ConfigurationProperties(prefix = WhiteListConfig.PREFIX)
public class WhiteListConfig {
public static final String PREFIX = "abc.link";
private List<String> whiteList;
@Autowired
private NacosConfigProperties nacosConfigProperties;
@PostConstruct
private void init() {
log.info("---->>>init white list, {}", this);
refreshWhiteList();
}
@EventListener(value = {
EnvironmentChangeEvent.class})
public void onEventChange(EnvironmentChangeEvent event) {
Set<String> keys = CollectionUtil.emptyIfNull(event.getKeys());
boolean inKeySet = keys.stream().anyMatch(ele -> StrUtil.startWith(ele, PREFIX + ".white-list"));
if (!inKeySet) {
return;
}
refreshWhiteList();
}
private void refreshWhiteList() {
Map<String, String> properties = EnvironmentUtils.getSubProperties(nacosConfigProperties.getEnvironment(), PREFIX + ".white-list");
List<String> newWhiteList = MapUtil.emptyIfNull(properties).entrySet().stream()
.filter(ele -> StrUtil.isNotBlank(ele.getValue()))
.sorted(Map.Entry.comparingByKey())
.map(Map.Entry::getValue)
.collect(Collectors.toList());
ResponseUtil.r