package cn.com.threeInOneRoad.task;java
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;spring
import javax.annotation.Resource;sql
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;數據庫
import cn.com.threeInOneRoad.entity.TSysLog;
import cn.com.threeInOneRoad.service.TSysLogService;
import cn.com.threeInOneRoad.util.CommonKeys;
import cn.com.threeInOneRoad.util.DateUtil;
import cn.com.threeInOneRoad.util.Tools;oracle
/**
* 備份oracle數據庫 7天備份一次實時數據,清空一次實時數據
*
* @author x_luwl
*
*/
@Configuration
@EnableScheduling
@Component
public class OracleDatabaseBackup {app
@Value("${spring.datasource.username}")
private String userName;url
@Value("${spring.datasource.password}")
private String password;debug
@Value("${SID}")
private String SID;對象
@Value("${savePath}")
private String savePath;three
@Value("${tablesName}")
private String tablesName;
@Value("${oracleLog}")
private String oracleLog;
@Value("${owner}")
private String owner;
@Value("${spring.datasource.url}")
private String strUrl;
@Value("${spring.datasource.driver-class-name}")
private String driver;
@Resource(name = "tSysLogService")
private TSysLogService tSysLogService;
private final Logger logger = LoggerFactory.getLogger(OracleDatabaseBackup.class);
//每七天的凌晨1點進行備份,刪除實時表
@Async
@Scheduled(cron = "0 0 1 1/7 * ?")
public void exportDatabaseTool() {
Process process = null;
String str = "exp " + userName + "/" + password + "@" + SID + " file=" + savePath + "/oracle_"
+ DateUtil.getCurrentDate() + ".dmp log=" + oracleLog + DateUtil.getCurrentDate() + ".log tables=("
+ tablesName + ")";
try {
File saveFile = new File(savePath);
if (!saveFile.exists()) {// 若是目錄不存在
saveFile.mkdirs();// 建立文件夾
}
long startTime = System.currentTimeMillis();
// 執行命令
process = Runtime.getRuntime().exec(str);
int waitStatus = process.waitFor();
long endTime = System.currentTimeMillis();
float excTime = (float) (endTime - startTime) / 1000;
// 備份成功
if (waitStatus == 0) {
logger.debug("數據庫備份完成,當前時間爲:" + DateUtil.getCurrentTime(), "共消耗時間爲:" + excTime + "s");
// 清除數據
String tableNames[] = tablesName.split(",");
for (String string : tableNames) {
deleteDataInf(string);
}
} else {
// 備份失敗,不刪除表
logger.debug("數據庫備份失敗,當前時間爲:" + DateUtil.getCurrentTime());
}
} catch (IOException | SQLException | InterruptedException e) {
e.printStackTrace();
setErrorToLog(e, "OracleDatabaseBackup", "exportDatabaseTool", "備份數據庫異常");
logger.debug("數據庫備份異常:" + e.getMessage());
} finally {
if (process != null) {
process.destroy();
logger.debug("銷燬進程,當前時間爲:" + DateUtil.getCurrentTime());
}
}
}
// 傳入表名
//鎖表+刪除數據
private void deleteDataInf(String tableName) throws SQLException {
// 數據庫鏈接對象象
Connection connect = null;
Statement stmt = null;
try {
connect = getConnection();
// 設置手動提交事務
connect.setAutoCommit(false);
stmt = connect.createStatement();
// 鎖表操做
stmt.addBatch("lock table " + tableName + " in exclusive mode");
// 執行鎖表命令
stmt.executeBatch();
// 執行數據庫操做
stmt.executeQuery("truncate table " + tableName);
// 提交事務,而且解開表
connect.commit();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
connect.rollback();
} finally {
// 釋放當前數據資源
stmt.close();
if (closeConnection(connect)) {
logger.debug("關閉數據庫鏈接對象成功,當前時間爲:" + DateUtil.getCurrentTime() + "當前操做表爲:" + tableName);
} else {
logger.debug("關閉數據庫鏈接對象失敗,當前時間爲:" + DateUtil.getCurrentTime() + "當前操做表爲:" + tableName);
}
}
}
// 建立數據庫鏈接
private Connection getConnection() throws ClassNotFoundException, SQLException {
logger.debug("建立數據庫鏈接,當前時間爲:" + DateUtil.getCurrentTime());
// 加載驅動
Class.forName(driver);
// 獲取鏈接
return DriverManager.getConnection(strUrl, userName, password);
}
// 關閉數據庫鏈接
private boolean closeConnection(Connection conn) throws SQLException {
if (conn != null) {
conn.close();
}
return conn.isClosed();
}
/**
*
* @param e
* 異常
* @param function
* 類名
* @param method
* 方法名
* @param memo
* 描述
*/
private void setErrorToLog(Exception e, String function, String method, String memo) {
TSysLog tlog = new TSysLog();
tlog.setInsTime(Tools.getTimeStamp(DateUtil.getCurrentTime()));
tlog.setIpAddr("");
tlog.setIsdelete((short) 0);
tlog.setOpTime(Tools.getTimeStamp(DateUtil.getCurrentTime()));
tlog.setOpType(CommonKeys.TSYSLOG.TYPE_HOUTAIRENWU);
tlog.setOpFunc(function);
tlog.setOpResult(CommonKeys.TSYSLOG.RESULT_FAIL);
tlog.setOpAction(method);
tlog.setErrMsg(getExceptionDetail(e));
tlog.setMemo("定時任務報錯:" + memo + "---------------" + e.getMessage());
tlog.setOpUserid("");
tSysLogService.save(tlog);
}
private String getExceptionDetail(Exception e) {
StringBuffer stringBuffer = new StringBuffer(e.toString() + "\n");
StackTraceElement[] messages = e.getStackTrace();
int length = messages.length;
for (int i = 0; i < length; i++) {
stringBuffer.append("\t" + messages[i].toString() + "\n");
}
return stringBuffer.substring(0, 250).toString();
}
}