Эх сурвалжийг харах

😁1、优化数据库备份流程 2、优化仓储基类初始化 3、优化AOP异步处理

zuohuaijun 2 жил өмнө
parent
commit
75d54b4feb

+ 0 - 8
Admin.NET/Admin.NET.Application/Configuration/Database.json

@@ -72,13 +72,5 @@
       //  }
       //}
     ]
-  },
-  // 数据库备份(PostgreSQL)
-  "DbBackup": {
-    "Host": "127.0.0.1",
-    "Port": 5432,
-    "Database": "Admin.NET",
-    "User": "postgres",
-    "Password": "123456"
   }
 }

+ 12 - 2
Admin.NET/Admin.NET.Core/Const/SqlSugarConst.cs

@@ -10,12 +10,12 @@ namespace Admin.NET.Core;
 public class SqlSugarConst
 {
     /// <summary>
-    /// 默认数据库标识(默认租户)
+    /// 默认数据库标识(默认租户)
     /// </summary>
     public const string MainConfigId = "1300000000001";
 
     /// <summary>
-    /// 日志数据库标识
+    /// 默认日志数据库标识
     /// </summary>
     public const string LogConfigId = "1300000000002";
 
@@ -23,4 +23,14 @@ public class SqlSugarConst
     /// 默认表主键
     /// </summary>
     public const string PrimaryKey = "Id";
+
+    /// <summary>
+    /// 仓储对象
+    /// </summary>
+    public static ITenant ITenant { get; set; }
+
+    /// <summary>
+    /// 主库提供器
+    /// </summary>
+    public static SqlSugarScopeProvider MainDb { get; set; }
 }

+ 0 - 36
Admin.NET/Admin.NET.Core/Option/DbBackupOptions.cs

@@ -1,36 +0,0 @@
-// 大名科技(天津)有限公司版权所有  电话:18020030720  QQ:515096995
-//
-// 此源代码遵循位于源代码树根目录中的 LICENSE 文件的许可证
-
-namespace Admin.NET.Core;
-
-/// <summary>
-/// 数据库备份配置选项
-/// </summary>
-public sealed class DbBackupOptions : IConfigurableOptions
-{
-    /// <summary>
-    /// 服务器地址
-    /// </summary>
-    public string Host { get; set; }
-
-    /// <summary>
-    /// 端口
-    /// </summary>
-    public int Port { get; set; }
-
-    /// <summary>
-    /// 数据库名称
-    /// </summary>
-    public string Database { get; set; }
-
-    /// <summary>
-    /// 账号
-    /// </summary>
-    public string User { get; set; }
-
-    /// <summary>
-    /// 密码
-    /// </summary>
-    public string Password { get; set; }
-}

+ 10 - 7
Admin.NET/Admin.NET.Core/Service/DataBase/SysDatabaseService.cs

@@ -4,6 +4,7 @@
 
 using Newtonsoft.Json;
 using Newtonsoft.Json.Converters;
+using Npgsql;
 
 namespace Admin.NET.Core.Service;
 
@@ -444,19 +445,21 @@ public class SysDatabaseService : IDynamicApiController, ITransient
     }
 
     /// <summary>
