前言:
首先讲述下工作场景:基于springboot 架构,对现有库中已知集合进行备份操作
pom.xml 需要添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver</artifactId>
<version>3.10.1</version><!--因人而异-->
</dependency>
这里我就直接上实现逻辑 至于controller、service 等就不再赘述
首先是备份
import com.example.demohb.daoMan.OperationLog;
import com.example.demohb.service.BaseBackupService;
import com.example.demohb.service.OperationLogService;
import com.example.demohb.utils.DateTimeUtil;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.mongodb.ConnectionString;
import com.mongodb.MongoClientSettings;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.Sorts;
import org.apache.commons.lang3.ObjectUtils;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
//已知备份库集合
@Value("${list}")
private List<String> collection_name;
//备份库连接
@Value("${mongo_url}")
private String mongo_url;
//备份库
@Value("${database_name}")
private String dataBase_name;
//备份储存地址
@Value("${backup_file_prefix}")
private String backup_file_prefix;
//回写库地址
@Value("${restore_url}")
private String restore_url;
//回写库
@Value("${restore_name}")
private String restore_name;
/**
* 数据库备份
*
* @param request
*/
@Override
public void getBaseBackup(HttpServletRequest request, HttpServletResponse response) {
// 创建MongoDB客户端
MongoClientSettings settings = MongoClientSettings.builder()
.applyConnectionString(new ConnectionString(mongo_url))
.build();
MongoClient mongoClient = MongoClients.create(settings);
// 获取MongoDB数据库
MongoDatabase database = mongoClient.getDatabase(dataBase_name);
//获取年月日--方便一后通过文件夹来选择恢复那天的数据
String date = DateTimeUtil.dateTime();
//判断文件是否存在
String urlPath = backup_file_prefix + date + "\\";
File backupFile = new File(urlPath);
if (!backupFile.exists()) {
backupFile.mkdirs();
}
//通过表名循环备份数据库
for (String key : collection_name) {
// 创建备份文件名
String backupFileName = urlPath + "backup_" + key + ".json";
// 获取MongoDB集合
MongoCollection<org.bson.Document> collectionDB = database.getCollection(key);
// 创建备份文件输出流
try (OutputStream putStream = new FileOutputStream(backupFileName)) {
// 查询集合中的所有文档并写入备份文件
collectionDB.find().sort(Sorts.ascending("_id")).forEach((Document document) -> {
try {
putStream.write(document.toJson().getBytes());
putStream.write("\n".getBytes());
} catch (IOException e) {
e.printStackTrace();
}
});
} catch (Exception e) {
throw new RuntimeException("备份异常");
}
}
// 关闭MongoDB客户端
mongoClient.close();
}
其次是恢复
/**
* 恢复还原数据表
*
* @param request
*/
@Override
public void baseReduction(String timePath, HttpServletRequest request) {
MongoClientSettings settings;
if (ObjectUtils.isEmpty(restore_url)) {
settings = MongoClientSettings.builder()
.applyConnectionString(new ConnectionString(mongo_url))
.build();
} else {
settings = MongoClientSettings.builder()
.applyConnectionString(new ConnectionString(restore_url))
.build();
}
MongoClient mongoClient = MongoClients.create(settings);
// 获取MongoDB数据库
MongoDatabase database = mongoClient.getDatabase(restore_name);
//文件地址组合
String urlPath = backup_file_prefix + timePath + "\\";
File backupFile = new File(urlPath);
if (!backupFile.exists()) {
throw new IllegalStateException("被选目录无法找到");
}
//通过表名循环备份数据库
for (String key : collection_name) {
String filePath = urlPath + "backup_" + key + ".json";
// 获取MongoDB集合
MongoCollection<org.bson.Document> collection = null;
try {
collection = database.getCollection(key);
} catch (Exception e) {
System.out.println("集合 " + key + " 不存在,现在创建...");
database.createCollection(key);
}
//判断文件是否存在
FileReader fileReader = null;
try {
fileReader = new FileReader(filePath);
} catch (FileNotFoundException e) {
continue;
}
// 获取文件数据集合
List<Document> documents = new ArrayList<Document>();
// 由于上方判断是否是有,存在新建集合所以再此获取MongoDB集合
collection = database.getCollection(key);
//回写数据库
Gson gson = new GsonBuilder().create();
try (BufferedReader br = new BufferedReader(fileReader)) {
String line;
while ((line = br.readLine()) != null) {
collection.drop();
// Document doc = gson.fromJson(line, Document.class);
Document doc = Document.parse(line);
documents.add(doc);
}
collection.insertMany(documents);
} catch (IOException e) {
e.printStackTrace();
}
}
mongoClient.close();
}
本次相对简单,相对固定,后续若有比较好的写法咱们评论区探讨下!!!