Linux java mysql 定时备份和手动备份 (一 )

  项目中需要备份与还原mysql数据库,mysql数据库在linux 服务器中.

  功能包括,1.手动备份 2.自动备份(按照指定时间自动备份,单位为周或者小时) 3.还原数据库(还原数据库不能在程序还原,虽然代码中有涉及测试一部分但是没执行) 4.删除备份

  开始还考虑到linux系统和windows系统兼容,但是时间越来越紧迫,许多未完善部分未实现,比如用户手动备份时,数据库过大,出现阻塞现象如何解决,删除备份未找到文件等等等等!只能暂时先实现功能,这块也本身不是太重要.....有时间优化吧!!!!!!!!!!!!!!就这样

  

  首先备份要有工具类,里面判断windows的那个忽略掉吧

  1 package cn.goldencis.tsa.common.utils;
  2 
  3 import java.io.BufferedReader;
  4 import java.io.File;
  5 import java.io.FileOutputStream;
  6 import java.io.IOException;
  7 import java.io.InputStreamReader;
  8 import java.io.OutputStreamWriter;
  9 import java.io.PrintWriter;
 10 import java.io.UnsupportedEncodingException;
 11 import java.text.SimpleDateFormat;
 12 import java.util.Date;
 13 
 14 import org.springframework.web.context.ContextLoader;
 15 
 16 import cn.goldencis.tsa.common.entity.BackupProperties;
 17 
 18 /**
 19  * About mysql backup restore.... util class
 20  * At first considered the system compatibility(windows and linux),
 21  * however, the time was pressing and later added
 22  * Note that some of the linux system to complete,
 23  * and some of the windows system to complete, so note is english
 24  * @author mll
 25  * 2017年4月10日上午10:41:48
 26  * 
 27  */
 28 public class BackupUtil {
 29     
 30     boolean isWindows = ServerListener.getInstance().checkOsWindows();
 31     
 32     private static BackupUtil instance = new BackupUtil();
 33     
 34     private BackupProperties pro;
 35     
 36     private String allFileName;
 37     
 38     private String fileName;
 39     
 40     private String refileName;
 41     
 42     @Override
 43     public String toString() {
 44         return "username: "+pro.getUsername()+"\npassword:" +pro.getPassword()+"\ndatabaseName:" +pro.getDatabaseName()
 45                 +"\nfilePath:" +pro.getWindowsFilePath()+"\n backupFileName:" +pro.getBackupFileName()
 46                 +"\nbackupFileMsg:" +pro.getBackupFileMsg()+"\nip:" +pro.getIp()+"\nwinFileMysqlPath: "+pro.getWinFileMysqlPath();
 47     }
 48 
 49     private BackupUtil(){
 50         
 51     }
 52     
 53     public static BackupUtil getInstance(){
 54         instance.setPro((BackupProperties) ContextLoader.getCurrentWebApplicationContext().getBean("backupProperties"));
 55         return instance;
 56     }
 57     
 58     /**
 59      * 拼接备份命令
 60      * @author mll
 61      * @return String
 62      */
 63     private String splitJointBackup(String cfileName){
 64         String str="mysqldump -h "+ pro.getIp() + " -u " +pro.getUsername() + " -p" + pro.getPassword() +" "+ pro.getDatabaseName() ;
 65         Date d = new Date();
 66         SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
 67         String time=sdf.format(d);
 68         if(isWindows){
 69             if(StringUtil.isEmpty(cfileName)){
 70                 refileName = pro.getBackupFileName() + time + ".sql";
 71                 fileName = pro.getWindowsFilePath() + refileName;
 72                 
 73             }else{
 74                 refileName = cfileName + time + ".sql";
 75                 fileName = pro.getWindowsFilePath() + refileName;
 76             }
 77             str = pro.getWinFileMysqlPath() + str;
 78             
 79             return str;
 80         }else{
 81             if(StringUtil.isEmpty(cfileName)){
 82                 refileName = pro.getBackupFileName() + time + ".sql";
 83                 fileName = pro.getLinuxFilePath() + refileName;
 84             }else{
 85                 refileName = cfileName + time + ".sql";
 86                 fileName = pro.getLinuxFilePath() + refileName;
 87             }
 88             return str;
 89         }
 90     }
 91     
 92     /**
 93      * 拼接还原命令
 94      * @author mll
 95      * @return String
 96      */
 97     private String splitJointRestore(String cfileName){
 98         
 99         String str="mysql -h "+ pro.getIp() + " -u" +pro.getUsername() + " -p" + pro.getPassword()
100         +" "+ pro.getDatabaseName() ;
101         
102         if(isWindows){
103             fileName = pro.getWindowsFilePath() + cfileName;
104             str = pro.getWinFileMysqlPath() + str;
105             
106             return str;
107         }else{
108             fileName = pro.getLinuxFilePath() + cfileName;
109             return str;
110         }
111     }
112     
113     /**
114      * FLag is true auto delete
115      * @param cfileName
116      * @param isAuto
117      * @return
118      */
119     private String splitJoinDeleteBackup(String cfileName){
120         String str;
121         String arrStr[]=cfileName.split(",");
122         
123         StringBuilder sb;
124         
125         if(isWindows){
126             sb = new StringBuilder();
127             for(String temp:arrStr){
128                 sb.append(pro.getWindowsFilePath() + temp + " ");
129             }
130             str = "del " + sb.toString();
131         }else{
132             sb = new StringBuilder();
133             for(String temp:arrStr){
134                 sb.append(pro.getLinuxFilePath() + temp + " ");
135             }
136             str = "rm " + sb.toString() + " -rf ";
137         }
138         return str;
139     }
140     
141     /**
142      * 删除备份
143      * @param cfileName
144      * @param isAuto
145      */
146     public void deleteBackup(String cfileName){
147         String cmd = splitJoinDeleteBackup(cfileName);
148         System.out.println(cmd);
149         try {
150             Runtime.getRuntime().exec(cmd);
151             
152         } catch (IOException e) {
153             e.printStackTrace();
154         }
155     }
156 
157     
158     /**
159      * 备份
160      * @author mll
161      * @param cfileName
162      * @return String
163      */
164     public String backup(String cfileName) {
165         String cmd = splitJointBackup(cfileName);
166         PrintWriter p = null;
167         BufferedReader reader = null;
168         File filePath = new File(pro.getLinuxFilePath());
169         FileOutputStream fileout = null;
170         try {
171             if(!filePath.exists()){
172                 filePath.mkdirs();
173             }
174             fileout = new FileOutputStream(fileName);
175             p = new PrintWriter(new OutputStreamWriter(fileout, "utf8"));
176             Process process = Runtime.getRuntime().exec(cmd);
177             InputStreamReader inputStreamReader = new InputStreamReader(process
178                     .getInputStream(), "utf8");
179             reader = new BufferedReader(inputStreamReader);
180             String line = null;
181             while ((line = reader.readLine()) != null) {
182                 p.println(line);
183             }
184             p.flush();
185         } catch (UnsupportedEncodingException e) {
186             e.printStackTrace();
187         } catch (IOException e) {
188             e.printStackTrace();
189         } finally {
190             try {
191                 if (reader != null) {
192                     reader.close();
193                 }
194                 if (p != null) {
195                     p.close();
196                 }
197                 if (fileout != null) {
198                     fileout.close();
199                 }
200             } catch (IOException e) {
201                 e.printStackTrace();
202             }
203         }
204         return refileName;
205     }
206     
207     /**
208      * 还原
209      * @author mll
210      * @param cfileName void
211      */
212     public void restore(String cfileName) {
213         String cmd = splitJointRestore(cfileName);
214         try {
215             System.out.println(cmd + "<"+fileName);
216             //Process runtimeProcess = Runtime.getRuntime().exec(cmd + "<"+fileName);  
217             
218             Process process = Runtime.getRuntime().exec("mysql -u root -proot -h 192.168.3.89 goldencis_tsa </opt/tsa/backup/1111492136868475.sql"); 
219 
220             // 输出执行结果
221             InputStreamReader in = new InputStreamReader(process.getInputStream());
222             BufferedReader br = new BufferedReader(in);
223             String line;
224             while((line = br.readLine()) != null){
225                 System.out.println(line);
226             }
227             br.close();
228             in.close();
229             
230             // 输出错误信息
231             InputStreamReader in2 = new InputStreamReader(process.getErrorStream());
232              BufferedReader br2 = new BufferedReader(in2);
233              String line2 ;
234              while((line2 = br2.readLine()) != null){
235                  System.out.println("="+line2);
236              }
237              br2.close();
238              in2.close();
239         } catch (UnsupportedEncodingException e) {
240             e.printStackTrace();
241         } catch (IOException e) {
242             e.printStackTrace();
243         }
244     }
245 
246     public String getAllFileName() {
247         return allFileName;
248     }
249 
250     public void setAllFileName(String allFileName) {
251         this.allFileName = allFileName;
252     }
253             
254     
255     public BackupProperties getPro() {
256         return pro;
257     }
258 
259     public void setPro(BackupProperties pro) {
260         this.pro = pro;
261     }
262 
263     public String getFileName() {
264         return fileName;
265     }
266 
267     public String getRefileName() {
268         return refileName;
269     }
270 
271     public void setRefileName(String refileName) {
272         this.refileName = refileName;
273     }
274 }
BackupUtil

 

  工具类中的BackupProperties

 1 package cn.goldencis.tsa.common.entity;
 2 
 3 import java.io.File;
 4 
 5 public class BackupProperties {
 6 
 7     private String username;                            //数据库登陆名
 8     private String password;                            //数据库密码
 9     private String databaseName;                        //数据库名
10     private String windowsFilePath;                            //备份的路径
11     private String linuxFilePath;                            //备份的路径
12     private String backupFileName;                        //备份的文件名
13     private String backupFileMsg;                        //备份文件的信息
14     private String ip;                                    //ip
15     private String winFileMysqlPath;                    //windows下mysql安装路径一直到bin
16     
17     
18     public String getUsername() {
19         return username;
20     }
21     public void setUsername(String username) {
22         this.username = username;
23     }
24     public String getPassword() {
25         return password;
26     }
27     public void setPassword(String password) {
28         this.password = password;
29     }
30     public String getDatabaseName() {
31         return databaseName;
32     }
33     public void setDatabaseName(String databaseName) {
34         this.databaseName = databaseName;
35     }
36 
37     public String getWinFileMysqlPath() {
38         return winFileMysqlPath;
39     }
40 
41     public void setWinFileMysqlPath(String winFileMysqlPath) {
42         if (!winFileMysqlPath.endsWith(File.separator)) {
43             this.winFileMysqlPath = winFileMysqlPath + File.separator;
44         }
45         this.winFileMysqlPath = winFileMysqlPath;
46     }
47 
48     public String getIp() {
49         return ip;
50     }
51 
52     public void setIp(String ip) {
53         this.ip = ip;
54     }
55 
56     public String getBackupFileName() {
57         return backupFileName;
58     }
59 
60     public void setBackupFileName(String backupFileName) {
61         this.backupFileName = backupFileName;
62     }
63 
64     public String getBackupFileMsg() {
65         return backupFileMsg;
66     }
67 
68     public void setBackupFileMsg(String backupFileMsg) {
69         this.backupFileMsg = backupFileMsg;
70     }
71     public String getWindowsFilePath() {
72         return windowsFilePath;
73     }
74     public void setWindowsFilePath(String windowsFilePath) {
75         this.windowsFilePath = windowsFilePath;
76     }
77     public String getLinuxFilePath() {
78         return linuxFilePath;
79     }
80     public void setLinuxFilePath(String linuxFilePath) {
81         this.linuxFilePath = linuxFilePath;
82     }    
83 }
BackupProperties

  

   spring-context.xml

 1     <bean id="backupProperties" class="cn.goldencis.tsa.common.entity.BackupProperties">
 2         <property name="username" value="${backup.username}"/>
 3         <property name="password" value="${backup.password}"/>
 4         <property name="databaseName" value="${backup.databaseName}"/>
 5         <property name="linuxFilePath" value="${backup.linuxFilePath}"/>
 6         <property name="windowsFilePath" value="${backup.windowsFilePath}"/>
 7         <property name="backupFileName" value="${backup.backupFileName}"/>
 8         <property name="backupFileMsg" value="${backup.backupFileMsg}"/>
 9         <property name="ip" value="${backup.ip}"/>
10         <property name="winFileMysqlPath" value="${backup.winFileMysqlPath}"/>
11     </bean> 
View Code

搞完这些,除了还原和自动备份不能用之外其他都是可以用的(linux下)

 

 

  

posted @ 2017-04-22 19:29  江湖人称洗发水  阅读(762)  评论(0编辑  收藏  举报