NewLife/Stardust

简化StarServerSetting的引用
智能大石头 authored at 2025-08-26 16:57:53
bbb1b93
Tree
1 Parent(s) 4c273d4
Summary: 7 changed files with 34 additions and 78 deletions.
Modified +5 -5
Modified +2 -6
Modified +1 -3
Modified +1 -3
Modified +15 -28
Modified +6 -15
Modified +4 -18
Modified +5 -5
diff --git a/Stardust.Server/Controllers/CubeController.cs b/Stardust.Server/Controllers/CubeController.cs
index eb20f6d..3ed62a5 100644
--- a/Stardust.Server/Controllers/CubeController.cs
+++ b/Stardust.Server/Controllers/CubeController.cs
@@ -11,7 +11,7 @@ namespace Stardust.Server.Controllers;
 [DisplayName("数据接口")]
 [ApiController]
 [Route("{controller}/{action}")]
-public class CubeController : ControllerBase
+public class CubeController(StarServerSetting setting) : ControllerBase
 {
     #region 附件
     private async Task<(Attachment att, String filePath)> GetFile(String id)
@@ -25,19 +25,19 @@ public class CubeController : ControllerBase
         var att = Attachment.FindById(id.ToLong());
         if (att == null) throw new ApiException(ApiCode.NotFound, "找不到附件信息");
 
-        var set = StarServerSetting.Current;
+        //var set = StarServerSetting.Current;
 
         // 如果附件不存在,则抓取
-        var filePath = att.GetFilePath(set.UploadPath);
+        var filePath = att.GetFilePath(setting.UploadPath);
         if (filePath.IsNullOrEmpty() || !System.IO.File.Exists(filePath))
         {
             var url = att.Source;
             if (url.IsNullOrEmpty()) throw new ApiException(ApiCode.NotFound, "找不到附件文件");
 
-            var rs = await att.Fetch(url, set.UploadPath);
+            var rs = await att.Fetch(url, setting.UploadPath);
             if (!rs) throw new ApiException(ApiCode.NotFound, "附件远程抓取失败");
 
-            filePath = att.GetFilePath(set.UploadPath);
+            filePath = att.GetFilePath(setting.UploadPath);
         }
         if (filePath.IsNullOrEmpty() || !System.IO.File.Exists(filePath)) throw new ApiException(ApiCode.NotFound, "附件文件不存在");
 
Modified +2 -6
diff --git a/Stardust.Server/Controllers/LogController.cs b/Stardust.Server/Controllers/LogController.cs
index fd484e6..a170e31 100644
--- a/Stardust.Server/Controllers/LogController.cs
+++ b/Stardust.Server/Controllers/LogController.cs
@@ -8,12 +8,8 @@ namespace Stardust.Server.Controllers;
 
 [ApiController]
 [Route("[controller]")]
-public class LogController : ControllerBase
+public class LogController(StarServerSetting setting) : ControllerBase
 {
-    private readonly StarServerSetting _setting;
-
-    public LogController(StarServerSetting setting) => _setting = setting;
-
     [HttpGet]
     public Object Get() => "LogController";
 
@@ -35,7 +31,7 @@ public class LogController : ControllerBase
                 app = new App
                 {
                     Name = appId,
-                    Enable = _setting.AppAutoRegister,
+                    Enable = setting.AppAutoRegister,
                 };
                 app.Insert();
             }
Modified +1 -3
diff --git a/Stardust.Server/Controllers/OAuthController.cs b/Stardust.Server/Controllers/OAuthController.cs
index 9fa393d..da0a918 100644
--- a/Stardust.Server/Controllers/OAuthController.cs
+++ b/Stardust.Server/Controllers/OAuthController.cs
@@ -17,8 +17,6 @@ public class OAuthController(ITokenService tokenService, AppTokenService appToke
     [ApiFilter]
     public TokenModel Token([FromBody] TokenInModel model)
     {
-        var set = setting;
-
         if (model.grant_type.IsNullOrEmpty()) model.grant_type = "password";
 
         var ip = HttpContext.GetUserHost();
@@ -29,7 +27,7 @@ public class OAuthController(ITokenService tokenService, AppTokenService appToke
             // 密码模式
             if (model.grant_type == "password")
             {
-                var app = appTokenService.Authorize(model.UserName, model.Password, set.AppAutoRegister, ip);
+                var app = appTokenService.Authorize(model.UserName, model.Password, setting.AppAutoRegister, ip);
 
                 // 更新应用信息
                 app.LastLogin = DateTime.Now;
Modified +1 -3
diff --git a/Stardust.Server/Controllers/TraceController.cs b/Stardust.Server/Controllers/TraceController.cs
index cafb4c9..1d3de0d 100644
--- a/Stardust.Server/Controllers/TraceController.cs
+++ b/Stardust.Server/Controllers/TraceController.cs
@@ -92,8 +92,6 @@ public class TraceController(ITraceStatService stat, IAppDayStatService appStat,
 
     private (AppTracer, AppOnline) Valid(String appId, TraceModel model, String clientId, String ip, String token)
     {
-        var set = setting;
-
         // 新版验证方式,访问令牌
         App ap = null;
         if (!token.IsNullOrEmpty() && token.Split(".").Length == 3)
@@ -137,7 +135,7 @@ public class TraceController(ITraceStatService stat, IAppDayStatService appStat,
                     }
                     else
                     {
-                        app.Enable = set.AppAutoRegister;
+                        app.Enable = setting.AppAutoRegister;
                     }
 
                     app.Insert();
Modified +15 -28
diff --git a/Stardust.Server/Services/AlarmService.cs b/Stardust.Server/Services/AlarmService.cs
index 30cdcb5..b88c111 100644
--- a/Stardust.Server/Services/AlarmService.cs
+++ b/Stardust.Server/Services/AlarmService.cs
@@ -10,26 +10,13 @@ using Stardust.Data.Nodes;
 
 namespace Stardust.Server.Services;
 
-public class AlarmService : IHostedService
+public class AlarmService(StarServerSetting setting, IServiceProvider serviceProvider, ITracer tracer) : IHostedService
 {
     /// <summary>计算周期。默认30秒</summary>
-    public Int32 Period { get; set; } = 30;
+    public Int32 Period { get; set; } = setting.AlarmPeriod;
 
     private TimerX _timer;
     private ICache _cache;
-    private readonly StarServerSetting _setting;
-    private readonly IServiceProvider _serviceProvider;
-    private readonly ITracer _tracer;
-
-    public AlarmService(StarServerSetting setting, IServiceProvider serviceProvider, ITracer tracer)
-    {
-        _setting = setting;
-        _serviceProvider = serviceProvider;
-        //_cache = cacheProvider.Cache;
-        _tracer = tracer;
-
-        Period = setting.AlarmPeriod;
-    }
 
     public Task StartAsync(CancellationToken cancellationToken)
     {
@@ -48,7 +35,7 @@ public class AlarmService : IHostedService
 
     private void DoAlarm(Object state)
     {
-        _cache ??= _serviceProvider.GetService<ICacheProvider>()?.Cache;
+        _cache ??= serviceProvider.GetService<ICacheProvider>()?.Cache;
 
         // 应用告警
         var list = AppTracer.FindAllWithCache();
@@ -87,7 +74,7 @@ public class AlarmService : IHostedService
         var webhook = RobotHelper.GetAlarm(app.Project, app.Category, app.AlarmRobot);
         if (webhook.IsNullOrEmpty()) return;
 
-        using var span = _tracer?.NewSpan($"alarm:{nameof(AppTracer)}");
+        using var span = tracer?.NewSpan($"alarm:{nameof(AppTracer)}");
 
         // 最近一段时间的5分钟级数据
         var time = DateTime.Now;
@@ -124,7 +111,7 @@ public class AlarmService : IHostedService
         sb.AppendLine($">**总数:**<font color=\"red\">{st.Errors}</font>");
         sb.AppendLine($">**错误率:**<font color=\"red\">{st.ErrorRate:p2}</font>");
 
-        var url = _setting.WebUrl;
+        var url = setting.WebUrl;
         var appUrl = "";
         var traceUrl = "";
         if (!url.IsNullOrEmpty())
@@ -209,7 +196,7 @@ public class AlarmService : IHostedService
             var time = DateTime.Now;
             var minute = time.Date.AddHours(time.Hour).AddMinutes(time.Minute / 5 * 5);
 
-            using var span = _tracer?.NewSpan($"alarm:{nameof(TraceItem)}", new { appId = app.ID, time, minute });
+            using var span = tracer?.NewSpan($"alarm:{nameof(TraceItem)}", new { appId = app.ID, time, minute });
 
             var list = TraceMinuteStat.Search(app.ID, minute, tis.Select(e => e.Id).ToArray());
             foreach (var st in list)
@@ -261,7 +248,7 @@ public class AlarmService : IHostedService
         sb.AppendLine($">**总数:**<font color=\"red\">{st.Errors}</font>");
         sb.AppendLine($">**错误率:**<font color=\"red\">{st.ErrorRate:p2}</font>");
 
-        var url = _setting.WebUrl;
+        var url = setting.WebUrl;
         var traceUrl = "";
         if (!url.IsNullOrEmpty())
         {
@@ -332,7 +319,7 @@ public class AlarmService : IHostedService
         var hour = time.Date.AddHours(time.Hour);
         if (time.Minute < 5) return;
 
-        using var span = _tracer?.NewSpan($"alarm:RingRate", new { app.ID, app.Name, app.DisplayName, time, hour });
+        using var span = tracer?.NewSpan($"alarm:RingRate", new { app.ID, app.Name, app.DisplayName, time, hour });
 
         var list = TraceHourStat.Search(app.ID, -1, null, hour, hour.AddHours(1), null, null);
         foreach (var st in list)
@@ -391,7 +378,7 @@ public class AlarmService : IHostedService
         sb.AppendLine($">**环比:**<font color=\"red\">{st.RingRate:p2}</font>");
         sb.AppendLine($">**折算环比:**<font color=\"red\">{rate:p2}</font>");
 
-        var url = _setting.WebUrl;
+        var url = setting.WebUrl;
         var traceUrl = "";
         if (!url.IsNullOrEmpty())
         {
@@ -421,7 +408,7 @@ public class AlarmService : IHostedService
 
         if (node.AlarmCpuRate <= 0 && node.AlarmMemoryRate <= 0 && node.AlarmDiskRate <= 0 && node.AlarmProcesses.IsNullOrEmpty()) return;
 
-        using var span = _tracer?.NewSpan($"alarm:{nameof(Node)}");
+        using var span = tracer?.NewSpan($"alarm:{nameof(Node)}");
 
         // 最新数据
         var data = NodeData.FindLast(node.ID);
@@ -573,7 +560,7 @@ public class AlarmService : IHostedService
         if (str.Length > 2000) str = str[..2000];
 
         // 构造网址
-        var url = _setting.WebUrl;
+        var url = setting.WebUrl;
         if (!url.IsNullOrEmpty())
         {
             url = url.EnsureEnd("/") + "Nodes/NodeData?nodeId=" + node.ID;
@@ -605,7 +592,7 @@ public class AlarmService : IHostedService
         var data = RedisData.FindLast(node.Id);
         if (data == null) return;
 
-        using var span = _tracer?.NewSpan($"alarm:{nameof(RedisNode)}");
+        using var span = tracer?.NewSpan($"alarm:{nameof(RedisNode)}");
 
         var actions = new List<Action<StringBuilder>>();
 
@@ -717,7 +704,7 @@ public class AlarmService : IHostedService
         if (str.Length > 2000) str = str[..2000];
 
         // 构造网址
-        var url = _setting.WebUrl;
+        var url = setting.WebUrl;
         if (!url.IsNullOrEmpty())
         {
             url = url.EnsureEnd("/") + "Nodes/RedisNode?id=" + node.Id;
@@ -731,7 +718,7 @@ public class AlarmService : IHostedService
     #region Redis队列告警
     private void ProcessRedisQueue(RedisNode node)
     {
-        using var span = _tracer?.NewSpan($"alarm:{nameof(RedisMessageQueue)}");
+        using var span = tracer?.NewSpan($"alarm:{nameof(RedisMessageQueue)}");
 
         // 所有队列
         var list = RedisMessageQueue.FindAllByRedisId(node.Id);
@@ -774,7 +761,7 @@ public class AlarmService : IHostedService
         if (str.Length > 2000) str = str[..2000];
 
         // 构造网址
-        var url = _setting.WebUrl;
+        var url = setting.WebUrl;
         if (!url.IsNullOrEmpty())
         {
             url = url.EnsureEnd("/") + "Nodes/RedisMessageQueue?redisId=" + queue.RedisId + "&q=" + queue.Name;
Modified +6 -15
diff --git a/Stardust.Server/Services/DataRetentionService.cs b/Stardust.Server/Services/DataRetentionService.cs
index 2838545..1730f3b 100644
--- a/Stardust.Server/Services/DataRetentionService.cs
+++ b/Stardust.Server/Services/DataRetentionService.cs
@@ -1,6 +1,5 @@
 using NewLife;
 using NewLife.Log;
-using NewLife.Security;
 using NewLife.Threading;
 using Stardust.Data;
 using Stardust.Data.Deployment;
@@ -9,16 +8,9 @@ using Stardust.Data.Nodes;
 
 namespace Stardust.Server.Services;
 
-public class DataRetentionService : IHostedService
+public class DataRetentionService(StarServerSetting setting, ITracer tracer) : IHostedService
 {
-    private readonly StarServerSetting _setting;
-    private readonly ITracer _tracer;
     private TimerX _timer;
-    public DataRetentionService(StarServerSetting setting, ITracer tracer)
-    {
-        _setting = setting;
-        _tracer = tracer;
-    }
 
     public Task StartAsync(CancellationToken cancellationToken)
     {
@@ -36,15 +28,14 @@ public class DataRetentionService : IHostedService
 
     private void DoWork(Object state)
     {
-        var set = _setting;
-        if (set.DataRetention <= 0) return;
+        if (setting.DataRetention <= 0) return;
 
         // 保留数据的起点
-        var time = DateTime.Now.AddDays(-set.DataRetention);
-        var time2 = DateTime.Now.AddDays(-set.DataRetention2);
-        var time3 = DateTime.Now.AddDays(-set.DataRetention3);
+        var time = DateTime.Now.AddDays(-setting.DataRetention);
+        var time2 = DateTime.Now.AddDays(-setting.DataRetention2);
+        var time3 = DateTime.Now.AddDays(-setting.DataRetention3);
 
-        using var span = _tracer?.NewSpan("DataRetention", new { time, time2, time3 });
+        using var span = tracer?.NewSpan("DataRetention", new { time, time2, time3 });
         try
         {
             // 删除节点数据
Modified +4 -18
diff --git a/Stardust.Server/Services/NodeOnlineService.cs b/Stardust.Server/Services/NodeOnlineService.cs
index 6f03d4b..0e2830b 100644
--- a/Stardust.Server/Services/NodeOnlineService.cs
+++ b/Stardust.Server/Services/NodeOnlineService.cs
@@ -7,24 +7,11 @@ using Stardust.Data.Nodes;
 namespace Stardust.Server.Services;
 
 /// <summary>节点在线服务</summary>
-public class NodeOnlineService : IHostedService
+public class NodeOnlineService(IServiceProvider serviceProvider, StarServerSetting setting, ITracer tracer) : IHostedService
 {
     #region 属性
     private TimerX _timer;
     private NodeService _nodeService;
-    private readonly IServiceProvider _serviceProvider;
-    private readonly StarServerSetting _setting;
-    private readonly ITracer _tracer;
-    #endregion
-
-    #region 构造
-    public NodeOnlineService(IServiceProvider serviceProvider, StarServerSetting setting, ITracer tracer)
-    {
-        //_nodeService = nodeService;
-        _serviceProvider = serviceProvider;
-        _setting = setting;
-        _tracer = tracer;
-    }
     #endregion
 
     #region 方法
@@ -45,12 +32,11 @@ public class NodeOnlineService : IHostedService
     private void CheckNodeOnline(Object state)
     {
         // 节点超时
-        var set = _setting;
-        var sessionTimeout = set.SessionTimeout;
+        var sessionTimeout = setting.SessionTimeout;
         if (sessionTimeout > 0)
         {
-            using var span = _tracer?.NewSpan(nameof(CheckNodeOnline));
-            _nodeService ??= _serviceProvider.GetService<NodeService>();
+            using var span = tracer?.NewSpan(nameof(CheckNodeOnline));
+            _nodeService ??= serviceProvider.GetService<NodeService>();
 
             var rs = NodeOnline.ClearExpire(TimeSpan.FromSeconds(sessionTimeout));
             if (rs != null)