Przeglądaj źródła

🤓定时任务优化相关优化

zuohuaijun 2 lat temu
rodzic
commit
cc36740707

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

@@ -1,8 +0,0 @@
-{
-    "$schema": "https://gitee.com/dotnetchina/Furion/raw/v4/schemas/v4/furion-schema.json",
-
-  "SignalRRedisDock": {
-    "Enabled": false,
-    "RedisConnectionString": "127.0.0.1:6379,connectRetry=3,syncTimeout=1000,connectTimeout=1000,defaultDatabase=2,ssl=false,writeBuffer=10240,abortConnect=False" // Redis连接字符串
-  }
-}

+ 0 - 2
Admin.NET/Admin.NET.Core/Admin.NET.Core.csproj

@@ -15,8 +15,6 @@
   </ItemGroup>
 
   <ItemGroup>
-    <PackageReference Include="Microsoft.AspNetCore.SignalR.Protocols.MessagePack" Version="7.0.5" />
-	<PackageReference Include="Microsoft.AspNetCore.SignalR.StackExchangeRedis" Version="6.0.16" />
     <PackageReference Include="AngleSharp" Version="1.0.1" />
     <PackageReference Include="AspectCore.Extensions.Reflection" Version="2.3.0" />
     <PackageReference Include="AspNetCoreRateLimit" Version="5.0.0" />

+ 0 - 67
Admin.NET/Admin.NET.Core/Hub/SignalRDockExtensions.cs

@@ -1,67 +0,0 @@
-using StackExchange.Redis;
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using System.Threading.Tasks;
-
-namespace Admin.NET.Core;
-public static class SignalRDockExtensions
-{
-    /// <summary>
-    /// 注入redis底板
-    /// </summary>
-    /// <param name="services"></param>
-    /// <param name="delegateRedisConnectionString"></param>
-    /// <exception cref="ArgumentNullException"></exception>
-    public static void AddSignalR_RedisDock(this IServiceCollection services, Func<string> delegateRedisConnectionString)
-    {
-        var RedisConnectionString = delegateRedisConnectionString();
-        if (string.IsNullOrEmpty(RedisConnectionString))
-        {
-            throw new ArgumentNullException(nameof(RedisConnectionString));
-        }
-        services.AddSignalR(hubOptions =>
-        {
-            //SignalR 自己的 pinger ,客户端在定义的时间跨度内没有响应,它将触发OnDisconnectedAsync
-            hubOptions.KeepAliveInterval = TimeSpan.FromSeconds(5);
-        }).AddJsonProtocol()
-            .AddMessagePackProtocol()
-            // 支持MessagePack
-            .AddStackExchangeRedis(options =>
-            {
-                options.ConnectionFactory = async writer =>
-                {
-
-                    var config = new ConfigurationOptions
-                    {
-                        AbortOnConnectFail = false,
-                        // Password = "changeme",
-                        ChannelPrefix = "__signalr_",
-                    };
-                    //config.EndPoints.Add(IPAddress.Loopback, 0);
-                    //config.SetDefaultPorts();
-                    config.DefaultDatabase = 1;
-                    var connection = await ConnectionMultiplexer.ConnectAsync(RedisConnectionString, writer);
-                    connection.ConnectionFailed += (_, e) =>
-                    {
-                        ConsoleDebug.WriteLine("Connection to Redis failed.");
-                    };
-
-                    if (connection.IsConnected)
-                    {
-                        ConsoleDebug.WriteLine("connected to Redis.");
-                    }
-                    else
-                    {
-                        ConsoleDebug.WriteLine("Did not connect to Redis");
-                    }
-
-                    return connection;
-                };
-            });
-    }
-}
-
-
-//redis查看订阅列表 PUBSUB CHANNELS

+ 0 - 2
Admin.NET/Admin.NET.Core/Job/DynamicJobCompiler.cs

