Browse Source

将配置移至Redis

林豪 左 2 năm trước cách đây
mục cha
commit
9fcbf8ca83
5 tập tin đã thay đổi với 180 bổ sung160 xóa
  1. 49 9
      WCS.Core/Configs.cs
  2. 18 0
      WCS.Core/Redis/RedisHelper.cs
  3. 7 9
      WCS.Service/Program.cs
  4. 106 86
      WCS.Service/Worker.cs
  5. 0 56
      WCS.Service/config.json

+ 49 - 9
WCS.Core/Configs.cs

@@ -1,7 +1,6 @@
-using System;
+using SqlSugar;
+using System;
 using System.Collections.Generic;
-using System.Configuration;
-using System.IO;
 using System.Text;
 using WCS.Entity;
 
@@ -12,12 +11,14 @@ namespace WCS.Core
     /// </summary>
     public static class Configs
     {
-
         #region 配置中心
 
-       
+        /// <summary>
+        /// 数据库连接字符串集合
+        /// </summary>
+        public static List<DataBaseConnectionString>? DbConnectionStrings { get; set; } = null!;
 
-        #endregion
+        #endregion 配置中心
 
         /// <summary>
         /// ProtocolProxyBase在业务中具体实现类的Type
@@ -51,7 +52,7 @@ namespace WCS.Core
             return SystemModes.Contains(mode);
         }
 
-        #endregion
+        #endregion 系统运行模式
 
         /// <summary>
         /// 默认的字符串编码类型
@@ -84,8 +85,6 @@ namespace WCS.Core
         public static Action<string, string> UploadException { get; set; }
 
         #endregion 异常上抛WMS
-
-
     }
 
     /// <summary>
@@ -98,4 +97,45 @@ namespace WCS.Core
         /// </summary>
         虚拟plc = 1,
     }
+
+    /// <summary>
+    /// 数据库连接
+    /// </summary>
+    public class DataBaseConnectionString
+    {
+        /// <summary>
+        /// 构造函数
+        /// </summary>
+        /// <param name="key">连接对应的Key</param>
+        /// <param name="connectionString">连接字符串</param>
+        /// <param name="dbType">数据库类型</param>
+        /// <param name="isDefault">是否为默认数据库连接</param>
+        public DataBaseConnectionString(string key, string connectionString, DbType dbType, bool isDefault)
+        {
+            Key = key;
+            ConnectionString = connectionString;
+            DbType = dbType;
+            IsDefault = isDefault;
+        }
+
+        /// <summary>
+        /// 连接对应的Key
+        /// </summary>
+        public string Key { get; set; }
+
+        /// <summary>
+        /// 连接字符串
+        /// </summary>
+        public string ConnectionString { get; set; }
+
+        /// <summary>
+        /// 数据库类型
+        /// </summary>
+        public DbType DbType { get; set; }
+
+        /// <summary>
+        /// 是否为默认数据库连接
+        /// </summary>
+        public bool IsDefault { get; set; }
+    }
 }

+ 18 - 0
WCS.Core/Redis/RedisHelper.cs

@@ -76,6 +76,24 @@ namespace WCS.Core.Redis
             if (ctx == null) throw new Exception("没有对应的链接,请先调用创建");
             return ctx.Client;
         }
+
+        /// <summary>
+        /// 检查Redis中是否有对应key且value不为空
+        /// </summary>
+        /// <param name="redisClient">redis连接</param>
+        /// <param name="key">要检查的Key</param>
+        /// <returns>
+        /// 1.key不存在,创建这个key value默认为三个空格符。返回null
+        /// 2.key存在单value为空 返回null
+        /// 3.key存在value不为空 返回获取到的值
+        /// </returns>
+        public static string? Check(this RedisClient redisClient, string key)
+        {
+            var result = redisClient.Get(key);
+            if (!string.IsNullOrEmpty(result)) return result;
+            redisClient.Set(key, "   ");
+            return null;
+        }
     }
 
     /// <summary>

+ 7 - 9
WCS.Service/Program.cs

