最近有个需求,要把所有nacos的配置在MySQL备份一份,所以就写了个工具来批量生成SQL insert语句. 整体思路为:
- 读取nacos的properties配置
- java代码读取配置的k,v 生成sql文件
- 发给DBA导入MySQL即可。
- 配置依赖
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-configuration2</artifactId>
<version>2.7</version>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.4</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.10.0</version>
</dependency>
- 编写代码
@Test
public void generateTest()throws Exception{
Configurations configs = new Configurations();
// 读取properties配置,指定配置文件地址
PropertiesConfiguration configuration = configs.properties(new File("config.properties"));
// 获取所有key
Iterator<String> keys = configuration.getKeys();
// 遍历生成SQL
String sqlPrefix = "INSERT INTO configuration (name, value, description, create_date_time) VALUES ('";
String currentDateTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
LinkedList<String> sqlList = new LinkedList<>();
keys.forEachRemaining(key->{
StringBuilder sqlJoiner = new StringBuilder(sqlPrefix).append(key).append("', '")
.append(configuration.getString(key)).append("',")
.append("'Auto Generation','").append(currentDateTime).append("');");
System.err.println(sqlJoiner+"\n");
sqlList.add(sqlJoiner.toString());
});
// 生成文件
File file = FileUtils.getFile("/Users/xxx/Desktop/", "config-nacos-cashier.sql");
FileUtils.writeLines(file,sqlList);
}
生成后的文件