名字
t-io官网的数据库都会定时备份,并且可以通过http直接下载到本地(这个当然需要特权,不是人人有这个操作权限),为了操作的灵活性,采用java来实现MySql的备份
package org.tio.sitexxx.service.tool;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author tanyaowu
*/
public class MysqlTool {
private static Logger log = LoggerFactory.getLogger(MysqlTool.class);
/**
* @param host 数据库服务器主机地址,可以是ip,也可以是域名
* @param port 数据库服务器端口
* @param dbName 数据库名字
* @param username 数据库用户名
* @param password 数据库密码(明文)
* @param filePath 存到哪个文件,形如:"d:/dbbackup/2019-08-03_00_00_00.sql"
* @return
*/
public static File backup(String host, int port, String dbName, String username, String password, String filePath) {
Long starttime = System.currentTimeMillis();
try {
File file = new File(filePath);
String[] commands = new String[3];
String os = System.getProperties().getProperty("os.name");
if (os.startsWith("Win")) {
commands[0] = "cmd.exe";
commands[1] = "/c";
} else {
commands[0] = "/bin/sh";
commands[1] = "-c";
}
StringBuilder mysqldump = new StringBuilder();
mysqldump.append("mysqldump");
mysqldump.append(" --opt");
mysqldump.append(" --user=").append(username);
mysqldump.append(" --password=").append(password);
mysqldump.append(" --host=").append(host);
mysqldump.append(" --protocol=tcp");
mysqldump.append(" --port=").append(port);
mysqldump.append(" --default-character-set=utf8");
mysqldump.append(" --single-transaction=TRUE");
mysqldump.append(" --routines");
mysqldump.append(" --events");
mysqldump.append(" ").append(dbName);
mysqldump.append(" > ");
mysqldump.append("").append(filePath).append("");
String command = mysqldump.toString();
System.out.println(command);
commands[2] = command;
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec(commands);
if (process.waitFor() == 0) {
Long endtime = System.currentTimeMillis();
Long distance = endtime - starttime;
System.out.println("【" + dbName + "】备份成功,耗时:" + distance + "ms");
return file;
} else {
InputStream is = process.getErrorStream();
if (is != null) {
BufferedReader in = new BufferedReader(new InputStreamReader(is, "utf-8"));
String line;
StringBuilder sb = new StringBuilder();
while ((line = in.readLine()) != null) {
sb.append(line);
}
System.out.println("数据库备【" + dbName + "】份失败\r\n" + sb.toString());
}
}
} catch (Exception e) {
log.error("数据库备【" + dbName + "】份失败", e);
return null;
}
return null;
}
}
非核心代码主要是获取数据库信息这些,同时将生成的SQL做成zip,然后用个定时任务去执行这个程序,这些代码就不贴出来啦
最新评论 我的评论
t-io为本站提供HTTP、WebSocket、Socket、页面渲染与压缩等服务,nginx为本站提供反向代理服务
© 2017-2023 钛特云 版权所有 | 浙ICP备17032976号 | 浙公网安备 33011802002129号