APDPlat中数据库备份恢复的设计与实现
作者:网络转载 发布时间:[ 2014/2/11 9:39:54 ] 推荐标签:数据库 备份 恢复 设计
对于各个不同的数据库来说,有一些通用的操作,如对加密的数据库用户名和密码的解密操作,还有接口定义的备份文件存放的本地文件系统路径,用一个抽象类来实现接口中的通用方法以及其他通用方法如decrypt:
/**
*备份恢复数据库抽象类,抽象出了针对各个数据库来说通用的功能
* @author
*/
public abstract class AbstractBackupService implements BackupService{
protected final APDPlatLogger LOG = new APDPlatLogger(getClass());
protected static final StandardPBEStringEncryptor encryptor;
protected static final String username;
protected static final String password;
//从配置文件中获取数据库用户名和密码,如果用户名和密码被加密,则解密
static{
EnvironmentStringPBEConfig config=new EnvironmentStringPBEConfig();
config.setAlgorithm("PBEWithMD5AndDES");
config.setPassword("config");
encryptor=new StandardPBEStringEncryptor();
encryptor.setConfig(config);
String uname=PropertyHolder.getProperty("db.username");
String pwd=PropertyHolder.getProperty("db.password");
if(uname!=null && uname.contains("ENC(") && uname.contains(")")){
uname=uname.substring(4,uname.length()-1);
username=decrypt(uname);
}else{
username=uname;
}
if(pwd!=null && pwd.contains("ENC(") && pwd.contains(")")){
pwd=pwd.substring(4,pwd.length()-1);
password=decrypt(pwd);
}else{
password=pwd;
}
}
@Override
public String getBackupFilePath(){
String path="/WEB-INF/backup/"+PropertyHolder.getProperty("jpa.database")+"/";
path=FileUtils.getAbsolutePath(path);
File file=new File(path);
if(!file.exists()){
file.mkdirs();
}
return path;
}
@Override
public File getNewestBackupFile(){
Map<String,File> map = new HashMap<>();
List<String> list = new ArrayList<>();
String path=getBackupFilePath();
File dir=new File(path);
File[] files=dir.listFiles();
for(File file : files){
String name=file.getName();
if(!name.contains("bak")) {
continue;
}
map.put(name, file);
list.add(name);
}
if(list.isEmpty()){
return null;
}
//按备份时间排序
Collections.sort(list);
//新备份的在前面
Collections.reverse(list);
String name = list.get(0);
File file = map.get(name);
//加速垃圾回收
list.clear();
map.clear();
return file;
} @Override
public List<String> getExistBackupFileNames(){
List<String> result=new ArrayList<>();
String path=getBackupFilePath();
File dir=new File(path);
File[] files=dir.listFiles();
for(File file : files){
String name=file.getName();
if(!name.contains("bak")) {
continue;
}
name=name.substring(0, name.length()-4);
String[] temp=name.split("-");
String y=temp[0];
String m=temp[1];
String d=temp[2];
String h=temp[3];
String mm=temp[4];
String s=temp[5];
name=y+"-"+m+"-"+d+" "+h+":"+mm+":"+s;
result.add(name);
}
//按备份时间排序
Collections.sort(result);
//新备份的在前面
Collections.reverse(result);
return result;
}
/**
* 解密用户名和密码
* @param encryptedMessage 加密后的用户名或密码
* @return 解密后的用户名或密码
*/
protected static String decrypt(String encryptedMessage){
String plain=encryptor.decrypt(encryptedMessage);
return plain;
}
}

sales@spasvo.com