@@ -1,6 +1,7 @@
 using Microsoft.AspNetCore.Hosting;
 using System.Runtime.InteropServices;
 using WCS.Core;
+using WCS.Core.Redis;
 using WCS.WebApi;
 using RedisHelper = WCS.Core.Redis.RedisHelper;
 
@@ -21,17 +22,12 @@ namespace WCS.Service
             #endregion 接入Redis
 
             //互斥锁检测
-            var mutexName = RedisHelper.Default.Get("Mutex");
-            if (string.IsNullOrEmpty(mutexName))
-            {
-                RedisHelper.Default.Set("Mutex", "   ");
-                Console.WriteLine("请在Redis中配置互斥量值");
-                return;
-            }
+            var mutexName = RedisHelper.Default.Check("Mutex") ?? throw new Exception("请在Redis中配置互斥量值");
+
             using var mt = new Mutex(true, mutexName);
             if (mt.WaitOne())
             {
-                Configs.AddSystemMode(SystemMode.虚拟plc);
+                
                 CreateHostBuilder(args).Build().Run(); mt.ReleaseMutex();
             }
             else
@@ -54,11 +50,13 @@ namespace WCS.Service
             Console.WriteLine($"win:{isWin}");
             if (isWin)
             {
+                var useUrls = RedisHelper.Default.Check("UseUrls") ?? throw new Exception("请在Redis中配置网络访问端口");
+                //"http://*:8080"
                 return Host.CreateDefaultBuilder(args)
                     .UseWindowsService()//win
                     .ConfigureWebHostDefaults(web => //网络访问配置
                     {
-                        web.UseUrls("http://*:8080"); //设备访问端口
+                        web.UseUrls(useUrls); //设备访问端口
                         web.UseStartup<Startup>(); //调用启动服务
                     })
                     .ConfigureServices((_, services) =>

+ 106 - 86
WCS.Service/Worker.cs

@@ -6,6 +6,7 @@ using WCS.Core.DataTrans;
 using WCS.Core.DbHelper;
 using WCS.Core.Helpers;
 using WCS.Core.Log;
+using WCS.Core.Redis;
 using WCS.Core.Virtual_PLC;
 using WCS.Entity;
 using WCS.Entity.Protocol;
@@ -25,6 +26,7 @@ namespace WCS.Service
         }
 
         public static readonly string WcsDlog = "WCSDlog";
+        public static readonly string Wcsdb = "WCSDB";
 
         protected override async System.Threading.Tasks.Task ExecuteAsync(CancellationToken stoppingToken)
         {
@@ -33,105 +35,128 @@ namespace WCS.Service
 
             #region 启用日志
 
-            var logConfig = JsonConvert.DeserializeObject<LogConfig>(await File.ReadAllTextAsync("config.json", Encoding.Default, stoppingToken));
+            var logConfigText = RedisHelper.Default.Check("LogConfigText") ?? throw new Exception("请在Redis中配置log4net相关内容");
+            var logConfig = JsonConvert.DeserializeObject<LogConfig>(logConfigText);
             LogHelper.SetConfigInfo(logConfig!);
 
             #endregion 启用日志
 
-            InfoLog.INFO_INIT("1111");
-
             _logger.LogInformation("WCS开始启动");
-            //InfoLog.INFO_INIT("WCS开始启动");
-            //Configs.DebugRedisUrl = "127.0.0.1";
             Configs.ProtocolProxyBaseType = typeof(ProtocolProxy);
             Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
             Configs.StringEncoding = Encoding.UTF8;
 
-            #region 需要改成循环遍历,以实现根据配置项完成多个数据库链接创建
+            #region 初始化数据库连接
 
-            Db.CreateContext(new ConnectionConfig()
-            {
-                ConnectionString = AppSettings.Config.GetConnectionString("WCSDB"),
-                DbType = DbType.SqlServer
-            }, "WCSDB");
-            Db.SetDefaultDbContextType("WCSDB");
-            Db.Do(db =>
-            {
-                //TODO:DbMaintenance.CreateDatabase()并没起到作用,如果没有对应的数据库的话任然需要手动新建一个
-                db.Default.DbMaintenance.CreateDatabase();
-                db.Default.CodeFirst.InitTables(typeof(WCS_CMD));
-                db.Default.CodeFirst.InitTables(typeof(WCS_PLC));
-                db.Default.CodeFirst.InitTables(typeof(WCS_DATABLOCK));
-                db.Default.CodeFirst.InitTables(typeof(WCS_DEVICE));
-                db.Default.CodeFirst.InitTables(typeof(WCS_PATH));
-                db.Default.CodeFirst.InitTables(typeof(WCS_PATHPOINT));
-                db.Default.CodeFirst.InitTables(typeof(WCS_ROUTE));
-                db.Default.CodeFirst.InitTables(typeof(WCS_TASK));
-                db.Default.CodeFirst.InitTables(typeof(WCS_TASK_OLD));
-                db.Default.CodeFirst.InitTables(typeof(WCS_EXCEPTION));
-                db.Default.CodeFirst.InitTables(typeof(WCS_SystemConfig));
-                db.Default.CodeFirst.InitTables(typeof(WCS_AGVTask));
-                db.Default.CodeFirst.InitTables(typeof(WCS_DEVICEPROTOCOL));
-                db.Default.CodeFirst.InitTables(typeof(WCS_GROUPMEMBER));
-                db.Default.CodeFirst.InitTables(typeof(WCS_MAPPINGENTRY));
-                db.Default.CodeFirst.InitTables(typeof(WCS_USERS));
-                db.Default.CodeFirst.InitTables(typeof(WCS_StatusLog));
-                db.Default.CodeFirst.InitTables(typeof(WCS.Entity.PlcRawData));
-                //db.Default.CodeFirst.InitTables(typeof(WCS_BCR80));
-                //db.Default.CodeFirst.InitTables(typeof(WCS_RGV520));
-                //db.Default.CodeFirst.InitTables(typeof(WCS_RGV521));
-                //db.Default.CodeFirst.InitTables(typeof(WCS_RGV523));
-                //db.Default.CodeFirst.InitTables(typeof(WCS_SRM520));
-                //db.Default.CodeFirst.InitTables(typeof(WCS_SRM521));
-                //db.Default.CodeFirst.InitTables(typeof(WCS_SRM537));
-                //db.Default.CodeFirst.InitTables(typeof(WCS_Station520));
-                //db.Default.CodeFirst.InitTables(typeof(WCS_Station521));
-                //db.Default.CodeFirst.InitTables(typeof(WCS_Station523));
-            });
-
-            Db.CreateContext(new ConnectionConfig()
+            var dbConnectionStrings = RedisHelper.Default.Check("DbConnectionStrings") ?? throw new Exception("请在Redis中配置数据库连接相关内容");
+            Configs.DbConnectionStrings = JsonConvert.DeserializeObject<List<DataBaseConnectionString>>(dbConnectionStrings);
+            if (Configs.DbConnectionStrings != null)
             {
-                ConnectionString = AppSettings.Config.GetConnectionString(WcsDlog),
-                DbType = DbType.PostgreSQL
-            }, WcsDlog);
+                if (Configs.DbConnectionStrings.All(v => v.Key != Wcsdb)) throw new Exception("请在DbConnectionStrings中配置WCS基础数据库连接字符串");
+                if (Configs.DbConnectionStrings.All(v => v.Key == Wcsdb && !v.IsDefault)) throw new Exception("请在DbConnectionStrings中配置WCS基础数据库为默认数据库");
+                if (Configs.DbConnectionStrings.All(v => v.Key != WcsDlog)) throw new Exception("请在DbConnectionStrings中配置WCS日志数据库连接字符串");
+            }
 
-            Db.Do(db =>
+            foreach (var connectionString in Configs.DbConnectionStrings!)
             {
-                //TODO:DbMaintenance.CreateDatabase()并没起到作用,如果没有对应的数据库的话任然需要手动新建一个
-                db.Context(WcsDlog).DbMaintenance.CreateDatabase();
-                db.Context(WcsDlog).CodeFirst.InitTables(typeof(WCS_BCR80));
-                db.Context(WcsDlog).CodeFirst.InitTables(typeof(WCS_RGV520));
-                db.Context(WcsDlog).CodeFirst.InitTables(typeof(WCS_RGV521));
-                db.Context(WcsDlog).CodeFirst.InitTables(typeof(WCS_RGV523));
-                db.Context(WcsDlog).CodeFirst.InitTables(typeof(WCS_SRM520));
-                db.Context(WcsDlog).CodeFirst.InitTables(typeof(WCS_SRM521));
-                db.Context(WcsDlog).CodeFirst.InitTables(typeof(WCS_SRM537));
-                db.Context(WcsDlog).CodeFirst.InitTables(typeof(WCS_Station520));
-                db.Context(WcsDlog).CodeFirst.InitTables(typeof(WCS_Station521));
-                db.Context(WcsDlog).CodeFirst.InitTables(typeof(WCS_Station523));
-                db.Context(WcsDlog).CodeFirst.InitTables(typeof(WCS.Entity.PlcRawData));
-            });
-
-            #endregion 需要改成循环遍历,以实现根据配置项完成多个数据库链接创建
-
-            //从现有结构解析出需要的结构
-            List<PLCData> list = new List<PLCData>();
-            Db.Do(db =>
+                Db.CreateContext(new ConnectionConfig()
+                {
+                    ConnectionString = connectionString.ConnectionString,
+                    DbType = connectionString.DbType
+                }, connectionString.Key);
+                if (connectionString.IsDefault) Db.SetDefaultDbContextType(connectionString.Key);
+
+                switch (connectionString.Key)
+                {
+                    case "WCSDB"://WCS基本数据库
+                        Db.Do(db =>
+                        {
+                            //TODO:DbMaintenance.CreateDatabase()并没起到作用,如果没有对应的数据库的话任然需要手动新建一个
+                            db.Default.DbMaintenance.CreateDatabase();
+                            db.Default.CodeFirst.InitTables(typeof(WCS_CMD));
+                            db.Default.CodeFirst.InitTables(typeof(WCS_PLC));
+                            db.Default.CodeFirst.InitTables(typeof(WCS_DATABLOCK));
+                            db.Default.CodeFirst.InitTables(typeof(WCS_DEVICE));
+                            db.Default.CodeFirst.InitTables(typeof(WCS_PATH));
+                            db.Default.CodeFirst.InitTables(typeof(WCS_PATHPOINT));
+                            db.Default.CodeFirst.InitTables(typeof(WCS_ROUTE));
+                            db.Default.CodeFirst.InitTables(typeof(WCS_TASK));
+                            db.Default.CodeFirst.InitTables(typeof(WCS_TASK_OLD));
+                            db.Default.CodeFirst.InitTables(typeof(WCS_EXCEPTION));
+                            db.Default.CodeFirst.InitTables(typeof(WCS_SystemConfig));
+                            db.Default.CodeFirst.InitTables(typeof(WCS_AGVTask));
+                            db.Default.CodeFirst.InitTables(typeof(WCS_DEVICEPROTOCOL));
+                            db.Default.CodeFirst.InitTables(typeof(WCS_GROUPMEMBER));
+                            db.Default.CodeFirst.InitTables(typeof(WCS_MAPPINGENTRY));
+                            db.Default.CodeFirst.InitTables(typeof(WCS_USERS));
+                            db.Default.CodeFirst.InitTables(typeof(WCS_StatusLog));
+                            db.Default.CodeFirst.InitTables(typeof(WCS.Entity.PlcRawData));
+                            //db.Default.CodeFirst.InitTables(typeof(WCS_BCR80));
+                            //db.Default.CodeFirst.InitTables(typeof(WCS_RGV520));
+                            //db.Default.CodeFirst.InitTables(typeof(WCS_RGV521));
+                            //db.Default.CodeFirst.InitTables(typeof(WCS_RGV523));
+                            //db.Default.CodeFirst.InitTables(typeof(WCS_SRM520));
+                            //db.Default.CodeFirst.InitTables(typeof(WCS_SRM521));
+                            //db.Default.CodeFirst.InitTables(typeof(WCS_SRM537));
+                            //db.Default.CodeFirst.InitTables(typeof(WCS_Station520));
+                            //db.Default.CodeFirst.InitTables(typeof(WCS_Station521));
+                            //db.Default.CodeFirst.InitTables(typeof(WCS_Station523));
+                        });
+                        break;
+
+                    case "WCSDlog"://WCS日志数据库
+                        Db.Do(db =>
+                        {
+                            //TODO:DbMaintenance.CreateDatabase()并没起到作用,如果没有对应的数据库的话任然需要手动新建一个
+                            db.Context(WcsDlog).DbMaintenance.CreateDatabase();
+                            db.Context(WcsDlog).CodeFirst.InitTables(typeof(WCS_BCR80));
+                            db.Context(WcsDlog).CodeFirst.InitTables(typeof(WCS_RGV520));
+                            db.Context(WcsDlog).CodeFirst.InitTables(typeof(WCS_RGV521));
+                            db.Context(WcsDlog).CodeFirst.InitTables(typeof(WCS_RGV523));
+                            db.Context(WcsDlog).CodeFirst.InitTables(typeof(WCS_SRM520));
+                            db.Context(WcsDlog).CodeFirst.InitTables(typeof(WCS_SRM521));
+                            db.Context(WcsDlog).CodeFirst.InitTables(typeof(WCS_SRM537));
+                            db.Context(WcsDlog).CodeFirst.InitTables(typeof(WCS_Station520));
+                            db.Context(WcsDlog).CodeFirst.InitTables(typeof(WCS_Station521));
+                            db.Context(WcsDlog).CodeFirst.InitTables(typeof(WCS_Station523));
+                            db.Context(WcsDlog).CodeFirst.InitTables(typeof(WCS.Entity.PlcRawData));
+                        });
+                        break;
+
+                    default: //其他库
+                        break;
+                }
+            }
+
+            #endregion 初始化数据库连接
+
+            #region 创建虚拟PLC
+
+            var isOpenVirtualPlc = RedisHelper.Default.Check("isOpenVirtualPLC");
+            if (isOpenVirtualPlc == "1")
             {
-                var dataBlocks = db.Default.Queryable<WCS_DATABLOCK>().Includes(v => v.PLC).ToList();
-                foreach (var dataBlock in dataBlocks)
+                var plcDataConnectionString = RedisHelper.Default.Check("plcDataConnectionString") ?? throw new Exception("请在Redsi中配置虚拟PLC使用的Redis连接字符串");
+
+                //从现有结构解析出需要的结构
+                var list = new List<PLCData>();
+                Db.Do(db =>
                 {
-                    list.Add(new PLCData()
+                    var dataBlocks = db.Default.Queryable<WCS_DATABLOCK>().Includes(v => v.PLC).ToList();
+                    list.AddRange(dataBlocks.Select(dataBlock => new PLCData()
                     {
                         IP = dataBlock.PLC.IP,
                         DB = dataBlock.NO,
                         Length = dataBlock.LENGTH,
                         DataLength = dataBlock.DATALENGTH,
-                    });
-                }
-            });
+                    }));
+                });
+                PlcData.Init(plcDataConnectionString).InitPlcData(list);
+            }
 