@@ -13,9 +13,7 @@ public class DynamicJobCompiler : ISingleton
     public Type BuildJob(string script)
     {
         var jobAssembly = Schedular.CompileCSharpClassCode(script);
-
         var jobType = jobAssembly.GetTypes().FirstOrDefault(u => typeof(IJob).IsAssignableFrom(u));
-
         return jobType;
     }
 }

+ 2 - 1
Admin.NET/Admin.NET.Core/Service/Config/SysConfigService.cs

@@ -28,7 +28,8 @@ public class SysConfigService : IDynamicApiController, ITransient
             .WhereIF(!string.IsNullOrWhiteSpace(input.Name?.Trim()), u => u.Name.Contains(input.Name))
             .WhereIF(!string.IsNullOrWhiteSpace(input.Code?.Trim()), u => u.Code.Contains(input.Code))
             .WhereIF(!string.IsNullOrWhiteSpace(input.GroupCode?.Trim()), u => u.GroupCode.Equals(input.GroupCode))
-            .OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
+            .OrderBuilder(input)
+            .ToPagedListAsync(input.Page, input.PageSize);
     }
 
     /// <summary>

+ 1 - 3
Admin.NET/Admin.NET.Core/Service/File/SysFileService.cs

@@ -179,11 +179,9 @@ public class SysFileService : IDynamicApiController, ITransient
         {
             var contentTypeProvider = FS.GetFileExtensionContentTypeProvider();
             suffix = contentTypeProvider.Mappings.FirstOrDefault(u => u.Value == file.ContentType).Key;
-            // image/jpeg 返回的后缀是.jpe ,导致vant上传回显图片失败
+            // 修改 image/jpeg 类型返回的 .jpe 后缀
             if (suffix == ".jpe")
-            {
                 suffix = ".jpg";
-            }
         }
         if (string.IsNullOrWhiteSpace(suffix))
             throw Oops.Oh(ErrorCodeEnum.D8003);

+ 1 - 1
Admin.NET/Admin.NET.Core/Service/Job/DbJobPersistence.cs

@@ -85,7 +85,7 @@ public class DbJobPersistence : IJobPersistence
                     throw new NotSupportedException();
             }
 
-            //动态构建的 jobType 的程序集名称为随机名称,需重新设置
+            // 动态构建的 jobType 的程序集名称为随机名称,需重新设置
             dbDetail.AssemblyName = jobType.Assembly.FullName!.Split(',')[0];
             var jobBuilder = JobBuilder.Create(jobType).LoadFrom(dbDetail);
 

+ 9 - 30
Admin.NET/Admin.NET.Core/Service/Job/JobClusterServer.cs

@@ -1,6 +1,3 @@
-//using Nest;
-using Furion.Schedule;
-
 namespace Admin.NET.Core.Service;
 
 /// <summary>
