whyclj
2019-08-16 2ed4d38d6551d1f755f012ff26428ace799d85c5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
package com.backup;
 
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
import com.base.Com;
import com.sql.MysqlConnPool;
 
import main.main_FBS9100S_DataBaseBackUp;
 
public class DataBaseBackUpThread extends Thread{
    public static final int REGULAR_BACKUP_MAXCOUNT = 3;                                //¶¨Ê±±¸·Ý±ÊÊý
    public static final int INSTANT_BACKUP_MAXCOUNT = 10;                                //˲¼ä±¸·Ý±ÊÊý
    public static final String REGULAR_BACKUP_PATHNAME = "REGULAR_BACKUP";                //¶¨ÆÚ±¸·ÝÎļþ¼ÐÃû³Æ
    public static final String INSTANT_BACKUP_PATHNAME = "INSTANT_BACKUP";                //˲¼ä±¸·ÝÎļþ¼ÐÃû³Æ
    
    private List<DatabaseTable> list = new ArrayList<DatabaseTable>();
    private MysqlConnPool pool;
    private String savePath = System.getProperty("user.dir")+ File.separator+"mysql_backup";            //±¸·ÝÊý¾Ý¿âµÄ¸ùĿ¼
    private MyRunTime runtime = null;
    
    public DataBaseBackUpThread(MysqlConnPool conn_pool){
        this.pool = conn_pool;
        this.runtime = new MyRunTime(this.pool);
        
        DataBaseBackUpThread_SQL.createBackupTable(pool);                                                             //³õʼ»¯Êý¾Ý¿â±í
        
        this.list = DataBaseBackUpThread_SQL.searchAllDataBaseAndTable(pool);                                        //²éѯÊý¾Ý¿âÖеÄËùÓбí(³ýÈ¥mysqlÖÐ×Ô´øµÄÊý¾Ý¿â)
        
        DataBaseBackUpThread_SQL.inseartBackupTable(pool,list);                                                        //²åÈëËùÓеÄÊý¾Ý¿â±í½á¹¹µ½Êý¾Ý¿âÖР   
    
        //DataBaseBackUpThread_SQL.DataBaseBackUp_StartTime(pool,main_FBS9100S_DataBaseBackUp.m_VersionNum);        //¼Ç¼µ±Ç°Ï̵߳İ汾ºÅºÍµ±Ç°Ïß³ÌµÄÆô¶¯Ê±¼ä
 
    }
    
    
    
    
    @Override
    public void run() {        
        System.out.println(this.getName() + " - DataBaseBackUpThread  start at "+Com.getDateTimeFormat(new Date(), Com.DTF_YMDhms));
        Date lastRecodTime = new Date(2000,1,1);
        Date normTime = null;
        Date nowTime = null;
        while(true){
            try {
                nowTime = new Date();
                normTime = createNomalDate(nowTime);
                //System.out.println();
                
                //12µã59·Ö¿ªÊ¼±¸·ÝËùÓеÄÊý¾Ý¿â
                if(countTimeLong(nowTime, normTime)<30 && countTimeLong(lastRecodTime, nowTime) >= 7*24*60*60) {
                    System.out.println("¿ªÊ¼±¸·ÝËùÓеÄÊý¾Ý¿â"+Com.getDateTimeFormat(new Date(), Com.DTF_YMDhms));
                    this.list = DataBaseBackUpThread_SQL.searchAllDataBaseAndTable(pool);
                    String path = savePath+File.separator+REGULAR_BACKUP_PATHNAME;
                    deleteFileRoot(path,REGULAR_BACKUP_MAXCOUNT);                            //ɾ³ý³¬¹ý¼Ç¼±ÊÊýµÄ±¸·Ý¼Ç¼(×î¶àÈý±Ê)
                    path += File.separator+Com.getDateTimeFormat(nowTime, Com.DTF_YMD_h_m_s);
                    for(int i=0;i<this.list.size();i++) {
                        DatabaseTable table = list.get(i);
                        if(DataBaseBackUpThread_SQL.isSpecialChar(table.getDatabase_name()) || DataBaseBackUpThread_SQL.isSpecialChar(table.getTable_name())) {
                            continue;                                                            //Ìø¹ýº¬ÓÐÌØÊâ×Ö·ûµÄÊý¾Ý¿âÃûºÍ±íÃû
                        }
                        String rootPath = path+File.separator+list.get(i).getDatabase_name();
                        craeteFileRoot(rootPath);
                        runtime.exec(list.get(i).getDatabase_name(), list.get(i).getTable_name(),rootPath);                    //±¸·ÝÖ¸¶¨µÄÊý¾Ý¿â
                    }                    
                    lastRecodTime = nowTime;
                    DataBaseBackUpThread_SQL.inseartBackupTable(pool,list);
                    
                    ZipUtil zipUtil = new ZipUtil();
                    String zipName = path+".zip";
                    File zipFile = zipUtil.createZip(zipName, new File(path));    //ѹËõÊý¾Ý¿âÎļþ
                    
                    
                    HzipSocket SocketClient = new HzipSocket();
                    SocketClient.init(zipName);                            //·¢ËÍÊý¾Ý¿â±¸·ÝÎļþµ½Ô¶³Ì·þÎñÆ÷
                    System.out.println("Ô¶³Ì±¸·ÝÊý¾Ý¿âÍê³É" + Com.getDateTimeFormat(new Date(), Com.DTF_YMDhms));
                    if(zipFile.exists() && zipFile.length() > 1*1024 && new File(path).exists()) {
                        deleteDir(new File(path));
                    }
                }
                
                //²éѯËùÓÐÐèÒª±¸·ÝÖ¸¶¨Êý¾Ý¿âµÄ¼Ç¼
                list = DataBaseBackUpThread_SQL.searAllTableState(pool);                                                    //²éѯµ±Ç°ÐèÒª±¸·ÝµÄ±íµÄ¼Ç¼
                if(list.size() > 0){
                    String root = savePath+File.separator+INSTANT_BACKUP_PATHNAME;
                    String path = root + File.separator+Com.getDateTimeFormat(nowTime, Com.DTF_YMD_h_m_s);
                    int count = 0;
                    for(int i = 0 ; i < list.size() ; i++){
                        DatabaseTable table = list.get(i);
                        if(DataBaseBackUpThread_SQL.isSpecialChar(table.getDatabase_name()) || DataBaseBackUpThread_SQL.isSpecialChar(table.getTable_name())) {
                            continue;
                        }
                        deleteFileRoot(root, INSTANT_BACKUP_MAXCOUNT);                                    //ɾ³ý³¬¹ý±¸·Ý±ÊÊýµÄ±¸·ÝÊý¾Ý
                        count ++;
                        String rootPath = path+File.separator+table.getDatabase_name();
                        craeteFileRoot(rootPath);                                                                            //´´½¨Ö¸¶¨µÄÎļþ¼Ð
                        // System.out.println(rootPath);
                        //Ö´Ðб¸·Ý
                        boolean flag = runtime.exec(table.getDatabase_name(), table.getTable_name(),rootPath);
                        // System.out.println("dbname:"+table.getDatabase_name()+"\t tname"+table.getTable_name()+"\ten="+flag);
                        if(flag){
                            //±¸·ÝÍê³ÉÖ®ºóÐ޸ļǼµÄ״̬
                            table.setBack_en(DatabaseTable.MYSQL_BACKUP_OVER);                                        //±¸·ÝÍê³É
                            DataBaseBackUpThread_SQL.UpdateDataBaseState(pool, table);
                        }
                    }                    
                    
                    if( count > 0) {
                        ZipUtil zipUtil = new ZipUtil();
                        String zipName = path+".zip";
                        File zipFile = zipUtil.createZip(zipName, new File(path));    //ѹËõÊý¾Ý¿âÎļþ
                        if(zipFile.exists() && zipFile.length() > 1*1024 && new File(path).exists()) {
                            deleteDir(new File(path));
                        }
                        System.out.println("¿ªÊ¼±¸·Ý"+count+"¸ö±í    at "+Com.getDateTimeFormat(nowTime, Com.DTF_YMD_h_m_s));
                    }
                }                
                sleep(500);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }        
    }
    
    /**
     *     ¹¹Ôì½ñÌìµÄ23:59:30
     * @return
     */
    public static Date createNomalDate(Date time) {
        String time_str = Com.getDateTimeFormat(time, Com.DTF_YMD) + " 23:59:30";
        //System.out.println(time_str);
        return Com.getDateTimeFromStr(time_str, Com.DTF_YMDhms);
    }
    
    /**
     *     ¼ÆËãÁ½¸öʱ¼äÖ®¼äµÄ¼ä¸ôÃëÊý
     * @param start
     * @param end
     * @return
     */
    public long countTimeLong(Date start,Date end){
        return (Math.abs(end.getTime()-start.getTime())/1000);
    }
    
    /**
     *     ´´½¨Ö¸¶¨µÄÎļþ¼Ð
     */
    public static void craeteFileRoot(String filepath) {
        File f = new File(filepath);
        if(!f.exists()) {
            f.mkdirs();
        }
    }
    
    /**
     * ±£Áôµ±Ç°Ä¿Â¼ÖеÄÖ¸¶¨ÊýÄ¿µÄÎļþ¼Ð            (ɾ³ýµ±Ç°Îļþ¼ÐϵÄ×îÔç֮ǰµÄ±¸·ÝÊý¾Ý)
     * @param filePath                ÐèÒª±¸·ÝÊý¾ÝµÄÎļþ¼Ð
     * @param filecount                 ±¸·ÝÊý¾ÝµÄ±ÊÊý
     */
    public static void deleteFileRoot(String filePath,int filecount) {
        File file = new File(filePath);
        if(file.exists()) {
            File[] files = file.listFiles();
            Arrays.sort(files, new CompratorByLastModified());
            if(files.length>=filecount && filecount>0) {
                //System.out.println("Îļþ¼Ð¸öÊý£º"+files.length + "\t ×î´ó±ÊÊý£º"+filecount);
                for(int i=(filecount-1);i<files.length;i++) {
                    deleteDir(files[i]);
                }
            }
        }
    }
    
    
    
    
    public static void main(String[] args) {
        deleteFileRoot("d:/aaaa",6);
    }
    
    //±È½ÏÁ½¸öÎļþ¼ÐϵÄÎļþ
    static class CompratorByLastModified implements Comparator<File> {
        public int compare(File f1, File f2) {
            long diff = f1.lastModified() - f2.lastModified();
            if (diff > 0) {
                return -1;//µ¹ÐòÕýÐò¿ØÖÆ
            }else if (diff == 0) {
                return 0;
            }else {
                return 1;//µ¹ÐòÕýÐò¿ØÖÆ
            }
        }
    }
    
    /**
     *     µÝ¹éɾ³ýĿ¼ÏµÄËùÓÐÎļþ¼°×ÓĿ¼ÏÂËùÓÐÎļþ
     * @param dir ½«ÒªÉ¾³ýµÄÎļþĿ¼
     * @return boolean Returns "true" if all deletions were successful.
     *                 If a deletion fails, the method stops attempting to
     *                 delete and returns "false".
     */
    private static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            //µÝ¹éɾ³ýĿ¼ÖеÄ×ÓĿ¼ÏÂ
            for (int i=0; i<children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        // Ä¿Â¼´ËʱΪ¿Õ£¬¿ÉÒÔɾ³ý
        return dir.delete();
    }
}