一、前言
上次我们介绍了动态获取consul配置信息的三种方式,但是毕竟还是需要去知道具体的键值才能去拿到这个数据,但是我们如果遇到连这个key的名字都是动态变化的话,上次那种就已经不太适用了。因此,本文介绍了个新的方法去更加的动态获取配置。
二、增加ConsulConfigService.java
@Service
public class ConsulConfigService {
@Autowired
private ConfigurableEnvironment environment;
public Map<String, Object> getTeacherDetails(String kv) {
Map<String, Object> teacherDetails = new HashMap<>();
String prefix = kv+".";
for (PropertySource<?> propertySource : environment.getPropertySources()) {
if (propertySource instanceof EnumerablePropertySource) {
EnumerablePropertySource<?> enumerablePropertySource = (EnumerablePropertySource<?>) propertySource;
for (String key : enumerablePropertySource.getPropertyNames()) {
if (key.startsWith(prefix)) {
teacherDetails.put(key.substring(prefix.length()), environment.getProperty(key));
}
}
}
}
return teacherDetails;
}
}
三、在controller里面做如下修改;
@Autowired
private ConsulConfigService consulConfigService;
@RequestMapping("/teacher")
public Map<String, Object> getTeacher(@RequestParam String kv) {
System.out.println(consulConfigService.getTeacherDetails(kv));
return consulConfigService.getTeacherDetails(kv);
}
四、consul的kv值为:
五、测试
由此,就可以在不需要知道具体键值对的情况下动态的获取consul配置啦。
对于之前consul的配置信息不清楚的小伙伴可以看上一条文章: