Преглед на файлове

😒1、仓储基类调整 2、缓存前缀默认值处理 3、其他细节调整

zuohuaijun преди 2 години
родител
ревизия
4d1ad5c8b7

+ 1 - 1
Admin.NET/Admin.NET.Core/Admin.NET.Core.csproj

@@ -36,7 +36,7 @@
     <PackageReference Include="OnceMi.AspNetCore.OSS" Version="1.1.9" />
     <PackageReference Include="SKIT.FlurlHttpClient.Wechat.Api" Version="2.32.0" />
     <PackageReference Include="SKIT.FlurlHttpClient.Wechat.TenpayV3" Version="2.20.0" />
-    <PackageReference Include="SqlSugarCore" Version="5.1.4.107-preview02" />
+    <PackageReference Include="SqlSugarCore" Version="5.1.4.106" />
     <PackageReference Include="System.Linq.Dynamic.Core" Version="1.3.4" />
     <PackageReference Include="UAParser" Version="3.1.47" />
     <PackageReference Include="Yitter.IdGenerator" Version="1.0.14" />

+ 13 - 6
Admin.NET/Admin.NET.Core/EventBus/AppEventSubscriber.cs

@@ -12,13 +12,13 @@ namespace Admin.NET.Core;
 /// <summary>
 /// 事件订阅
 /// </summary>
-public class AppEventSubscriber : IEventSubscriber, ISingleton
+public class AppEventSubscriber : IEventSubscriber, IDisposable
 {
-    private readonly IServiceProvider _serviceProvider;
+    private readonly IServiceScope _serviceScope;
 
-    public AppEventSubscriber(IServiceProvider serviceProvider)
+    public AppEventSubscriber(IServiceScopeFactory scopeFactory)
     {
-        _serviceProvider = serviceProvider;
+        _serviceScope = scopeFactory.CreateScope();
     }
 
     ///// <summary>
@@ -29,11 +29,18 @@ public class AppEventSubscriber : IEventSubscriber, ISingleton
     //[EventSubscribe("Add:ExLog")]
     //public async Task CreateExLog(EventHandlerExecutingContext context)
     //{
-    //    using var scope = _serviceProvider.CreateScope();
-    //    var _rep = scope.ServiceProvider.GetRequiredService<SqlSugarRepository<SysLogEx>>();
+    //    var _rep = _serviceScope.ServiceProvider.GetRequiredService<SqlSugarRepository<SysLogEx>>();
     //    await _rep.InsertAsync((SysLogEx)context.Source.Payload);
 
     //    // 发送邮件
     //    await scope.ServiceProvider.GetRequiredService<SysMessageService>().SendEmail(JSON.Serialize(context.Source.Payload));
     //}
+
+    /// <summary>
+    /// 释放服务作用域
+    /// </summary>
+    public void Dispose()
+    {
+        _serviceScope.Dispose();
+    }
 }

+ 12 - 12
Admin.NET/Admin.NET.Core/Logging/LoggingSetup.cs

