feat: 新增数据库定时备份功能

This commit is contained in:
陈淳
2023-12-22 18:57:04 +08:00
parent 8139a9585d
commit 61beac9ef2
9 changed files with 95 additions and 18 deletions

View File

@@ -12,5 +12,10 @@ namespace Yi.Framework.SqlSugarCore.Abstractions
{
// IAbpLazyServiceProvider LazyServiceProvider { get; set; }
ISqlSugarClient SqlSugarClient { get; }
/// <summary>
/// 数据库备份
/// </summary>
void BackupDataBase();
}
}

View File

@@ -43,5 +43,7 @@ namespace Yi.Framework.SqlSugarCore
/// 读写分离
/// </summary>
public List<string>? ReadUrl { get; set; }
}
}

View File

@@ -218,13 +218,13 @@ namespace Yi.Framework.SqlSugarCore
/// </summary>
/// <param name="sql"></param>
/// <param name="pars"></param>
protected virtual void OnLogExecuting(string sql , SugarParameter[] pars)
protected virtual void OnLogExecuting(string sql, SugarParameter[] pars)
{
if (Options.EnabledSqlLog)
{
Logger.CreateLogger<SqlSugarDbContext>().LogDebug("Yi-SQL执行:"+UtilMethods.GetSqlString(DbType.SqlServer, sql, pars));
Logger.CreateLogger<SqlSugarDbContext>().LogDebug("Yi-SQL执行:" + UtilMethods.GetSqlString(DbType.SqlServer, sql, pars));
}
}
/// <summary>
@@ -234,6 +234,45 @@ namespace Yi.Framework.SqlSugarCore
/// <param name="pars"></param>
protected virtual void OnLogExecuted(string sql, SugarParameter[] pars)
{
}
public void BackupDataBase()
{
string directoryName = "database_backup";
string fileName = DateTime.Now.ToString($"yyyyMMdd_HHmmss")+ $"_{SqlSugarClient.Ado.Connection.Database}";
if (!Directory.Exists(directoryName))
{
Directory.CreateDirectory(directoryName);
}
switch (Options.DbType)
{
case DbType.MySql:
//MySql
SqlSugarClient.DbMaintenance.BackupDataBase(SqlSugarClient.Ado.Connection.Database, $"{Path.Combine(directoryName, fileName) }.sql");//mysql 只支持.net core
break;
case DbType.Sqlite:
//Sqlite
SqlSugarClient.DbMaintenance.BackupDataBase(null, $"{fileName}.db"); //sqlite 只支持.net core
break;
case DbType.SqlServer:
//SqlServer
SqlSugarClient.DbMaintenance.BackupDataBase(SqlSugarClient.Ado.Connection.Database, $"{Path.Combine(directoryName, fileName)}.bak"/*服务器路径*/);//第一个参数库名
break;
default:
throw new NotImplementedException("其他数据库备份未实现");
}
}
}
}

View File

@@ -3,6 +3,7 @@
<ItemGroup>
<PackageReference Include="MySqlBackup.NET.MySqlConnector" Version="2.3.8" />
<PackageReference Include="SqlSugarCore" Version="5.1.4.124" />
</ItemGroup>

View File

@@ -3,21 +3,42 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Quartz;
using Quartz.Logging;
using Volo.Abp.BackgroundWorkers.Quartz;
using Volo.Abp.Domain.Repositories;
using Yi.Framework.Rbac.Domain.Shared.Options;
using Yi.Framework.SqlSugarCore.Abstractions;
namespace Yi.Framework.Rbac.Application.Jobs
{
//public class BackupDataBaseJob : QuartzBackgroundWorkerBase
//{
// public TestJob()
// {
// JobDetail = JobBuilder.Create<TestJob>().WithIdentity(nameof(TestJob)).Build();
// Trigger = TriggerBuilder.Create().WithIdentity(nameof(TestJob)).WithCronSchedule("* * * * * ? *").Build();
// }
// public override Task Execute(IJobExecutionContext context)
// {
// Console.WriteLine("你好,世界");
// return Task.CompletedTask;
// }
//}
public class BackupDataBaseJob : QuartzBackgroundWorkerBase
{
private ISqlSugarDbContext _dbContext;
public BackupDataBaseJob(ISqlSugarDbContext dbContext)
{
_dbContext = dbContext;
JobDetail = JobBuilder.Create<BackupDataBaseJob>().WithIdentity(nameof(BackupDataBaseJob)).Build();
//每天00点与24点进行备份
Trigger = TriggerBuilder.Create().WithIdentity(nameof(BackupDataBaseJob)).WithCronSchedule("0 0 0,12 * * ? ").Build();
//Trigger = TriggerBuilder.Create().WithIdentity(nameof(BackupDataBaseJob)).WithSimpleSchedule(x=>x.WithIntervalInSeconds(10)).Build();
}
public override Task Execute(IJobExecutionContext context)
{
var options = LazyServiceProvider.GetRequiredService<IOptions<RbacOptions>>();
if (options.Value.EnableDataBaseBackup)
{
var logger = LoggerFactory.CreateLogger<BackupDataBaseJob>();
logger.LogWarning("正在进行数据库备份");
_dbContext.BackupDataBase();
logger.LogWarning("数据库备份已完成");
}
return Task.CompletedTask;
}
}
}

View File

@@ -22,5 +22,10 @@ namespace Yi.Framework.Rbac.Domain.Shared.Options
/// 是否开启用户注册功能
/// </summary>
public bool EnableRegister { get; set; } = false;
/// <summary>
/// 是否开启数据库备份
/// </summary>
public bool EnableDataBaseBackup { get; set; } = false;
}
}

View File

@@ -9,7 +9,7 @@ Log.Logger = new LoggerConfiguration()
.MinimumLevel.Override("Microsoft.AspNetCore.Hosting.Diagnostics",LogEventLevel.Error)
.MinimumLevel.Override("Quartz", LogEventLevel.Warning)
.Enrich.FromLogContext()
.WriteTo.Async(c => c.File("Logs/log-.txt", rollingInterval: RollingInterval.Day))
.WriteTo.Async(c => c.File("logs/log-.txt", rollingInterval: RollingInterval.Day))
.WriteTo.Async(c => c.Console())
.CreateLogger();

View File

@@ -36,6 +36,7 @@
</ItemGroup>
<ItemGroup>
<Folder Include="logs\" />
<Folder Include="wwwroot\" />
</ItemGroup>

View File

@@ -47,6 +47,9 @@
"EnableCaptcha": true,
//是否开启注册功能
"EnableRegister": false
"EnableRegister": false,
//开启定时数据库备份
"EnableDataBaseBackup": false
}
}