spring+apollo动态获取yaml格式的配置⽅式
默认spring装载的都是.properties格式的配置⽂件,但是有时我们需要定义list或者map类型的配置,那么yaml就具有优势。以下演⽰利⽤apollo来完成⾃动更新ip⽩名单的功能
1.重写配置⼯⼚
public class YmlPropertySourceFactory extends DefaultPropertySourceFactory {
public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
String configName = Resource().getFilename();
ConfigFile configFile = ConfigFile(configName.substring(0, configName.indexOf(".")), ConfigFileFormat.YML);
String ct = Content();
return YamlPropUtil.buildYaml(configName, ct);
}
}
定义-D参数的appid和conf⽬录
public class YamlPropUtil {
public static PropertySource buildYaml(String name, String content) throws IOException {
String sysName = Property("app.id");
String appDir = Property("apollo.cacheDir");
if (dsWith(File.separator)) {
appDir= appDir.substring(0, appDir.length() - 1);
}
String filePath = appDir+ File.separator + sysName + File.separator + name;
File file = new File(filePath);
if (ists()) {
file.delete();
}
try (BufferedWriter bufferedWriter = wWriter(file, Charsets.UTF_8)) {
bufferedWriter.write(content);
bufferedWriter.flush();
List<PropertySource<?>> sources = new YamlPropertySourceLoader().load(name, new FileSystemResource(filePath));
(0);
} catch (IOException e) {
throw e;
}
}
}
2.装载配置
注意本地也要存放上述⽂件在classpath下
white:
ip:
#ip⽩名单列表
list:
- 192.168.103.34
-
192.168.1.102
@Configuration
@ConfigurationProperties(prefix = "white.ip")
@PropertySource(value = "l", factory = YmlPropertySourceFactory.class)
@Slf4j
public class IpWhiteListService {
private List<String> list;
private final static int MAX_PROP_ITEM = 1000;
private final static String PROP_NAME = "l";spring framework和spring的关系
private final static String KEY_PREFIX = "white.ip.list";
public void setList(List<String> list) {
this.list = list;
}
public boolean isAllow(String address) {
ains(address);
}
@ApolloConfigChangeListener(PROP_NAME)
public void onChange(ConfigChangeEvent changeEvent) {
Set<String> keys = changeEvent.changedKeys();
keys.forEach(e -> {
String newVal = Change(e).getNewValue();
log.debug("whiteList is changed={}", newVal);
String ct = newVal;
nv.PropertySource propertySource = null;
try {
propertySource = YamlPropUtil.buildYaml(PROP_NAME, ct);
} catch (IOException ex) {
<("", e);
}
List<String> newList = wArrayList();
for (int i = 0; i < MAX_PROP_ITEM; i++) {
String pName = KEY_PREFIX + "[" + i + "]";
if (ainsProperty(pName)) {
String val = (String) Property(pName);
newList.add(val);
}
}
list = newList;
});
}
}
补充知识:yml格式问题
以缩进代表层级关系
空格个数不重要,但是同⼀层级必须左对齐
⼤⼩写敏感
格式为:key= value
注释单⾏⽤#,只能注释单⾏
application.properties中
=DEBUG
springframework=DEBUG
g.mybatis=DEBUG
转化为l中
logging:
level:
root: DEBUG
org.springframework: DEBUG
冒号后⾯必须跟空格,否则格式错误
以上这篇spring+apollo动态获取yaml格式的配置⽅式就是⼩编分享给⼤家的全部内容了,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。