Explorar o código

修复格式问题并重构 Worker 类

在 `DataAcquisitionSolution.csproj` 文件中,修复了 `<Project>` 标签的格式问题。

在 `Program.cs` 文件中,删除了多余的括号,修复了代码格式。

在 `Worker.cs` 文件中:
* 添加了类和方法的 XML 注释。
* 将 `Worker` 类的定义从嵌套类移到了顶层,并添加了 `ILogger<Worker>` 的依赖注入。
* 重构了 `ExecuteAsync` 方法,优化了 Redis 和数据库的初始化逻辑。
* 删除了重复的代码块,简化了 Redis 和数据库连接的配置。
* 添加了对 PLC 访问器的初始化和设备信息的初始化。
* 添加了日志记录,捕获并记录了初始化过程中的异常。
林豪 左 hai 10 meses
pai
achega
fe85fa3f99

+ 1 - 1
DataAcquisitionSolution/DataAcquisitionSolution.csproj

@@ -15,4 +15,4 @@
     <PackageReference Include="System.Text.RegularExpressions" Version="4.3.1" />
   </ItemGroup>
 
-</Project>
+</Project>

+ 0 - 1
DataAcquisitionSolution/Program.cs

@@ -65,6 +65,5 @@ public class Program
                     services.AddHttpClient();
                 });
         }
-
     }
 }

+ 122 - 119
DataAcquisitionSolution/Worker.cs

@@ -12,155 +12,158 @@ using ServiceCenter.SqlSugars;
 using SqlSugar;
 using WCS.Core;
 
