APDPlat中数据库备份恢复的设计与实现
作者:网络转载 发布时间:[ 2014/2/11 9:39:54 ] 推荐标签:数据库 备份 恢复 设计
下面来看一个MySQL数据库的实现:
/**
*MySQL备份恢复实现
* @author 杨尚川
*/
@Service("MYSQL")
public class MySQLBackupService extends AbstractBackupService{
/**
* MySQL备份数据库实现
* @return
*/
@Override
public boolean backup() {
try {
String path=getBackupFilePath()+DateTypeConverter.toFileName(new Date())+".bak";
String command=PropertyHolder.getProperty("db.backup.command");
command=command.replace("${db.username}", username);
command=command.replace("${db.password}", password);
command=command.replace("${module.short.name}", PropertyHolder.getProperty("module.short.name"));
Runtime runtime = Runtime.getRuntime();
Process child = runtime.exec(command);
InputStream in = child.getInputStream();
try(OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(path), "utf8");BufferedReader reader = new BufferedReader(new InputStreamReader(in, "utf8"))){
String line=reader.readLine();
while (line != null) {
writer.write(line+"
");
line=reader.readLine();
}
writer.flush();
}
LOG.debug("备份到:"+path);
return true;
} catch (Exception e) {
LOG.error("备份出错",e);
}
return false;
}
/**
* MySQL恢复数据库实现
* @param date
* @return
*/
@Override
public boolean restore(String date) {
try {
String path=getBackupFilePath()+date+".bak";
String command=PropertyHolder.getProperty("db.restore.command");
command=command.replace("${db.username}", username);
command=command.replace("${db.password}", password);
command=command.replace("${module.short.name}", PropertyHolder.getProperty("module.short.name"));
Runtime runtime = Runtime.getRuntime();
Process child = runtime.exec(command);
try(OutputStreamWriter writer = new OutputStreamWriter(child.getOutputStream(), "utf8");BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(path), "utf8"))){
String line=reader.readLine();
while (line != null) {
writer.write(line+"
");
line=reader.readLine();
}
writer.flush();
}
LOG.debug("从 "+path+" 恢复");
return true;
} catch (Exception e) {
LOG.error("恢复出错",e);
}
return false;
}
}
这里的关键有两点,一是从配置文件db.properties或db.local.properties中获取指定的命令进行备份和恢复操作,二是为实现类指定注解@Service("MYSQL"),这里服务名称必须和配置文件db.properties或db.local.properties中jpa.database的值一致,jpa.database的值指定了当前使用哪一种数据库,如下所示:
#mysql
db.driver=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/${module.short.name}?useUnicode=true&characterEncoding=UTF-8&createDatabaseIfNotExist=true&autoReconnect=true
db.username=ENC(i/TOu44AD6Zmz0fJwC32jQ==)
db.password=ENC(i/TOu44AD6Zmz0fJwC32jQ==)
jpa.database=MYSQL
db.backup.command=mysqldump -u${db.username} -p${db.password} ${module.short.name}
db.restore.command=mysql -u${db.username} -p${db.password} ${module.short.name}

sales@spasvo.com