SpringBoot 动态配置数据源-进阶-可视化动态配置数据源-1

固定配置多数据源: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文件。

未完待续....

  

原文地址:https://www.cnblogs.com/feecy/p/12108350.html