Browse Source

新增数据库定时备份功能

新增气象预警数量查询功能
develop
zhaoxianglong 9 months ago
parent
commit
2a2f84aea3
  1. 10
      ruoyi-common/src/main/java/com/ruoyi/common/config/RuoYiConfig.java
  2. 119
      zc-business/src/main/java/com/zc/business/controller/DcMYSQLJob.java
  3. 140
      zc-business/src/main/java/com/zc/business/controller/DcMYSQLUtil.java
  4. 63
      zc-business/src/main/java/com/zc/business/controller/WeatherForecastController.java

10
ruoyi-common/src/main/java/com/ruoyi/common/config/RuoYiConfig.java

@ -5,7 +5,7 @@ import org.springframework.stereotype.Component;
/**
* 读取项目相关配置
*
*
*/
@Component
@ConfigurationProperties(prefix = "ruoyi")
@ -154,4 +154,12 @@ public class RuoYiConfig
{
return getProfile() + "/boardImg";
}
/**
* 获取sql文件下载路径
*/
public static String getDownloadMysqlPath()
{
return getProfile() + "/mysql";
}
}

119
zc-business/src/main/java/com/zc/business/controller/DcMYSQLJob.java

@ -0,0 +1,119 @@
package com.zc.business.controller;
import com.ruoyi.common.config.RuoYiConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
/**
* 数据库定时备份任务
* 在backup文件夹中备份最近七日的数据库文件, 备份文件夹 与当前程序同一目录
*/
@Component
@Slf4j
public class DcMYSQLJob {
private final Environment environment;
private static final String IP = "10.0.81.202";
private static final String PORT = "3306";
private static final String USER = "root";
private static final String PASSWORD = "mysql123!@#";
public DcMYSQLJob(Environment environment) {
this.environment = environment;
}
@Scheduled(cron = "0 0 22 * * ?")
//@Scheduled(cron = "0 25 * * * ?")
public void backupAthena() throws IOException {
String url = "jdbc:mysql://10.0.81.202:3306/athena?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true";
extracted(url, "athena");
}
@Scheduled(cron = "0 30 22 * * ?")
//@Scheduled(cron = "0 27 * * * ?")
public void backupJiHeDC() throws IOException {
// 数据库配置信息
String url = "jdbc:mysql://10.0.81.202:3306/jihe-dc?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true";
extracted(url, "jihe-dc");
}
@Scheduled(cron = "0 0 23 * * ?")
//@Scheduled(cron = "0 56 * * * ?")
public void backupJiHeDCPro() throws IOException {
// 数据库配置信息
String url = "jdbc:mysql://10.0.81.202:3306/jihe-dc-pro?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=GMT%2B8&allowPublicKeyRetrieval=true";
extracted(url, "jihe-dc-pro");
}
private static void extracted(String url, String nameOfTheDatabase) throws IOException {
LocalDateTime now = LocalDateTime.now();
log.info("*******************时间:【{}】, 系统开启定时任务数据库备份*******************", now);
// 第三个 :号下标
int subStrIndex = url.indexOf(":", url.indexOf(":", url.indexOf(":") + 1) + 1);
// IP
String host = url.substring(url.indexOf("//") + 2, subStrIndex);
// 端口
String subStr2 = url.substring(subStrIndex);
String port = subStr2.substring(1, subStr2.indexOf("/"));
// 数据库名
String dataBaseName = subStr2.substring(subStr2.indexOf("/") + 1, subStr2.indexOf("?"));
// 环境
String os = System.getProperties().getProperty("os.name");
log.info("备份环境信息:【{}】, 用户名:【{}】,密码:【{}】, 地址:【{}】, 端口:【{}】,数据库:【{}】", os, url, PASSWORD, host, port, dataBaseName);
LocalDate localDate = LocalDate.now();
String filePath = RuoYiConfig.getDownloadMysqlPath();
Date date = new Date();
String format = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss ").format(date).replace(" ", "");
String fileName = nameOfTheDatabase + "_" + format + ".sql";
File file = new File(filePath, fileName);
file.getParentFile().mkdirs();
file.createNewFile();
// 备份今天数据库
DcMYSQLUtil.backup(IP, PORT, USER, PASSWORD, dataBaseName, file);
// 删除七天前数据库备份文件 LocalDate
LocalDate before = localDate.minusDays(7);
String fileBeforeName = nameOfTheDatabase + "-" + before + ".sql";
File fileBefore = new File(filePath, fileBeforeName);
if (fileBefore.exists()) {
fileBefore.delete();
}
log.info("*******************时间:【{}】, 系统结束定时任务数据库备份*******************", now);
}
}

