k94314517
2025-03-26 e87b711cc267567d8374315dc99ef9780cb25dd8
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
package com.doumee.api;
 
import com.doumee.biz.system.SystemDictDataBiz;
import com.doumee.service.business.third.model.ApiResponse;
import com.doumee.core.utils.Constants;
import com.doumee.core.utils.Date;
import com.doumee.core.utils.DateUtil;
import com.doumee.service.business.PlatformJobService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.*;
 
/**
 * @author 江蹄蹄
 * @date 2023/11/30 15:33
 */
@Api(tags = "月台作业定时")
@RestController
@Slf4j
@RequestMapping("/timer/db")
public class DatabaseController extends BaseController {
 
    @Autowired
    private PlatformJobService platformJobService;
    @Autowired
    private SystemDictDataBiz systemDictDataBiz;
 
 
    @ApiOperation("数据库备份,保留最近7个备份sql")
    @GetMapping("/backupDatabase")
    public ApiResponse backupDatabase() {
        try {
            String timestamp = DateUtil.getNowLongTime();
//            String path = "/usr/local/jars/db/";
//            String backupPath = path + timestamp + ".sql";
            String path = systemDictDataBiz.queryByCode(Constants.SYSTEM,Constants.MYSQL_BACKUP_DIR).getCode();
            String code = systemDictDataBiz.queryByCode(Constants.SYSTEM,Constants.MYSQL_BACKUP_CDOE).getCode() ;
            String backupPath = path + timestamp + ".sql";
            code= code.replace("${param}",backupPath);
            log.error("数据库备份================: " + code);
            ProcessBuilder builder = new ProcessBuilder(code);
            // 重定向错误流到标准输出流
            builder.redirectErrorStream(true);
            // stdout
            Process process = builder.start();
            new Thread(new ProcessHandleRunnable(process)).start();
            process.waitFor(); // wait if needed
 
      /*      // 使用mysqldump命令进行数据库备份
            Process process = Runtime.getRuntime().exec(code);
            process.getErrorStream();
            process.getInputStream();
            process.waitFor();*/
 
            // 检查备份是否成功
            if (new File(backupPath).exists()) {
                log.info("数据库备份成功: " + backupPath);
                return ApiResponse.success("数据库备份成功: " + backupPath);
            } else {
                log.error("数据库备份失败.");
            }
            deleteOldFiles(path,7);//保留最近7个文件
        } catch (Exception e) {
            e.printStackTrace();
 
            log.error("数据库备份失败."+e.getMessage());
        }
        return ApiResponse.failed("数据库备份失败" );
    }
    public void run() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String currentDateTime = dateFormat.format(new Date());
        String fileName =  "backup_" + currentDateTime + ".sql";
 
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            Connection connection = DriverManager.getConnection("localhost:3306/antaiwuliu", "root", "Atwl@2024");
            Statement statement = connection.createStatement();
 
            String query = "SELECT * INTO OUTFILE '" + fileName + "' FROM your_table";
            statement.execute(query);
 
            System.out.println("Database backup successful to " + fileName);
 
            statement.close();
            connection.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    public static void main(String[] args) {
         new DatabaseController().run();;
    }
 
    static class ProcessHandleRunnable implements Runnable {
        private Process process;
 
        public ProcessHandleRunnable(Process process) {
            this.process = process;
        }
 
        public void run() {
            BufferedReader br = null;
            InputStreamReader reader = null;
            try {
                System.out.println("start run...");
                reader = new InputStreamReader(process.getInputStream());
                br = new BufferedReader(reader);
                String line = null;
                while ((line = br.readLine()) != null) {
                    System.out.println(line);
                }
                System.out.println("stop run...");
            } catch (IOException ex) {
                ex.printStackTrace();
            } finally {
                try {
                    if (br != null)
                        br.close();
                    if (reader != null)
                        reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    /**
     * @param path
     */
    public   void deleteOldFiles(String path,int num) {
        //文件路径
        List<File> list = getFileSort(path);
        if(list==null || list.size() <= num){
            return;
        }
        for (int i = 0; i <list.size(); i++) {
            if(i>=7){
                list.get(i).delete();
            }
        }
    }
 
    /**
     * 获取目录下所有文件(按时间排序)
     *
     * @param path
     * @return
     */
    public static List<File> getFileSort(String path) {
 
        List<File> list = getFiles(path, new ArrayList<>());
 
        if (list != null && list.size() > 0) {
 
            Collections.sort(list, new Comparator<File>() {
                public int compare(File file, File newFile) {
                    if (file.lastModified() < newFile.lastModified()) {
                        return 1;
                    } else if (file.lastModified() == newFile.lastModified()) {
                        return 0;
                    } else {
                        return -1;
                    }
 
                }
            });
 
        }
 
        return list;
    }
 
    /**
     *
     * 获取目录下所有文件
     *
     * @param realpath
     * @param files
     * @return
     */
    public static List<File> getFiles(String realpath, List<File> files) {
        File realFile = new File(realpath);
        if (realFile.isDirectory()) {
            File[] subfiles = realFile.listFiles();
            for (File file : subfiles) {
                if (file.isDirectory()) {
                    getFiles(file.getAbsolutePath(), files);
                } else {
                    files.add(file);
                }
            }
        }
        return files;
    }
 
}