@@ -8,18 +5,11 @@ namespace Admin.NET.Core.Service;
 /// </summary>
 public class JobClusterServer : IJobClusterServer
 {
-    private readonly Random ro=new Random(DateTime.Now.Millisecond);
+    private readonly Random rd = new(DateTime.Now.Millisecond);
 
     public JobClusterServer()
     {
     }
-    //public JobClusterServer(SqlSugarRepository<SysJobCluster> sysJobClusterRep)
-    //{
-    //    _sysJobClusterRep = sysJobClusterRep;
-
-
-    //}
-
 
     /// <summary>
     /// 当前作业调度器启动通知
@@ -27,26 +17,16 @@ public class JobClusterServer : IJobClusterServer
     /// <param name="context">作业集群服务上下文</param>
     public async void Start(JobClusterContext context)
     {
-        var _sysJobClusterRep = App.GetService<SqlSugarRepository<SysJobCluster>>(); 
+        var _sysJobClusterRep = App.GetService<SqlSugarRepository<SysJobCluster>>();
         // 在作业集群表中,如果 clusterId 不存在,则新增一条(否则更新一条),并设置 status 为 ClusterStatus.Waiting
-        var clusters = await _sysJobClusterRep.AsQueryable().Where(u => u.ClusterId == context.ClusterId).ToListAsync();
-        if (clusters.Any())
+        if (await _sysJobClusterRep.IsAnyAsync(u => u.ClusterId == context.ClusterId))
         {
-            await _sysJobClusterRep.AsUpdateable().SetColumns(u => u.Status ==  ClusterStatus.Waiting).Where(u => u.ClusterId == context.ClusterId).ExecuteCommandAsync();
+            await _sysJobClusterRep.AsUpdateable().SetColumns(u => u.Status == ClusterStatus.Waiting).Where(u => u.ClusterId == context.ClusterId).ExecuteCommandAsync();
         }
         else
         {
-
             await _sysJobClusterRep.AsInsertable(new SysJobCluster { ClusterId = context.ClusterId, Status = ClusterStatus.Waiting }).ExecuteCommandAsync();
         }
-        //if (await _sysJobClusterRep.IsAnyAsync(u => u.ClusterId == context.ClusterId))
-        //{
-        //    await _sysJobClusterRep.UpdateSetColumnsTrueAsync(u => new SysJobCluster { Status = ClusterStatus.Waiting }, u => u.ClusterId == context.ClusterId);
-        //}
-        //else
-        //{
-        //    await _sysJobClusterRep.InsertAsync(new SysJobCluster { ClusterId = context.ClusterId, Status = ClusterStatus.Waiting });
-        //}
     }
 
     /// <summary>
@@ -60,15 +40,15 @@ public class JobClusterServer : IJobClusterServer
 
         while (true)
         {
-             // 控制集群心跳频率 放在头部为了防止 IsAnyAsync continue 没sleep占用大量IO和CPU
-            await Task.Delay(3000 + ro.Next(500, 1000));//错开集群同时启动
+            // 控制集群心跳频率(放在头部为了防止 IsAnyAsync continue 没sleep占用大量IO和CPU)
+            await Task.Delay(3000 + rd.Next(500, 1000)); // 错开集群同时启动
+
             try
             {
                 ICache _cache = App.GetService<ICache>();
                 //使用分布式锁
                 using (_cache.AcquireLock("lock:JobClusterServer:WaitingForAsync", 1000))
                 {
-                     
                     var _sysJobClusterRep = App.GetService<SqlSugarRepository<SysJobCluster>>();
                     // 在这里查询数据库,根据以下两种情况处理
                     // 1) 如果作业集群表已有 status 为 ClusterStatus.Working 则继续循环
@@ -77,10 +57,9 @@ public class JobClusterServer : IJobClusterServer
                     if (await _sysJobClusterRep.IsAnyAsync(u => u.Status == ClusterStatus.Working))
                         continue;
 
-                    WorkNowAsync(clusterId);
+                    await WorkNowAsync(clusterId);
                     return;
                 }
-                 
             }
             catch { }
         }
@@ -113,7 +92,7 @@ public class JobClusterServer : IJobClusterServer
     /// </summary>
     /// <param name="clusterId">集群 Id</param>
     /// <returns></returns>
-    private async void WorkNowAsync(string clusterId)
+    private async Task WorkNowAsync(string clusterId)
     {
         var _sysJobClusterRep = App.GetService<SqlSugarRepository<SysJobCluster>>();
         // 在作业集群表中,更新 clusterId 的 status 为 ClusterStatus.Working

+ 33 - 34
Admin.NET/Admin.NET.Web.Core/Startup.cs

@@ -34,11 +34,6 @@ public class Startup : AppStartup
         services.AddSqlSugar();
         // JWT
         services.AddJwt<JwtHandler>(enableGlobalAuthorize: true);
-        if (App.GetConfig<bool>("SignalRRedisDock:Enabled"))
-        {
-            //redis底板 AddSignalR_RedisDock 需要在Addjwt后。在之前会导致JwtHandler失效
-            services.AddSignalR_RedisDock(() => App.GetConfig<string>("SignalRRedisDock:RedisConnectionString"));
-        }
         // 允许跨域
         services.AddCorsAccessor();
         // 远程请求
@@ -65,31 +60,31 @@ public class Startup : AppStartup
         });
 
         services.AddControllersWithViews()