-            PlcData.Init("127.0.0.1,database=0").InitPlcData(list);
+            #endregion 创建虚拟PLC
+
+            //是否启用虚拟PLC
+            Configs.AddSystemMode(SystemMode.虚拟plc);
             //日志发布事件s
             Configs.PublishEvent += () =>
             {
@@ -150,8 +175,6 @@ namespace WCS.Service
                 WMS.TaskException(d, s);
             };
 
-            //LogicHandler.DbLog = Helpers.LogHelper.AddWCS_EXCEPTION;
-
             PlcAccessor.Creater = new PLCAccessors.PlcAccessorsCreater();
             try
             {
@@ -161,8 +184,8 @@ namespace WCS.Service
                     .Includes(d => d.DEVICE, r => r.ROUTES)
                     .Includes(d => d.DEVICE, p => p.PATHS)
                     .Includes(d => d.DB, p => p.PLC).ToArray();
-                    items.Select(v => v.Data()).ToArray();
-                    LogicHandler.AllObjects.AddRange(items);
+                    var objects = items.Select(v => v.Data()).ToArray();
+                    LogicHandler.AllObjects.AddRange(objects);
 
                     var devices = db.Default.Queryable<WCS_DEVICE>()
                                             .Includes(v => v.ROUTES)
@@ -211,7 +234,7 @@ namespace WCS.Service
                 foreach (var type in managerTypes)
                 {
                     var m = Activator.CreateInstance(type);
-                    LogicHandler.AddManager(m as LogicHandler);
+                    LogicHandler.AddManager((m as LogicHandler)!);
                 }
 
                 LogicHandler.StartAll();
@@ -219,19 +242,16 @@ namespace WCS.Service
                 #endregion 启用所有的逻辑处理器
 
                 _logger.LogInformation("WCS启动成功");
-                //InfoLog.INFO_INIT("WCS启动成功");
             }
             catch (Exception ex)
             {
                 _logger.LogError("WCS启动失败{0}", ex.Message);
-                //InfoLog.INFO_INIT($"WCS启动失败{ex.Message}");
             }
         }
 
         public override System.Threading.Tasks.Task StopAsync(CancellationToken cancellationToken)
         {
             _logger.LogError("WCS关闭");
-            //InfoLog.INFO_INIT("WCS关闭");
             LogicHandler.StopAll();
             return base.StopAsync(cancellationToken);
         }