-namespace DataAcquisitionSolution
+namespace DataAcquisitionSolution;
+
+/// <summary>
+///     工作服务
+/// </summary>
+public class Worker : BackgroundService
 {
+    public static readonly string WcsDlog = "WCSDlog";
+    public static readonly string Wcsdb = "WCSDB";
+
+    /// <summary>
+    ///     记录器
+    /// </summary>
+    private readonly ILogger<Worker> _logger;
+
     /// <summary>
-    /// 工作服务
+    ///     构造函数
     /// </summary>
-    public class Worker : BackgroundService
+    /// <param name="logger">记录器</param>
+    public Worker(ILogger<Worker> logger)
     {
-        /// <summary>
-        /// 记录器
-        /// </summary>
-        private readonly ILogger<Worker> _logger;
-
-        /// <summary>
-        /// 构造函数
-        /// </summary>
-        /// <param name="logger">记录器</param>
-        public Worker(ILogger<Worker> logger)
-        {
-            _logger = logger;
-        }
+        _logger = logger;
+    }
 
-        public static readonly string WcsDlog = "WCSDlog";
-        public static readonly string Wcsdb = "WCSDB";
+    /// <summary>
+    ///     执行
+    /// </summary>
+    /// <param name="stoppingToken">停止令牌</param>
+    /// <returns></returns>
+    protected override Task ExecuteAsync(CancellationToken stoppingToken)
+    {
+        if (stoppingToken.IsCancellationRequested)
+            return Task.CompletedTask;
 
-        /// <summary>
-        ///  执行
-        /// </summary>
-        /// <param name="stoppingToken">停止令牌</param>
-        /// <returns></returns>
-        protected override Task ExecuteAsync(CancellationToken stoppingToken)
-        {
-            if (stoppingToken.IsCancellationRequested)
-                return Task.CompletedTask;
+        #region 初始化Redis连接
 
-            #region 初始化Redis连接
+        var redisConnectionStrings = RedisHub.Default.Check("RedisConnectionStrings") ??
+                                     throw new Exception("请在Redis中配置RedisConnectionStrings");
+        var configs = JsonConvert.DeserializeObject<List<DataBaseConnectionString>>(redisConnectionStrings);
+        if (configs != null)
+            if (configs.All(v => v.Key != "Monitor"))
+                throw new Exception("请在RedisConnectionStrings中配置监控RedisDB库连接字符串");
 
-            var redisConnectionStrings = RedisHub.Default.Check("RedisConnectionStrings") ?? throw new Exception("请在Redis中配置RedisConnectionStrings");
-            var configs = JsonConvert.DeserializeObject<List<DataBaseConnectionString>>(redisConnectionStrings);
-            if (configs != null)
+        foreach (var redisConnection in configs!)
+        {
+            RedisHub.CreateContext(redisConnection.ConnectionString, redisConnection.Key);
+            switch (redisConnection.Key)
             {
-                if (configs.All(v => v.Key != "Monitor")) throw new Exception("请在RedisConnectionStrings中配置监控RedisDB库连接字符串");
+                case "Monitor":
+                    RedisHub.SetMonitorContextType(redisConnection.Key);
+                    RedisHub.Monitor.Serialize = obj =>
+                    {
+                        var bytes = MessagePackSerializer.Serialize(obj);
+                        return bytes;
+                    };
+                    RedisHub.Monitor.DeserializeRaw = (bytes, type) =>
+                    {
+                        var obj = MessagePackSerializer.Deserialize(type, bytes);
+                        return obj;
+                    };
+                    break;
+
+                case "DebugRedisUrl":
+                    RedisHub.SetDebugContextType(redisConnection.Key);
+                    Configs.DebugRedisUrl = redisConnection.ConnectionString;
+                    break;
+
+                case "WMS":
+                    RedisHub.SetWMSContextType(redisConnection.Key);
+                    break;
             }
+        }
 
-            foreach (var redisConnection in configs!)
-            {
-                RedisHub.CreateContext(redisConnection.ConnectionString, redisConnection.Key);
-                switch (redisConnection.Key)
-                {
-                    case "Monitor":
-                        RedisHub.SetMonitorContextType(redisConnection.Key);
-                        RedisHub.Monitor.Serialize = obj =>
-                        {
-                            var bytes = MessagePackSerializer.Serialize(obj);
-                            return bytes;
-                        };
-                        RedisHub.Monitor.DeserializeRaw = (bytes, type) =>
-                        {
-                            var obj = MessagePackSerializer.Deserialize(type, bytes);
-                            return obj;
-                        };
-                        break;
-
-                    case "DebugRedisUrl":
-                        RedisHub.SetDebugContextType(redisConnection.Key);
-                        Configs.DebugRedisUrl = redisConnection.ConnectionString;
-                        break;
-
-                    case "WMS":
-                        RedisHub.SetWMSContextType(redisConnection.Key);
-                        break;
-                }
-            }
+        #endregion 初始化Redis连接
 
-            #endregion 初始化Redis连接
+        #region 启用日志
 
-            #region 启用日志
+        //var logConfigText = RedisHub.Default.Check("LogConfigText") ?? throw new Exception("请在Redis中配置log4net相关内容");
+        //var logConfig = JsonConvert.DeserializeObject<LogConfig>(logConfigText);
+        //LogHub.SetConfigInfo(logConfig!);
 
-            //var logConfigText = RedisHub.Default.Check("LogConfigText") ?? throw new Exception("请在Redis中配置log4net相关内容");
-            //var logConfig = JsonConvert.DeserializeObject<LogConfig>(logConfigText);
-            //LogHub.SetConfigInfo(logConfig!);
+        #endregion 启用日志
 
-            #endregion 启用日志
+        _logger.LogInformation("WCS开始启动");
+        Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
+        Configs.StringEncoding = Encoding.UTF8;
+        //var warehouseName = RedisHub.Default.Check("WarehouseName") ?? throw new Exception("请在Redis中配置仓库名称");
+        //if (string.IsNullOrEmpty(warehouseName)) throw new Exception("请在Redis中配置仓库名称");
+        //ServiceHub.SetWarehouseName(warehouseName);
 
-            _logger.LogInformation("WCS开始启动");
-            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
-            Configs.StringEncoding = Encoding.UTF8;
-            //var warehouseName = RedisHub.Default.Check("WarehouseName") ?? throw new Exception("请在Redis中配置仓库名称");
-            //if (string.IsNullOrEmpty(warehouseName)) throw new Exception("请在Redis中配置仓库名称");
-            //ServiceHub.SetWarehouseName(warehouseName);
+        #region 初始化数据库连接
 
-            #region 初始化数据库连接
+        var dbConnectionStrings =
+            RedisHub.Default.Check("DbConnectionStrings") ?? throw new Exception("请在Redis中配置数据库连接相关内容");
+        ServiceHub.DbConnectionStrings =
+            JsonConvert.DeserializeObject<List<DataBaseConnectionString>>(dbConnectionStrings);
+        if (ServiceHub.DbConnectionStrings != null)
+        {
+            if (ServiceHub.DbConnectionStrings.All(v => v.Key != Wcsdb))
+                throw new Exception("请在DbConnectionStrings中配置WCS基础数据库连接字符串");
+            if (ServiceHub.DbConnectionStrings.All(v => v.Key == Wcsdb && !v.IsDefault))
+                throw new Exception("请在DbConnectionStrings中配置WCS基础数据库为默认数据库");
+            // if (ServiceHub.DbConnectionStrings.All(v => v.Key != WcsDlog)) throw new Exception("请在DbConnectionStrings中配置WCS日志数据库连接字符串");
+        }
 
-            var dbConnectionStrings = RedisHub.Default.Check("DbConnectionStrings") ?? throw new Exception("请在Redis中配置数据库连接相关内容");
-            ServiceHub.DbConnectionStrings = JsonConvert.DeserializeObject<List<DataBaseConnectionString>>(dbConnectionStrings);
-            if (ServiceHub.DbConnectionStrings != null)
+        //设置连接信息
+        var connectionConfigs = ServiceHub.DbConnectionStrings!.Select(connectionString => new ConnectionConfig
             {
-                if (ServiceHub.DbConnectionStrings.All(v => v.Key != Wcsdb)) throw new Exception("请在DbConnectionStrings中配置WCS基础数据库连接字符串");
-                if (ServiceHub.DbConnectionStrings.All(v => v.Key == Wcsdb && !v.IsDefault)) throw new Exception("请在DbConnectionStrings中配置WCS基础数据库为默认数据库");
-                // if (ServiceHub.DbConnectionStrings.All(v => v.Key != WcsDlog)) throw new Exception("请在DbConnectionStrings中配置WCS日志数据库连接字符串");
-            }
+                ConfigId = connectionString.Key,
+                ConnectionString = connectionString.ConnectionString, //连接符字串
+                DbType = connectionString.DbType, //数据库类型
+                IsAutoCloseConnection = true, //不设成true要手动close
+                LanguageType = LanguageType.Chinese,
+                MoreSettings = new ConnMoreSettings { IsNoReadXmlDescription = true }
+            })
+            .ToList();
+        ;
+        SqlSugarHelper.SetDb(new SqlSugarScope(connectionConfigs));
 
-            //设置连接信息
-            var connectionConfigs = ServiceHub.DbConnectionStrings!.Select(connectionString => new ConnectionConfig()
-                {
-                    ConfigId = connectionString.Key,
-                    ConnectionString = connectionString.ConnectionString, //连接符字串
-                    DbType = connectionString.DbType, //数据库类型
-                    IsAutoCloseConnection = true, //不设成true要手动close
-                    LanguageType = LanguageType.Chinese,
-                    MoreSettings = new ConnMoreSettings() { IsNoReadXmlDescription = true }
-                })
-                .ToList();
-            ;
-            SqlSugarHelper.SetDb(new SqlSugarScope(connectionConfigs));
+        ServiceHub.DbConnectionStrings.InitDb();
 
-            ServiceHub.DbConnectionStrings.InitDb();
+        #endregion 初始化数据库连接
 
-            #endregion 初始化数据库连接
+        #region 初始化设备信息
 
-            #region 初始化设备信息
+        WorkStart.InitializeDeviceInfo();
 
-            WorkStart.InitializeDeviceInfo();
+        #endregion 初始化设备信息
 
-            #endregion 初始化设备信息
+        #region 初始化PLC访问器及PLC读取协议
 
-            #region 初始化PLC访问器及PLC读取协议
+        //创建PLC访问器
+        Configs.PLCAccessorCreater = new PlcAccessorsCreater();
 
-            //创建PLC访问器
-            Configs.PLCAccessorCreater = new PlcAccessorsCreater();
-
-            try
-            {
-                #region 唤醒所有的世界
+        try
+        {
+            #region 唤醒所有的世界
 
-                World.StartAll();
+            World.StartAll();
 
-                #endregion 唤醒所有的世界
+            #endregion 唤醒所有的世界
 
-                _logger.LogInformation("WCS启动成功");
-            }
-            catch (Exception ex)
-            {
-                _logger.LogError("WCS启动失败{0}", ex.Message);
-            }
+            _logger.LogInformation("WCS启动成功");
+        }
+        catch (Exception ex)
+        {
+            _logger.LogError("WCS启动失败{0}", ex.Message);
+        }
 
-            #endregion 初始化PLC访问器及PLC读取协议
+        #endregion 初始化PLC访问器及PLC读取协议
 
-            LogHub.init();
-            return Task.CompletedTask;
-        }
+        LogHub.init();
+        return Task.CompletedTask;
     }
-}
+}