spring+apollo动态获取yaml格式的配置方式
默认spring装载的都是.properties格式的配置文件,但是有时我们需要定义list或者map类型的配置,那么yaml就具有优势。
以下演示利用apollo来完成自动更新ip白名单的功能
1.重写配置工厂
publicclassYmlPropertySourceFactoryextendsDefaultPropertySourceFactory{ publicPropertySource>createPropertySource(Stringname,EncodedResourceresource)throwsIOException{ StringconfigName=resource.getResource().getFilename(); ConfigFileconfigFile=ConfigService.getConfigFile(configName.substring(0,configName.indexOf(".")),ConfigFileFormat.YML); Stringct=configFile.getContent(); returnYamlPropUtil.buildYaml(configName,ct); } }
定义-D参数的appid和conf目录
publicclassYamlPropUtil{ publicstaticPropertySourcebuildYaml(Stringname,Stringcontent)throwsIOException{ StringsysName=System.getProperty("app.id"); StringappDir=System.getProperty("apollo.cacheDir"); if(appDir.endsWith(File.separator)){ appDir=appDir.substring(0,appDir.length()-1); } StringfilePath=appDir+File.separator+sysName+File.separator+name; Filefile=newFile(filePath); if(file.exists()){ file.delete(); } try(BufferedWriterbufferedWriter=Files.newWriter(file,Charsets.UTF_8)){ bufferedWriter.write(content); bufferedWriter.flush(); List>sources=newYamlPropertySourceLoader().load(name,newFileSystemResource(filePath)); returnsources.get(0); }catch(IOExceptione){ throwe; } } }
2.装载配置
whiteList.yml
注意本地也要存放上述文件在classpath下
white: ip: #ip白名单列表 list: -192.168.103.34 -192.168.1.102 @Configuration @ConfigurationProperties(prefix="white.ip") @PropertySource(value="classpath:whiteList.yml",factory=YmlPropertySourceFactory.class) @Slf4j publicclassIpWhiteListService{ privateListlist; privatefinalstaticintMAX_PROP_ITEM=1000; privatefinalstaticStringPROP_NAME="whiteList.yml"; privatefinalstaticStringKEY_PREFIX="white.ip.list"; publicvoidsetList(List list){ this.list=list; } publicbooleanisAllow(Stringaddress){ returnlist.contains(address); } @ApolloConfigChangeListener(PROP_NAME) publicvoidonChange(ConfigChangeEventchangeEvent){ Set keys=changeEvent.changedKeys(); keys.forEach(e->{ StringnewVal=changeEvent.getChange(e).getNewValue(); log.debug("whiteListischanged={}",newVal); Stringct=newVal; org.springframework.core.env.PropertySourcepropertySource=null; try{ propertySource=YamlPropUtil.buildYaml(PROP_NAME,ct); }catch(IOExceptionex){ log.error("",e); } List newList=Lists.newArrayList(); for(inti=0;i 补充知识:yml格式问题
以缩进代表层级关系
空格个数不重要,但是同一层级必须左对齐
大小写敏感
格式为:key=value
注释单行用#,只能注释单行
application.properties中
logging.level.root=DEBUG
logging.level.org.springframework=DEBUG
logging.level.org.org.mybatis=DEBUG转化为application.yml中
logging:
level:
root:DEBUG
org.springframework:DEBUG
org.org.mybatis:DEBUG冒号后面必须跟空格,否则格式错误
以上这篇spring+apollo动态获取yaml格式的配置方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。