-                .AddAppLocalization()
-                .AddNewtonsoftJson(options =>
-                {
-                    options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local;
-                    options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); // 首字母小写(驼峰样式)
-                    options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss"; // 时间格式化
-                    // options.SerializerSettings.MetadataPropertyHandling = MetadataPropertyHandling.Ignore;
-                    // options.SerializerSettings.DateParseHandling = DateParseHandling.None;
-                    // options.SerializerSettings.Converters.Add(new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal });
-                    options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; // 忽略循环引用
-                    // options.SerializerSettings.Converters.AddLongTypeConverters(); // long转string(防止js精度溢出) 超过16位开启
-                    // options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore; // 忽略空值
-                })
-                //.AddXmlSerializerFormatters()
-                //.AddXmlDataContractSerializerFormatters()
-                .AddInjectWithUnifyResult<AdminResultProvider>();
+            .AddAppLocalization()
+            .AddNewtonsoftJson(options =>
+            {
+                options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local;
+                options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); // 首字母小写(驼峰样式)
+                options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss"; // 时间格式化
+                // options.SerializerSettings.MetadataPropertyHandling = MetadataPropertyHandling.Ignore;
+                // options.SerializerSettings.DateParseHandling = DateParseHandling.None;
+                // options.SerializerSettings.Converters.Add(new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal });
+                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; // 忽略循环引用
+                // options.SerializerSettings.Converters.AddLongTypeConverters(); // long转string(防止js精度溢出) 超过16位开启
+                // options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore; // 忽略空值
+            })
+            //.AddXmlSerializerFormatters()
+            //.AddXmlDataContractSerializerFormatters()
+            .AddInjectWithUnifyResult<AdminResultProvider>();
 
         //// 第三方授权登录
         //services.AddAuthentication()
-        //        .AddWeixin(options =>
-        //        {
-        //            var opt = App.GetOptions<OAuthOptions>();
-        //            options.ClientId = opt.Weixin.ClientId;
-        //            options.ClientSecret = opt.Weixin.ClientSecret;
-        //        });
+        //    .AddWeixin(options =>
+        //    {
+        //        var opt = App.GetOptions<OAuthOptions>();
+        //        options.ClientId = opt.Weixin.ClientId;
+        //        options.ClientSecret = opt.Weixin.ClientSecret;
+        //    });
 
         // ElasticSearch
         services.AddElasticSearch();
@@ -140,18 +135,22 @@ public class Startup : AppStartup
         // 电子邮件
         var emailOpt = App.GetOptions<EmailOptions>();
         services.AddFluentEmail(emailOpt.DefaultFromEmail, emailOpt.DefaultFromName)
-                .AddSmtpSender(new SmtpClient(emailOpt.Host, emailOpt.Port)
-                {
-                    EnableSsl = emailOpt.EnableSsl,
-                    UseDefaultCredentials = emailOpt.UseDefaultCredentials,
-                    Credentials = new NetworkCredential(emailOpt.UserName, emailOpt.Password)
-                });
+            .AddSmtpSender(new SmtpClient(emailOpt.Host, emailOpt.Port)
+            {
+                EnableSsl = emailOpt.EnableSsl,
+                UseDefaultCredentials = emailOpt.UseDefaultCredentials,
+                Credentials = new NetworkCredential(emailOpt.UserName, emailOpt.Password)
+            });
 
         // 模板引擎
         services.AddViewEngine();
 
         // 即时通讯
-        services.AddSignalR();
+        services.AddSignalR(options =>
+            {
+                options.KeepAliveInterval = TimeSpan.FromSeconds(5);
+            })
+            .AddJsonProtocol();
 
         // logo显示
         services.AddLogoDisplay();