SpringBoot+SpringCloud+vue+Element开发项⽬——数据备份还
⼀、新建⼯程
新建jansens-backup⼯程,这是⼀个独⽴运⾏于admin的服务模块,可以分开独⽴部署
⼆、添加依赖
在l⽂件中添加web、swagger、common依赖包。
<dependencies>
<!-- spring boot -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- swagger -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId&ad</groupId>
<artifactId>jansens-common</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
</dependencies>
三、添加配置
# tomcat
server:
port: 8002
spring:
application:
name: jansens-backup
# backup datasource
jansens:
backup:
datasource:
host: localhost
userName: root
password: 123456
database: jansens
四、⾃定义Banner⽂件
在resources⽬录下添加⼀个⾃定义⽂件
////////////////////////////////////////////////////////////////////
//                          _ooOoo_                              //
//                        o8888888o                              //
//                        88" . "88                              //
//                        (| ^_^ |)                              //
//                        O\  =  /O                              //
//                      ____/`---'\____                          //
//                    .'  \\|    |//  `.                        //
/
/                  /  \\|||  :  |||//  \                        //
//                  /  _||||| -:- |||||-  \                      //
//                  |  | \\\  -  /// |  |                      //
//                  | \_|  ''\---/''  |  |                      //
//                  \  .-\__  `-`  ___/-. /                      //
//                ___`. .'  /--.--\  `. . ___                    //
//              ."" '<  `.___\_<|>_/___.'  >'"".                  //
//            | | :  `- \`.;`\ _ /`;.`/ - ` : | |                //
//            \  \ `-.  \_ __\ /__ _/  .-` /  /                //
//      ========`-.____`-.___\_____/___.-`____.-'========        //
//                          `=---='                              //
/
/      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^        //
//            佛祖保佑上海研发永⽆BUG                    //
////////////////////////////////////////////////////////////////////
五、修改启动类
修改启动类为JansensBackupApplication,指定扫描路径为com.louis.jansens JansensBackupApplication.java
@SpringBootApplication(scanBasePackages={"com.louis.jansens"})
@EnableSwagger2
public class JansensBackupApplication {
public static void main(String[] args) {
SpringApplication.run(JansensBackupApplication.class, args);
}
}
六、跨域配置
在config包添加跨域配置类
CorsConfig.java
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")    // 允许跨域访问的路径
.allowedOrigins("*")    // 允许跨域访问的源
.allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")    // 允许请求⽅法                .maxAge(168000)    // 预检间隔时间
.allowedHeaders("*")  // 允许头部设置
.allowCredentials(true);    // 是否发送cookie
}
}
七、Swagger配置
在config包添加swagger配置类
SwaggerConfig.java
/**
* Swagger配置
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2).select()
.apis(RequestHandlerSelectors.any()).paths(PathSelectors.any()).build();
}
}
⼋、数据源属性
BackupDataSourceProperties.java
/**
* 数据源
*/
@Component
@ConfigurationProperties(prefix = "jansens.backup.datasource")
public class BackupDataSourceProperties {
private String host;
private String userName;
private String password;
private String database;
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getDatabase() {
return database;
}
public void setDatabase(String database) {
this.database = database;
}
}
九、备份还原接⼝
在service包下添加MysqlBackupService接⼝
MysqlBackupService.java
/**
* MySql命令⾏备份恢复服务
*/
public interface MysqlBackupService {
/**
* 备份数据库
* @param host host地址,可以是本机也可以是远程
* @param userName 数据库的⽤户名
* @param password 数据库的密码
* @param savePath 备份的路径
* @param fileName 备份的⽂件名
* @param databaseName 需要备份的数据库的名称
* @return
* @throws IOException
*/
boolean backup(String host, String userName, String password, String backupFolderPath, String fileName, String database) throws Exception; /**
* 恢复数据库
* @param restoreFilePath 数据库备份的脚本路径
* @param host IP地址
* @param database 数据库名称
* @param userName ⽤户名
* @param password 密码
* @return
*/
boolean restore(String restoreFilePath, String host, String userName, String password, String database) throws Exception;
}
⼗、备份还原实现
在service.impl包下添加MysqlBackupServiceImpl实现类
MysqlBackupServiceImpl.java
@Service
public class MysqlBackupServiceImpl implements MysqlBackupService {
@Override
public boolean backup(String host, String userName, String password, String backupFolderPath, String fileName,
String database) throws Exception {
return MySqlBackupRestoreUtils.backup(host, userName, password, backupFolderPath, fileName, database);
}
@Override
public boolean restore(String restoreFilePath, String host, String userName, String password, String database)
throws Exception {
store(restoreFilePath, host, userName, password, database);
}
}
⼗⼀、备份还原逻辑
在util包下创建⼀个备份还原⼯具类
MySqlBackupRestoreUtils.java
/**
* MySQL备份还原⼯具类
*/
public class MySqlBackupRestoreUtils {
/
**
* 备份数据库
* @param host host地址,可以是本机也可以是远程
* @param userName 数据库的⽤户名
* @param password 数据库的密码
* @param savePath 备份的路径
* @param fileName 备份的⽂件名
* @param databaseName 需要备份的数据库的名称
* @return
* @throws IOException
*/
public static boolean backup(String host, String userName, String password, String backupFolderPath, String fileName,
String database) throws Exception {
File backupFolderFile = new File(backupFolderPath);
if (!ists()) {
// 如果⽬录不存在则创建
backupFolderFile.mkdirs();
}
if (!dsWith(File.separator) && !dsWith("/")) {
backupFolderPath = backupFolderPath + File.separator;
}
// 拼接命令⾏的命令
String backupFilePath = backupFolderPath + fileName;
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("mysqldump --opt").append(" --add-drop-database").append(" --add-drop-table");
stringBuilder.append(" -h").append(host).append(" -u").append(userName).append(" -p").append(password);
stringBuilder.append(" --result-file=").append(backupFilePath).append(".sql").append(" --default-character-set=utf8 ").append(database);        System.out.String());
// 调⽤外部执⾏ exe ⽂件的 Java API
Process process = Runtime().exec(String()));
if (process.waitFor() == 0) {
// 0 表⽰线程正常终⽌
System.out.println("数据已经备份到 " + backupFilePath + " ⽂件中");
return true;
}
return false;
}
/**
* 还原数据库
* @param restoreFilePath 数据库备份的脚本路径
* @param host IP地址
* @param database 数据库名称
* @param userName ⽤户名
* @param password 密码
* @return
*/
public static boolean restore(String restoreFilePath, String host, String userName, String password, String database)
throws Exception {
File restoreFile = new File(restoreFilePath);
if (restoreFile.isDirectory()) {
for (File file : restoreFile.listFiles()) {
if (ists() && Path().endsWith(".sql")) {
restoreFilePath = AbsolutePath();
break;
}
}
}
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("mysql -h").append(host).append(" -u").append(userName).append(" -p").append(password);
stringBuilder.append("").append(database).append(" < ").append(restoreFilePath);
try {
Process process = Runtime().exec(String()));
if (process.waitFor() == 0) {
System.out.println("数据已从 " + restoreFilePath + " 导⼊到数据库中");
}
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
private static String[] getCommand(String command) {
String os = Property("os.name");
String shell = "/bin/bash";
String c = "-c";
LowerCase().startsWith("win")){
shell = "cmd";
c = "/c";
}
String[] cmd = { shell, c, command };
return cmd;
}
public static void main(String[] args) throws Exception {
String host = "localhost";
String userName = "root";
String password = "123456";
String database = "jansens";
System.out.println("开始备份");
String backupFolderPath = "d:/dev/";
String fileName = "mdh";
backup(host, userName, password, backupFolderPath, fileName, database);        System.out.println("备份成功");
/*System.out.println("开始还原");
String restoreFilePath = "d:/dev/mdh.sql";
restore(restoreFilePath, host, userName, password, database);
System.out.println("还原成功");*/
}
}
在util包HTTP结果封装类
HttpResult.java
/**
* HTTP结果封装
*/
public class HttpResult {
private int code = 200;
private String msg;
private Object data;
public static HttpResult error() {
return error(500, "未知异常,请联系管理员");
}
public static HttpResult error(String msg) {
return error(500, msg);
}
vue element admin
public static HttpResult error(int code, String msg) {
HttpResult r = new HttpResult();
r.setCode(code);
r.setMsg(msg);
return r;
}
public static HttpResult ok(String msg) {
HttpResult r = new HttpResult();
r.setMsg(msg);
return r;
}
public static HttpResult ok(Object data) {
HttpResult r = new HttpResult();
r.setData(data);
return r;
}
public static HttpResult ok() {
return new HttpResult();
}
public int getCode() {
return code;
}
public void setCode(int code) {
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Object getData() {

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。