-    /// 备份数据库(PostgreSQL)
+    /// 备份数据库(PostgreSQL)🔖
     /// </summary>
     /// <returns></returns>
     [HttpPost, NonUnify]
     public async Task<IActionResult> BackupDatabase()
     {
-        var dbBackupOpt = App.GetConfig<DbBackupOptions>("DbBackup", true);
-        if (dbBackupOpt == null || string.IsNullOrWhiteSpace(dbBackupOpt.Host) || string.IsNullOrWhiteSpace(dbBackupOpt.User) || string.IsNullOrWhiteSpace(dbBackupOpt.Password) || string.IsNullOrWhiteSpace(dbBackupOpt.Database))
-            throw Oops.Oh("PostgreSQL数据库配置错误");
+        if (_db.CurrentConnectionConfig.DbType != SqlSugar.DbType.PostgreSQL)
+            throw Oops.Oh("只支持 PostgreSQL 数据库 😁");
 
-        var backupDirectory = Path.Combine(Directory.GetCurrentDirectory(), "backups");
+        var npgsqlConn = new NpgsqlConnectionStringBuilder(_db.CurrentConnectionConfig.ConnectionString);
+        if (npgsqlConn == null || string.IsNullOrWhiteSpace(npgsqlConn.Host) || string.IsNullOrWhiteSpace(npgsqlConn.Username) || string.IsNullOrWhiteSpace(npgsqlConn.Password) || string.IsNullOrWhiteSpace(npgsqlConn.Database))
+            throw Oops.Oh("PostgreSQL 数据库配置错误");
 
         // 确保备份目录存在
+        var backupDirectory = Path.Combine(Directory.GetCurrentDirectory(), "backups");
         Directory.CreateDirectory(backupDirectory);
 
         // 构建备份文件名
@@ -465,7 +468,7 @@ public class SysDatabaseService : IDynamicApiController, ITransient
 
         // 启动pg_dump进程进行备份
         // 设置密码:export PGPASSWORD='xxxxxx'
-        var bash = $"-U {dbBackupOpt.User} -h {dbBackupOpt.Host} -p {dbBackupOpt.Port} -E UTF8 -F c -b -v -f {backupFilePath} {dbBackupOpt.Database}";
+        var bash = $"-U {npgsqlConn.Username} -h {npgsqlConn.Host} -p {npgsqlConn.Port} -E UTF8 -F c -b -v -f {backupFilePath} {npgsqlConn.Database}";
         var startInfo = new ProcessStartInfo
         {
             FileName = "pg_dump",
@@ -476,7 +479,7 @@ public class SysDatabaseService : IDynamicApiController, ITransient
             CreateNoWindow = true,
             EnvironmentVariables =
             {
-                ["PGPASSWORD"] = dbBackupOpt.Password
+                ["PGPASSWORD"] = npgsqlConn.Password
             }
         };
 

+ 8 - 11
Admin.NET/Admin.NET.Core/SqlSugar/SqlSugarRepository.cs

@@ -10,35 +10,32 @@ namespace Admin.NET.Core;
 /// <typeparam name="T"></typeparam>
 public class SqlSugarRepository<T> : SimpleClient<T> where T : class, new()
 {
-    protected static ITenant ITenant { get; set; }
-    protected static SqlSugarScopeProvider MainDb { get; set; }
-
     public SqlSugarRepository()
     {
-        ITenant ??= App.GetRequiredService<ISqlSugarClient>().AsTenant();
-        MainDb ??= ITenant.GetConnectionScope(SqlSugarConst.MainConfigId);
-        base.Context = MainDb;
+        SqlSugarConst.ITenant ??= App.GetRequiredService<ISqlSugarClient>().AsTenant();
+        SqlSugarConst.MainDb ??= SqlSugarConst.ITenant.GetConnectionScope(SqlSugarConst.MainConfigId);
+        base.Context = SqlSugarConst.MainDb;
 
         // 若实体贴有多库特性,则返回指定库连接
         if (typeof(T).IsDefined(typeof(TenantAttribute), false))
         {
-            base.Context = ITenant.GetConnectionScopeWithAttr<T>();
+            base.Context = SqlSugarConst.ITenant.GetConnectionScopeWithAttr<T>();
             return;
         }
 
         // 若实体贴有日志表特性,则返回日志库连接
         if (typeof(T).IsDefined(typeof(LogTableAttribute), false))
         {
-            base.Context = ITenant.IsAnyConnection(SqlSugarConst.LogConfigId)
-                ? ITenant.GetConnectionScope(SqlSugarConst.LogConfigId)
-                : ITenant.GetConnectionScope(SqlSugarConst.MainConfigId);
+            base.Context = SqlSugarConst.ITenant.IsAnyConnection(SqlSugarConst.LogConfigId)
+                ? SqlSugarConst.ITenant.GetConnectionScope(SqlSugarConst.LogConfigId)
+                : SqlSugarConst.ITenant.GetConnectionScope(SqlSugarConst.MainConfigId);
             return;
         }
 
         // 若实体贴有系统表特性,则返回默认库连接
         if (typeof(T).IsDefined(typeof(SysTableAttribute), false))
         {
-            base.Context = ITenant.GetConnectionScope(SqlSugarConst.MainConfigId);
+            base.Context = SqlSugarConst.ITenant.GetConnectionScope(SqlSugarConst.MainConfigId);
             return;
         }
 

+ 3 - 18
Admin.NET/Admin.NET.Core/SqlSugar/SqlSugarSetup.cs

@@ -99,8 +99,6 @@ public static class SqlSugarSetup
     /// <param name="enableConsoleSql"></param>
     public static void SetDbAop(SqlSugarScopeProvider db, bool enableConsoleSql)
     {
-        var config = db.CurrentConnectionConfig;
-
         // 设置超时时间
         db.Ado.CommandTimeOut = 30;
 
@@ -133,7 +131,7 @@ public static class SqlSugarSetup
             };
             db.Aop.OnLogExecuted = (sql, pars) =>
             {
-                // 执行时间超过5秒
+                // 执行时间超过5秒
                 if (db.Ado.SqlExecutionTime.TotalSeconds > 5)
                 {
                     var fileName = db.Ado.SqlStackTrace.FirstFileName; // 文件名
@@ -151,19 +149,6 @@ public static class SqlSugarSetup
         // 数据审计
         db.Aop.DataExecuting = (oldValue, entityInfo) =>
         {
-            //// 演示环境判断
-            //if (entityInfo.EntityColumnInfo.IsPrimarykey)
-            //{
-            //    if (entityInfo.EntityName != nameof(SysJobDetail) && entityInfo.EntityName != nameof(SysJobTrigger) &&
-            //        entityInfo.EntityName != nameof(SysLogOp) && entityInfo.EntityName != nameof(SysLogVis) &&
-            //        entityInfo.EntityName != nameof(SysOnlineUser))
-            //    {
-            //        var isDemoEnv = App.GetService<SysConfigService>().GetConfigValue<bool>(CommonConst.SysDemoEnv).GetAwaiter().GetResult();
-            //        if (isDemoEnv)
-            //            throw Oops.Oh(ErrorCodeEnum.D1200);
-            //    }
-            //}
-
             if (entityInfo.OperationType == DataFilterType.InsertByObject)
             {
                 // 主键(long类型)且没有值的---赋值雪花Id
@@ -264,9 +249,9 @@ public static class SqlSugarSetup
                 Parameters = JSON.Serialize(u.Parameters),
                 Elapsed = u.Time == null ? 0 : (long)u.Time.Value.TotalMilliseconds
             };
-            await db.Insertable(logDiff).ExecuteCommandAsync();
+            await db.CopyNew().Insertable(logDiff).ExecuteCommandAsync();
             Console.ForegroundColor = ConsoleColor.Red;
-            Console.WriteLine(DateTime.Now + $"\r\n*****差异日志开始*****\r\n{Environment.NewLine}{JSON.Serialize(logDiff)}{Environment.NewLine}*****差异日志结束*****\r\n");
+            Console.WriteLine(DateTime.Now + $"\r\n*****开始差异日志*****\r\n{Environment.NewLine}{JSON.Serialize(logDiff)}{Environment.NewLine}*****结束差异日志*****\r\n");
         };
     }
 

+ 0 - 1
Admin.NET/Admin.NET.Web.Core/ProjectOptions.cs

@@ -19,7 +19,6 @@ public static class ProjectOptions
     public static IServiceCollection AddProjectOptions(this IServiceCollection services)
     {
         services.AddConfigurableOptions<DbConnectionOptions>();
-        services.AddConfigurableOptions<DbBackupOptions>();
         services.AddConfigurableOptions<SnowIdOptions>();
         services.AddConfigurableOptions<CacheOptions>();
         services.AddConfigurableOptions<ClusterOptions>();