固定配置多數據源:https://www.cnblogs.com/feecy/protected/p/11847207.html
springboot-yml 配置編輯
節點配置:
slave: datasource: names: N1,N2 N1: driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://XXXXXXXXXXX1 username: root password: type: com.alibaba.druid.pool.DruidDataSource N2: driver-class-name: com.mysql.jdbc.Driver url: jdbc:mysql://XXXXXXXXXXX2 username: root password: type: com.alibaba.druid.pool.DruidDataSource
yaml-jar包:
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>1.25</version>
</dependency>
獲取Yaml對象
private Yaml getYamlObject(){ DumperOptions dumperOptions = new DumperOptions(); dumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); dumperOptions.setDefaultScalarStyle(DumperOptions.ScalarStyle.PLAIN); dumperOptions.setPrettyFlow(false); Yaml yaml = new Yaml(dumperOptions); return yaml; }
配置一個新的節點
//DatabaseConfig{url,username,password}
private Map<String, String> getNodeMap(DatabaseConfig config) {
Map<String,String> node = new LinkedHashMap<>(); node.put("driver-class-name","com.mysql.jdbc.Driver"); node.put("url",config.getUrl()); node.put("username",config.getUsername()); node.put("password",config.getPassword()); node.put("type","com.alibaba.druid.pool.DruidDataSource");
return node; }
獲取配置文件對象(我的配置文件在jar同級config/ 下面)
yaml-load加載成Map ,獲取並編輯后,yaml-dump 重新寫回到文件
public void add(DatabaseConfig config){
//獲取配置文件對象(我的配置文件在jar包同級目錄/config/ 下面)
log.info("user.dir:{}",System.getProperty("user.dir"));
File dumpFile = new File(System.getProperty("user.dir")+"/config/application.yml");
JSONObject result = new JSONObject();
Yaml yaml = getYamlObject();
Map map = null;
try {
map = (Map)yaml.load(new FileInputStream(dumpFile));
} catch (FileNotFoundException e) {
log.error("{}",e);
}
Map datasource = (Map) ((Map) map.get("slave")).get("datasource");
String[] names = ((String)datasource.get("names")).split(",");
if(StringUtil.contains(names,config.getName())){
//名稱已經存在
return;
}
//追加names
if(names.length>0){
datasource.put("names",(String)datasource.get("names")+","+config.getName());
}else{
datasource.put("names", config.getName());
}
//獲取新的Node
Map<String, String> node = getNodeMap(config);
datasource.put(config.getName(),node);
try {
//寫回到配置文件
yaml.dump(map, new OutputStreamWriter(new FileOutputStream(dumpFile)));
} catch (FileNotFoundException e) {
log.error("{}",e);
}
//添加成功
return;
}
編輯節點,刪除節點同添加 操作Map對象后寫回到Yml文件。
未完待續....