您的位置:首页 > 编程语言 > Java开发

java 实现mysql数据库备份,以及 Runtime.getRuntime().exec 阻塞解决

2019-03-23 17:09 141 查看

需要注意的就是,执行数据库备份和还原操作,直接用Runtime.getRuntime().exec 的话会造成阻塞,因为读写数据量太大,所以用线程来实现。还有就是网上看到一堆 说什么命令前面加上 “/bin/ch”,”-c” 反正我试了的,加这个不行 。但是加上 “/bash/”,”-c” 是可以的。

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

@Controller
@RequestMapping(value = "/DbOperate")
public class DbOperate {

private static Process process = null;
@RequestMapping(value = "/dbBackUp", method = RequestMethod.POST)
@ResponseBody
public String dbBackUp() throws Exception {
String msg = "";
try {
String sb = "mysqldump -uAdmin -pchinawiserv --set-charset=UTF8 oc4db > /bak/mysqldata/oc4db_$(date " +
"+%Y%m%d_%H%M%S).sql";
process = Runtime.getRuntime().exec(new String[]{"bash", "-c",sb});
final InputStream is1 = process.getInputStream();
final  InputStream is2 = process.getErrorStream();
new Thread(){
public void run(){
BufferedReader br1 = new BufferedReader(new InputStreamReader(is1));
try{
String line1 = null;
while ((line1 = br1.readLine()) != null){
if(line1 != null){}
}
}catch (IOException e){
e.printStackTrace();
}
finally {
try {
is1.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
}.start();

new Thread(){
public void run(){
BufferedReader br2 = new BufferedReader(new InputStreamReader(is2));
try{
String line2 = null;
while ((line2 = br2.readLine()) != null){
if(line2 != null){}
}
}catch (IOException e){
e.printStackTrace();
}
finally {
try {
is2.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
}.start();

process.waitFor();
process.destroy();
msg = "数据库备份成功";
}catch (Exception e){
msg = "数据库备份失败";
try{
process.getErrorStream().close();
process.getInputStream().close();
process.getOutputStream().close();
}catch (Exception ee){

}
}
return msg;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: