package com.exam.controller.backup;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.exam.entity.backup;
import com.exam.entity.log;
import com.exam.service.log.ILocalLogService;
import com.exam.service.backup.IBackupService;
import com.exam.util.IdGenerate;
import com.exam.util.ServletContextUtil;
/**
* 备份管理控制层
* @author
*
*/
@Controller
@RequestMapping("/backupmag")
public class backUpCtrl {
@Autowired
private IBackupService backupService;
@Autowired
private ILocalLogService logService;
@RequestMapping("/initBackUp")
public String initorg(){
return "backUp/backUpList";
}
@RequestMapping("/getbackuplist")
@ResponseBody
public Object getbackuplist(backup bup, int page, int rows){
Map<String, Object> data = new HashMap<String, Object>();
try{
List<backup> backL= backupService.findAllBackup(bup, page, rows);
//rows对应机构列表
data.put("rows", backupService.findAllBackup(bup, page, rows));
//total对应机构总数
data.put("total", backupService.findBackupRow(bup));
}catch(Exception e){
e.printStackTrace();
}
return data;
}
public void backTh(String id)
{
}
//增加备份
@RequestMapping("/addbackup")
@ResponseBody
public Object addBackup() throws IOException{
final Map<String, String> data = new HashMap<String, String>();
final String uuid=IdGenerate.getUUIDString();
final String editName=ServletContextUtil.getLoginuser().getUserName();
Thread t = new Thread(){
public void run() {
try {
backup bup=new backup();
SimpleDateFormat sd=new SimpleDateFormat("yyyyMMddHHmmss");
Properties props=System.getProperties(); //获得系统属性集
String osName = props.getProperty("os.name"); //操作系统名称
String backupsSqlFileName=null;
String osStr=osName.replace(" ", "");
if(osStr.equals("Windows7"))
{
backupsSqlFileName = "c:\\"+"exam_system"+sd.format(new Date())+".sql";
}
else if(osStr.equals("WindowsServer2008R2"))
{
backupsSqlFileName = "c:\\"+"exam_system"+sd.format(new Date())+".sql";
}
else
{
backupsSqlFileName = "/usr/local/"+sd.format(new Date())+".sql";
}
String cmdStr= "mysqldump exam_system -u root -p12345aB ";
String result=newBackup(backupsSqlFileName,cmdStr);
if(result.equals("success"))
{
//数据库写入存放地址和操作人
bup.setUid(uuid);
bup.setBackupName(backupsSqlFileName);
bup.setStatus(1);
//bup.setEditor(ServletContextUtil.getLoginuser().getUserName());
//日志
log log=new log();
log.setLog_type("7");
log.setAdmin_name(editName);
log.setCreate_date(sd.format(new Date()));
log.setRemark(editName+"进行数据库备份,文件的名字为:"+backupsSqlFileName);
logService.addLog(log);
data.put("result",result);
data.put("fileName", backupsSqlFileName);
backupService.updateBack(bup);
Thread.sleep(3000);//数据库数据少时会报错,所以添加了延时3秒钟后才走下个流程
}
else
{
log log=new log();
log.setLog_type("7");
log.setAdmin_name(editName);
log.setCreate_date(sd.format(new Date()));
log.setRemark(editName+"进行数据库备份,备份失败");
logService.addLog(log);
data.put("result",result);
}
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}};
t.start();
System.out.println("ping");
backup backAdd=new backup();
backAdd.setUid(uuid);
backAdd.setStatus(0);
backAdd.setBackupName("正在备份中");
backAdd.setEditor(ServletContextUtil.getLoginuser().getUserName());
backupService.addbackUp(backAdd);
data.put("result","11");
return data;
}
//进行备份还原操作
@RequestMapping("/loadbackup")
@ResponseBody
public Object loadNewBackup(String id) throws InterruptedException
{
SimpleDateFormat sd=new SimpleDateFormat("yyyyMMddHHmmss");
String backupsSqlFileName=null;
//先把存储备份表名字的表备份(名字是固定的)
//把存储日志的表备份
Properties props=System.getProperties(); //获得系统属性集
String osName = props.getProperty("os.name"); //操作系统名称
String osStr=osName.replace(" ", "");
if(osStr.equals("Windows7"))
{
backupsSqlFileName = "c:\\"+"exam_systemBack"+".sql";
}
else if(osStr.equals("WindowsServer2008R2"))
{
backupsSqlFileName = "c:\\"+"exam_systemBack"+".sql";
}
else
{
backupsSqlFileName = "/usr/local/"+"exam_systemBack"+".sql";
}
//String backupsSqlFileName = "c:\\"+"exam_system"+sd.format(new Date())+".sql";
String cmdStr= "mysqldump exam_system backup_info -uroot -p12345aB ";
newBackup(backupsSqlFileName,cmdStr);
Map<String, Object> data = new HashMap<String, Object>();
String result=null;
String filePath=backupService.findPathById(id);
System.out.println("*******************"+osStr);
if(osStr.equals("Linux"))
{
result=loadLinux(filePath);
}
else
{
result=load(filePath);
}
//在linux服务器上,延时5秒再还原backup_info表
if(osStr.equals("Linux"))
{
Thread.currentThread();
Thread.sleep(5000);//毫秒
}
if(result.equals("success"))
{
//再还原存储备份表名字的表
//记录日志
String aa=null;
if(osStr.equals("Linux"))
{
aa=loadLinux(backupsSqlFileName);
}
else
{
aa=load(backupsSqlFileName);
}
if(aa.equals("success")){
data.put("result", result);
}
}
else
{
//记录日志
log log=new log();
log.setLog_type("7");
log.setAdmin_name(ServletContextUtil.getLoginuser().getUserName());
log.setCreate_date(sd.format(new Date()));
log.setRemark(ServletContextUtil.getLoginuser().getUserName()+"还原备份文件失败,其文件的名字为:"+filePath);
logService.addLog(log);
data.put("result", "fail");
}
log log=new log();
log.setLog_type("7");
log.setAdmin_name(ServletContextUtil.getLoginuser().getUserName());
log.setCreate_date(sd.format(new Date()));
log.setRemark(ServletContextUtil.getLoginuser().getUserName()+"进行了备份文件的还原,还原文件的名字为:"+filePath);
logService.addLog(log);
return data;
}
//删除备份
@RequestMapping("/delebackup")
@ResponseBody
public Object deleFile(String id)
{
SimpleDateFormat sd=new SimpleDateFormat("yyyyMMddHHmmss");
Map<String, Object> data = new HashMap<String, Object>();
String[] ids=id.split(",");
for (String idStr : ids) {
String fPath=backupService.findPathById(idStr);
File myDelFile = new File(fPath);
try {
myDelFile.delete();
backupService.delbackUp(idStr);
data.put("success", true);
log log=new log();
log.setLog_type("7");
log.setAdmin_name(ServletContextUtil.getLoginuser().getUserName());
log.setCreate_date(sd.format(new Date()));
log.setRemark(ServletContextUtil.getLoginuser().getUserName()+"删除了备份文件:"+fPath);
logService.addLog(log);
}
catch (Exception e) {
data.put("success", false);
e.printStackTrace();
}
}
return data;
}
/*
* 进行备份操作
* */
public static String newBackup(String backupsSqlFileName,String cmdStr) throws InterruptedException {
String result=null;
try {
Runtime rt = Runtime.getRuntime();
String aa=cmdStr+" --result-file="+backupsSqlFileName;
Process child = rt.exec(cmdStr+" --result-file="+backupsSqlFileName);
// 设置导出编码为utf-8。这里必须是utf-8
// 把进程执行中的控制台输出信息写入.sql文件,即生成了备份文件。注:如果不对控制台信息进行读出,则会导致进程堵塞无法运行
if(child.waitFor()==0)
{
result="success";
}
else
{
result="fail";
}
} catch (Exception e) {
result="fail";
e.printStackTrace();
}
return result;
}
/*
* 进行备份的还原操作
* */
public static String loadLinux(String fPath) {
String result = null;
try {
Runtime rt = Runtime.getRuntime();
String aa="mysql -uroot -p12345aB exam_system";
// 调用 mysql 的 cmd:
Process child = rt.exec(aa);
OutputStream out = child.getOutputStream();//控制台的输入信息作为输出流
String inStr;
StringBuffer sb = new StringBuffer("");
String outStr;
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream(fPath), "utf8"));
while ((inStr = br.readLine()) != null) {
sb.append(inStr + "\r\n");
}
outStr = sb.toString();
OutputStreamWriter writer = new OutputStreamWriter(out, "utf8");
writer.write(outStr);
// 注:这里如果用缓冲方式写入文件的话,会导致中文乱码,用flush()方法则可以避免
writer.flush();
// 别忘记关闭输入输出流
out.close();
br.close();
writer.close();
result="success";
} catch (Exception e) {
result="fail";
e.printStackTrace();
}
return result;
}
public static String load(String fPath) {
String result = null;
try {
Runtime rt = Runtime.getRuntime();
//-u用户名 -p 密码 然后是要备份的数据库的名称
String aa="mysql -uroot -p12345aB exam_system < "+fPath;
String[] cmd = { "cmd", "/c", aa};
// 调用 mysql 的 cmd:
Process child = rt.exec(cmd);
if(child.waitFor()==0)
{
result="success";
}
else
{
result="fail";
}
} catch (Exception e) {
result="fail";
e.printStackTrace();
}
return result;
}
}
在win7和Linux环境,使用mysql进行数据库的备份和恢复
最新推荐文章于 2024-05-06 11:07:47 发布