springboot 数据库还原
- 数据库实体类
public class MysqlBackups implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String mysqlIp;
private String mysqlPort;
private String mysqlCmd;
private String mysqlBackCmd;
private String databaseName;
private String backupsName;
private String backupsPath;
private Integer operation;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
private Date backupTime;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
private Date recoveryTime;
private String remark;
}
- 实现类
public interface IMysqlBackupsService extends IService<MysqlBackups> {
R rollback(MysqlBackups backups, String userName, String password);
}
@Service
public class MysqlBackupsServiceImpl extends ServiceImpl<MysqlBackupsMapper, MysqlBackups> implements IMysqlBackupsService {
@Transactional
@Override
public R rollback(MysqlBackups backups, String userName, String password) {
StringBuilder realFilePath = new StringBuilder().append(backups.getBackupsPath()).append(backups.getBackupsName());
if (!new File(String.valueOf(realFilePath)).exists()) {
return R.error("文件不存在,恢复失败,请查看目录内文件是否存在后重新尝试!");
}
StringBuilder cmd = new StringBuilder()
.append("mysql -h")
.append(backups.getMysqlIp())
.append(" -u")
.append(userName)
.append(" -p")
.append(password)
.append(" ")
.append(backups.getDatabaseName())
.append(" < ")
.append(realFilePath);
String[] command = new String[0];
String osName = System.getProperty("os.name").toLowerCase();
if (Constant.isSystem(osName)) {
command = new String[]{"cmd", "/c", String.valueOf(cmd)};
} else {
command = new String[]{"/bin/sh", "-c", String.valueOf(cmd)};
}
backups.setMysqlBackCmd(String.valueOf(cmd));
backups.setRecoveryTime(new Date());
backups.setOperation(backups.getOperation() + 1);
try {
Runtime.getRuntime().exec(command);
this.updateById(backups);
return R.ok("Mysql 数据库恢复成功,恢复文件名:{}"+ realFilePath);
} catch (Exception e) {
e.printStackTrace();
return R.error("网络异常,恢复失败,请稍后重新尝试!");
}
}
}
- 控制类
@PostMapping("/rollback")
public R rollback(@RequestBody MysqlBackups backups) {
if (backups.getId() == null) {
return R.error("id不能为null,请重新尝试!");
}
String userName = this.userName;
String password = this.password;
MysqlBackups mb = mysqlBackupsService.getById(backups.getId());
if (mb == null) {
return R.error("还原数据错误");
}
R r = mysqlBackupsService.rollback(mb, userName, password);
return r;
}