+ 0 - 56
WCS.Service/config.json

@@ -1,56 +0,0 @@
-{
-  "LogPath": "D:\\WCSLog\\", // ��־Ŀ¼
-  "LogDays": 30,
-  "LogSize": 100,
-  "Logs": [
-    {
-      "Name": "Info",
-      "FileName": "D:\\WCSLog\\",
-      "SubLogNames": {
-        "INFO_INIT": "Info_Init",
-        "INFO_SRMALARM": "Info_SrmAlarm",
-        "INFO_INFO": "Info_Info",
-        "INFO_ERROR": "Info_Error",
-        "INFO_SRMINFO": "Info_SRMInfo",
-        "INFO_SYTASKSTATUS": "Info_SyTaskTatus",
-        "INFO_WMSREQUEST": "INFO_WMSRequest",
-        "INFO_WARN": "Info_Warn",
-        "INFO_PLCREADLOG": "Info_PlcReadLog",
-        "INFO_TIMING": "Info_Timing",
-        "INFO_UPEX": "INFO_I_WCS_GetExcTask",
-        "INFO_CREATETASKIN": "CreateTaskIn",
-        "INFO_RGVINFO": "RgvInfo",
-        "INFO_AGV": "info_agv"
-      }
-    },
-
-    {
-      "Name": "PLC",
-      "FileName": "D:\\WCSLog\\",
-      "SubLogNames": {
-        "PLC_LINKS": "PLC_Links"
-      }
-    },
-    {
-      "Name": "Error",
-      "FileName": "D:\\WCSLog\\",
-      "SubLogNames": {
-      }
-    },
-    {
-      "Name": "Warn",
-      "FileName": "D:\\WCSLog\\",
-      "SubLogNames": {
-      }
-    },
-    {
-      "Name": "Db",
-      "FileName": "D:\\WCSLog\\",
-      "SubLogNames": {
-        "DB_EX": "Db_Ex",
-        "DB_CLEAN": "Db_Clean",
-        "INFO_PLCREADLOG": "Info_PlcReadLog"
-      }
-    }
-  ]
-}