java实现的MySQL自动备份和还原(struts2+Hibernate)---兼容 wi_MySQL
HibernateStruts2
相信很多朋友都经历过数据库出问题的情况,我也同样(见我的上一篇博文:phpmyadmin误删表后的恢复过程(心惊胆跳啊) )。如果数据很大或者很重要,那么恢复起来是相当困难的,所以我们在做一个相对完善的系统时,数据库的备份/还原功能是必不可少的。本文将在javaEE环境下实现MySQL的自动备份/还原,使用了struts2和hibernate框架,MySQL版本是5.1.16。
下图展示的是web application的执行流程,
Timer是在一个随着application启动而启动的servlet中初始化,并接受一个名叫‘BACKUP_DEPLY'的参数,它告诉Timer多久去备份一次数据库(单位为小时):
1 <servlet> 2 <servlet-name>StartupServlet</servlet-name> 3 <servlet-class>com.nerve.web.servlet.StartupServlet</servlet-class> 4 5 <load-on-startup>1</load-on-startup> 6 7 <init-param> 8 <param-name>BACKUP_DELAY</param-name> 9 <param-value>24</param-value><!--自动备份程序执行间隔,单位为小时-->10 </init-param>11 </servlet>
每次备份数据库后,会将备份信息保存到数据库中,为此我们定义了一个PO,如下:
1 public class Backup{2 private int id;3 private String name;4 private long size;5 private Date addDate;6 7 //setter and getter8 }
上图是备份过程中主要用到的类,大概过程为:
1.当Timer开始执行备份操作时,会调用BackupService(BackupServiceImpl为其实现类)中的backup()方法
2.BackupService会实例化一个BackWorker(MySQLBackupWorker为其实现类),并调用它的backup(boolean isRestore)throws Excetion方法来完成备份
3.当BackupWorker的isDone()方法返回true时,则表示备份成功(这时可以通过BackupWorker的getFileName()方法获取保存的文件名),否则是失败
BackupWorker接口定义如下:
1 public interface BackupWorker { 2 3 public void backup(boolean isRestore) throws Exception; 4 5 public void reload(String path) throws Exception; 6 7 /** 8 * 是否备份成功 9 * @method name: isDone10 * @return type: boolean11 *@return12*/13 public boolean isDone();14 15 /**16 * 获取备份后文件的名称(不包括目录)17 * @method name: getFileName18 * @return type: String19 *@return20*/21 public String getFileName();22 23 /**24 * 获取备份后文件的大小25 * @method name: getFileSize26 * @return type: long27 *@return28*/29 public long getFileSize();30 31 /**32 * 获取配置文件中自动备份的时间间隔,单位为小时33 * @method name: getHours34 * @return type: int35 *@return36*/37 public int getHours();38 39 /**40 * 更新自动备份的时间间隔41 * @method name: setHours42 * @return type: void43 *@param hours44*/45 public void setHours(int hours);46 47 /**48 * 删除备份文件49 * @method name: delete50 * @return type: void51 *@param fileName52*/53 public void delete(String fileName);54 }
MySQLBackupWorker是MySQL的备份/还原类,实现了BackupWorker接口,在构造函数被执行时,会读取我们预设的MySQL相关设置(即上面类图中的MySQLBackup.properties),配置文件中包含如下内容:
(使用时,请将这些配置修改为本机的实际值,当OS为Linux是,mysqlpath可以不用设置,前提是 mysqldump 命令有效)
下面是MySQLBackupWorker中在window环境下的备份实现(默认的编码是utf-8,可以改为本机值):
1 public void backup(boolean isRe) throws Exception { 2 boolean isWindow = isWindowsOS(); 3 isRestore = isRe; 4 if(isWindow){ 5 this.backupWindow(); 6 }else{ 7 this.backupLinux(); 8 } 9 }10 11 /**12 * window下的mysql备份13 * @method name: backupWindow14 * @return type: void15*/16 private void backupWindow(){17 try {18 String sqlPath = bkPath + getBackupName();19 mkDir(sqlPath);20 21 StringBuffer sb = new StringBuffer();22 sb.append(mysqlPath);23 sb.append("mysqldump ");24 sb.append("--opt ");25 sb.append("-h ");26 sb.append(host);27 sb.append(" ");28 sb.append("--user=");29 sb.append(loginName);30 sb.append(" ");31 sb.append("--password=");32 sb.append(loginPass);33 sb.append(" ");34 sb.append("--lock-all-tables=true ");35 sb.append("--result-file=");36 sb.append(sqlPath);37 sb.append(" ");38 sb.append("--default-character-set=utf8 ");39 sb.append(dbName);40 41 System.out.println(sb.toString());42 Runtime cmd = Runtime.getRuntime();43 try {44 Process p = cmd.exec(sb.toString());45 int tag = p.waitFor();46 System.out.println("result::: "+tag);47 if(tag == 0)48 done = true;49 } catch (IOException e) {50 e.printStackTrace();51 }52 } catch (Exception e) {53 e.printStackTrace();54 }55 }
获取更多源代码:源代码
【本文为小弟原创文章,引用请注明出处,谢谢】

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

DeepSeek is a powerful intelligent search and analysis tool that provides two access methods: web version and official website. The web version is convenient and efficient, and can be used without installation; the official website provides comprehensive product information, download resources and support services. Whether individuals or corporate users, they can easily obtain and analyze massive data through DeepSeek to improve work efficiency, assist decision-making and promote innovation.

There are many ways to install DeepSeek, including: compile from source (for experienced developers) using precompiled packages (for Windows users) using Docker containers (for most convenient, no need to worry about compatibility) No matter which method you choose, Please read the official documents carefully and prepare them fully to avoid unnecessary trouble.

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

BITGet is a cryptocurrency exchange that provides a variety of trading services including spot trading, contract trading and derivatives. Founded in 2018, the exchange is headquartered in Singapore and is committed to providing users with a safe and reliable trading platform. BITGet offers a variety of trading pairs, including BTC/USDT, ETH/USDT and XRP/USDT. Additionally, the exchange has a reputation for security and liquidity and offers a variety of features such as premium order types, leveraged trading and 24/7 customer support.

Ouyi OKX, the world's leading digital asset exchange, has now launched an official installation package to provide a safe and convenient trading experience. The OKX installation package of Ouyi does not need to be accessed through a browser. It can directly install independent applications on the device, creating a stable and efficient trading platform for users. The installation process is simple and easy to understand. Users only need to download the latest version of the installation package and follow the prompts to complete the installation step by step.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Gate.io is a popular cryptocurrency exchange that users can use by downloading its installation package and installing it on their devices. The steps to obtain the installation package are as follows: Visit the official website of Gate.io, click "Download", select the corresponding operating system (Windows, Mac or Linux), and download the installation package to your computer. It is recommended to temporarily disable antivirus software or firewall during installation to ensure smooth installation. After completion, the user needs to create a Gate.io account to start using it.

Ouyi, also known as OKX, is a world-leading cryptocurrency trading platform. The article provides a download portal for Ouyi's official installation package, which facilitates users to install Ouyi client on different devices. This installation package supports Windows, Mac, Android and iOS systems. Users can choose the corresponding version to download according to their device type. After the installation is completed, users can register or log in to the Ouyi account, start trading cryptocurrencies and enjoy other services provided by the platform.