140
zc-business/src/main/java/com/zc/business/controller/DcMYSQLUtil.java

@ -0,0 +1,140 @@
package com.zc.business.controller;
import java.io.*;
public class DcMYSQLUtil {
/**
* 导出sql文件
*
* @param host ip地址
* @param port 端口
* @param userName 用户名
* @param password 密码
* @param dbName 数据库名
* @param file 文件对象
*/
public static void backup(String host, String port, String userName, String password, String dbName, File file) {
String cmd = "mysqldump --single-transaction " + " -h" + host + " -P" + port + " -u" + userName + " -p" + password + " --databases --skip-extended-insert " + dbName + " > " + file.getPath();
String os = System.getProperties().getProperty("os.name");
if (os.contains("Windows")) {
// Windows 需要加上 cmd /c
cmd = "cmd /c " + cmd;
}
System.out.printf("cmd命令为:%s%n", cmd);
try {
Process process = Runtime.getRuntime().exec(cmd);
if (process.waitFor() == 0) {
System.out.printf(" 数据库:%s 备份成功!%n", dbName);
} else {
System.out.printf(" 数据库:%s 备份失败!%n", dbName);
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
// /**
// * 导入sql文件
// *
// * @param host ip地址
// * @param port 端口
// * @param userName 用户名
// * @param password 密码
// * @param databaseName 数据库名
// * @param file 文件对象
// */
// public static void reduction(String host, String port, String userName, String password, String databaseName, File file) throws Exception {
// if (!file.exists()) {
// System.out.printf("文件:%s 不存在,请检查%n", file.getPath());
// return;
// }
// String filePath = file.getPath();
// String cmd = "mysql -h" + host + " -P" + port + " -u" + userName + " -p" + password + " " + databaseName + " < " + filePath;
// String os = System.getProperties().getProperty("os.name");
// if (os.contains("Windows")) {
// // Windows 需要加上 cmd /c
// cmd = "cmd /c " + cmd;
// }
// System.out.printf("数据库还原命令:%s%n", cmd);
//
//
// //拼接cmd命令
// Process exec = Runtime.getRuntime().exec(cmd);
// if (exec.waitFor() == 0) {
// System.out.printf("数据库:%s 还原成功,还原的文件为:%s%n", databaseName, filePath);
// } else {
// System.out.println(databaseName + "数据库还原失败");
// System.out.printf("数据库:%s 还原失败", databaseName);
// }
// }
//
//
// /**
// * 导入sql文件
// *
// * @param file 文件对象
// * @param user 用户
// * @param password 密码
// * @param db 数据库
// */
// public static void load(File file, String user, String password, String db) {
// try {
// Runtime rt = Runtime.getRuntime();
// String command = "mysql -u" + user + " -p" + password + " --default-character-set=utf8 " + db;
// Process child = rt.exec(command);
// OutputStream outputStream = child.getOutputStream();
// BufferedReader bufferedReader = new BufferedReader(
// new InputStreamReader(Files.newInputStream(file.toPath()), StandardCharsets.UTF_8));
// OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8);
// String str;
// while ((str = bufferedReader.readLine()) != null) {
// outputStreamWriter.write(str + "\r\n");
// }
// outputStreamWriter.flush();
// outputStream.close();
// bufferedReader.close();
// outputStreamWriter.close();
// System.out.println("数据库导入完成");
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
//
//
///*
// public static void main(String[] args) throws Exception {
// File file = new File("C:\\Users\\hansonh\\Desktop\\jar", "backup.sql");
//
//
// System.out.println("系统环境:" + System.getProperties().getProperty("os.name"));
//
// String subStr = "jdbc:mysql://127.0.0.1:3306/pms?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true&verifyServerCertificate=false&useSSL=false&rewriteBatchedStatements=true&zeroDateTimeBehavior=convertToNull";
//
//
// // 第三个 :号下标
// int subStrIndex = subStr.indexOf(":", subStr.indexOf(":", subStr.indexOf(":") + 1) + 1);
// // IP
// String host = subStr.substring(subStr.indexOf("//") + 2, subStrIndex);
// System.out.println("IP:" + host);
//
// // 端口
// String subStr2 = subStr.substring(subStrIndex);
// String port = subStr2.substring(1, subStr2.indexOf("/"));
// System.out.println("端口:" + port);
//
// // 数据库名
// String dataBaseName = subStr2.substring(subStr2.indexOf("/") + 1, subStr2.indexOf("?"));
//
// System.out.println("数据库名:" + dataBaseName);
//
// // 备份数据库
// DbUtil.backup( "127.0.0.1","3306", "dev1", "dev1", "pms", file);
// // 恢复数据库
//// DbUtil.reduction( "127.0.0.1","3306", "root", "123456", "pms", file);
// }
//
// */
}

63
zc-business/src/main/java/com/zc/business/controller/WeatherForecastController.java

@ -1,5 +1,6 @@
package com.zc.business.controller;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
@ -66,7 +67,67 @@ public class WeatherForecastController extends BaseController {
}
/*
* 气象预警查询
* 气象预警数量查询
* */
@ApiOperation("气象预警数量查询")
@PostMapping(value = "/queryTheNumberOfMeteorologicalWarning")
public AjaxResult queryTheNumberOfMeteorologicalWarning() throws HttpException, IOException {
JSONObject jsonObject = new JSONObject();
JSONObject cacheObject = redisCache.getCacheObject(METEOROLOGICALEARLYWARNING);
if (cacheObject != null) {
jsonObject = cacheObject;
} else {
List<DcRegion> list = dcRegionService.list();
for (DcRegion dcRegion : list) {
OkHttp okHttp = new OkHttp();
Response response // 请求响应
= okHttp
.headers(new HashMap<>())
.url(METEOROLOGICALEARLYWARNINGURI + dcRegion.getLongitude() + "," + dcRegion.getLatitude() + KEY + METEOROLOGICALEARLYWARNINGKEY) // 请求地址
.get(); // 请求方法
if (response.body() != null) {
JSONObject jsonResult = JSONObject.parseObject(response.body().string());
if (jsonResult.getInteger("code") == 200) {
jsonObject.put(METEOROLOGICALEARLYWARNING + dcRegion.getId(), extracted(jsonResult, "warning"));
} else {
return AjaxResult.error(jsonResult.getInteger("code"), "请求失败");
}
}
}
}
redisCache.setCacheObject(METEOROLOGICALEARLYWARNING, jsonObject, 13, TimeUnit.MINUTES);
JSONArray meteorologicalEarlyWarning1 = jsonObject.getJSONArray("meteorologicalEarlyWarning1");
JSONArray meteorologicalEarlyWarning2 = jsonObject.getJSONArray("meteorologicalEarlyWarning2");
JSONArray meteorologicalEarlyWarning3 = jsonObject.getJSONArray("meteorologicalEarlyWarning3");
JSONArray meteorologicalEarlyWarning4 = jsonObject.getJSONArray("meteorologicalEarlyWarning4");
JSONArray meteorologicalEarlyWarning5 = jsonObject.getJSONArray("meteorologicalEarlyWarning5");
JSONArray meteorologicalEarlyWarning6 = jsonObject.getJSONArray("meteorologicalEarlyWarning6");
JSONArray meteorologicalEarlyWarning7 = jsonObject.getJSONArray("meteorologicalEarlyWarning7");
JSONArray meteorologicalEarlyWarning8 = jsonObject.getJSONArray("meteorologicalEarlyWarning8");
return AjaxResult.success(meteorologicalEarlyWarning1.size() +
meteorologicalEarlyWarning2.size() +
meteorologicalEarlyWarning3.size() +
meteorologicalEarlyWarning4.size() +
meteorologicalEarlyWarning5.size() +
meteorologicalEarlyWarning6.size() +
meteorologicalEarlyWarning7.size() +
meteorologicalEarlyWarning8.size()
);
}
/*
* 逐小时天气查询
* */
@ApiOperation("逐小时天气查询")
@PostMapping(value = "/hourlyWeather")

Loading…
Cancel
Save