@@ -17,6 +17,14 @@ public static class LoggingSetup
     /// <param name="services"></param>
     public static void AddLoggingSetup(this IServiceCollection services)
     {
+        //// 控制台日志格式化
+        //services.AddConsoleFormatter(options =>
+        //{
+        //    options.DateFormat = "yyyy-MM-dd HH:mm:ss(zzz) dddd";
+        //    //options.WithTraceId = true;
+        //    //options.WithStackFrame = true;
+        //});
+
         // 日志监听
         services.AddMonitorLogging(options =>
         {
@@ -24,16 +32,8 @@ public static class LoggingSetup
             options.IgnorePropertyTypes = new[] { typeof(byte[]) };
         });
 
-        // 控制台日志格式化
-        services.AddConsoleFormatter(options =>
-        {
-            options.DateFormat = "yyyy-MM-dd HH:mm:ss(zzz) dddd";
-            options.WithTraceId = true;
-            options.WithStackFrame = true;
-        });
-
         // 日志写入文件
-        if (App.GetConfig<bool>("Logging:File:Enabled")) 
+        if (App.GetConfig<bool>("Logging:File:Enabled"))
         {
             Array.ForEach(new[] { LogLevel.Information, LogLevel.Warning, LogLevel.Error }, logLevel =>
             {
@@ -52,7 +52,7 @@ public static class LoggingSetup
         }
 
         // 日志写入数据库
-        if (App.GetConfig<bool>("Logging:Database:Enabled")) 
+        if (App.GetConfig<bool>("Logging:Database:Enabled"))
         {
             services.AddDatabaseLogging<DatabaseLoggingWriter>(options =>
             {
@@ -67,12 +67,12 @@ public static class LoggingSetup
         }
 
         // 日志写入ElasticSearch
-        if (App.GetConfig<bool>("Logging:ElasticSearch:Enabled")) 
+        if (App.GetConfig<bool>("Logging:ElasticSearch:Enabled"))
         {
             services.AddDatabaseLogging<ElasticSearchLoggingWriter>(options =>
             {
                 options.WithTraceId = true; // 显示线程Id
-                options.WithStackFrame = true; // 显示程序集                
+                options.WithStackFrame = true; // 显示程序集
                 options.IgnoreReferenceLoop = false; // 忽略循环检测
                 options.MessageFormat = LoggerFormatter.Json;
                 options.WriteFilter = (logMsg) =>

+ 6 - 1
Admin.NET/Admin.NET.Core/Option/CacheOptions.cs

@@ -12,7 +12,7 @@ namespace Admin.NET.Core;
 /// <summary>
 /// 缓存配置选项
 /// </summary>
-public sealed class CacheOptions : IConfigurableOptions
+public sealed class CacheOptions : IConfigurableOptions<CacheOptions>
 {
     /// <summary>
     /// 缓存前缀
@@ -28,6 +28,11 @@ public sealed class CacheOptions : IConfigurableOptions
     /// Redis缓存
     /// </summary>
     public RedisOption Redis { get; set; }
+
+    public void PostConfigure(CacheOptions options, IConfiguration configuration)
+    {
+        options.Prefix = string.IsNullOrWhiteSpace(options.Prefix) ? "" : options.Prefix.Trim();
+    }
 }
 
 /// <summary>

+ 2 - 1
Admin.NET/Admin.NET.Core/Service/Cache/SysCacheService.cs

@@ -32,7 +32,8 @@ public class SysCacheService : IDynamicApiController, ISingleton
     public List<string> GetKeyList()
     {
         // 键名去掉全局缓存前缀
-        return _cache.Keys.Where(u => u.StartsWith(_cacheOptions.Prefix)).Select(u => u[_cacheOptions.Prefix.Length..]).OrderBy(u => u).ToList();
+        return _cache.Keys.WhereIF(!string.IsNullOrWhiteSpace(_cacheOptions.Prefix), u => u.StartsWith(_cacheOptions.Prefix))
+            .Select(u => u[_cacheOptions.Prefix.Length..]).OrderBy(u => u).ToList();
     }
 
     /// <summary>

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

@@ -17,9 +17,10 @@ public class SqlSugarRepository<T> : SimpleClient<T> where T : class, new()
 {
     protected ITenant iTenant = null;
 
-    public SqlSugarRepository(ISqlSugarClient context = null) : base(context)
+    public SqlSugarRepository(ISqlSugarClient db)
     {
-        iTenant = App.GetRequiredService<ISqlSugarClient>().AsTenant();
+        iTenant = db.AsTenant();
+        base.Context = iTenant.GetConnectionScope(SqlSugarConst.MainConfigId);
 
         // 若实体贴有多库特性,则返回指定库连接
         if (typeof(T).IsDefined(typeof(TenantAttribute), false))
@@ -45,15 +46,15 @@ public class SqlSugarRepository<T> : SimpleClient<T> where T : class, new()
         }
 
         // 若未贴任何表特性或当前未登录或是默认租户Id,则返回默认库连接
-        var tenantId = App.GetRequiredService<UserManager>().TenantId;
-        if (tenantId < 1 || tenantId.ToString() == SqlSugarConst.MainConfigId) return;
+        var tenantId = App.User?.FindFirst(ClaimConst.TenantId)?.Value;
+        if (string.IsNullOrWhiteSpace(tenantId) || tenantId == SqlSugarConst.MainConfigId) return;
 
         // 若租户为空或租户以Id隔离模式时,则返回默认库连接
-        var tenant = App.GetRequiredService<SysCacheService>().Get<List<SysTenant>>(CacheConst.KeyTenant).FirstOrDefault(u => u.Id == tenantId);
+        var tenant = App.GetRequiredService<SysCacheService>().Get<List<SysTenant>>(CacheConst.KeyTenant).FirstOrDefault(u => u.Id == long.Parse(tenantId));
         if (tenant is null || tenant is { TenantType: TenantTypeEnum.Id }) return;
 
         // 若租户以库隔离模式时,根据租户Id切换库连接
-        if (!iTenant.IsAnyConnection(tenantId.ToString()))
+        if (!iTenant.IsAnyConnection(tenantId))
         {
             // 获取默认库连接配置
             var dbOptions = App.GetOptions<DbConnectionOptions>();
@@ -73,8 +74,8 @@ public class SqlSugarRepository<T> : SimpleClient<T> where T : class, new()
             };
             iTenant.AddConnection(tenantConnConfig);
             SqlSugarSetup.SetDbConfig(tenantConnConfig);
-            SqlSugarSetup.SetDbAop(iTenant.GetConnectionScope(tenantId.ToString()), dbOptions.EnableConsoleSql);
+            SqlSugarSetup.SetDbAop(iTenant.GetConnectionScope(tenantId), dbOptions.EnableConsoleSql);
         }
-        base.Context = iTenant.GetConnectionScope(tenantId.ToString());
+        base.Context = iTenant.GetConnectionScope(tenantId);
     }
 }

+ 12 - 12
Admin.NET/Admin.NET.Core/SqlSugar/SqlSugarSetup.cs

@@ -154,18 +154,18 @@ 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.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)
             {