This commit is contained in:
Diego
2025-06-13 13:35:38 +08:00
parent 1c7f8b5cab
commit 003b8a3763
41 changed files with 170 additions and 137 deletions

View File

@@ -20,6 +20,7 @@ using System.Collections.Concurrent;
using ThingsGateway.Extension; using ThingsGateway.Extension;
using ThingsGateway.FriendlyException; using ThingsGateway.FriendlyException;
using ThingsGateway.NewLife.Json.Extension; using ThingsGateway.NewLife.Json.Extension;
using ThingsGateway.SqlSugar;
namespace ThingsGateway.Admin.Application; namespace ThingsGateway.Admin.Application;
@@ -90,13 +91,12 @@ public sealed class OperDescAttribute : MoAttribute
OperDescAttribute.WriteToQueue(log); OperDescAttribute.WriteToQueue(log);
} }
} }
private static SqlSugarClient _db = DbContext.Db.GetConnectionScopeWithAttr<SysOperateLog>().CopyNew();
/// <summary> /// <summary>
/// 将日志消息写入数据库中 /// 将日志消息写入数据库中
/// </summary> /// </summary>
private static async Task ProcessQueue() private static async Task ProcessQueue()
{ {
var db = DbContext.Db.GetConnectionScopeWithAttr<SysOperateLog>().CopyNew();
var appLifetime = App.RootServices!.GetService<IHostApplicationLifetime>()!; var appLifetime = App.RootServices!.GetService<IHostApplicationLifetime>()!;
while (!appLifetime.ApplicationStopping.IsCancellationRequested) while (!appLifetime.ApplicationStopping.IsCancellationRequested)
{ {
@@ -105,7 +105,7 @@ public sealed class OperDescAttribute : MoAttribute
var data = _logMessageQueue.ToListWithDequeue(); // 从日志队列中获取数据 var data = _logMessageQueue.ToListWithDequeue(); // 从日志队列中获取数据
if (data.Count > 0) if (data.Count > 0)
{ {
await db.InsertableWithAttr(data).ExecuteCommandAsync(appLifetime.ApplicationStopping).ConfigureAwait(false);//入库 await _db.InsertableWithAttr(data).ExecuteCommandAsync(appLifetime.ApplicationStopping).ConfigureAwait(false);//入库
} }
} }
catch (Exception ex) catch (Exception ex)

View File

@@ -20,6 +20,7 @@ using ThingsGateway.NewLife;
using ThingsGateway.NewLife.Caching; using ThingsGateway.NewLife.Caching;
using ThingsGateway.NewLife.Threading; using ThingsGateway.NewLife.Threading;
using ThingsGateway.Schedule; using ThingsGateway.Schedule;
using ThingsGateway.SqlSugar;
namespace ThingsGateway.Admin.Application; namespace ThingsGateway.Admin.Application;
@@ -60,7 +61,7 @@ public class HardwareJob : IJob, IHardwareJob
var historyHardwareInfos = MemoryCache.Get<List<HistoryHardwareInfo>>(CacheKey); var historyHardwareInfos = MemoryCache.Get<List<HistoryHardwareInfo>>(CacheKey);
if (historyHardwareInfos == null) if (historyHardwareInfos == null)
{ {
using var db = DbContext.Db.GetConnectionScopeWithAttr<HistoryHardwareInfo>().CopyNew(); using var db = _db.CopyNew();
historyHardwareInfos = await db.Queryable<HistoryHardwareInfo>().Where(a => a.Date > DateTime.Now.AddDays(-3)).ToListAsync().ConfigureAwait(false); historyHardwareInfos = await db.Queryable<HistoryHardwareInfo>().Where(a => a.Date > DateTime.Now.AddDays(-3)).ToListAsync().ConfigureAwait(false);
MemoryCache.Set(CacheKey, historyHardwareInfos); MemoryCache.Set(CacheKey, historyHardwareInfos);
@@ -70,6 +71,7 @@ public class HardwareJob : IJob, IHardwareJob
private bool error = false; private bool error = false;
private DateTime hisInsertTime = default; private DateTime hisInsertTime = default;
private SqlSugarClient _db = DbContext.Db.GetConnectionScopeWithAttr<HistoryHardwareInfo>().CopyNew();
public async Task ExecuteAsync(JobExecutingContext context, CancellationToken stoppingToken) public async Task ExecuteAsync(JobExecutingContext context, CancellationToken stoppingToken)
{ {
@@ -121,7 +123,6 @@ public class HardwareJob : IJob, IHardwareJob
if (DateTime.Now > hisInsertTime.Add(TimeSpan.FromMilliseconds(HardwareInfoOptions.HistoryInterval))) if (DateTime.Now > hisInsertTime.Add(TimeSpan.FromMilliseconds(HardwareInfoOptions.HistoryInterval)))
{ {
hisInsertTime = DateTime.Now; hisInsertTime = DateTime.Now;
using var db = DbContext.Db.GetConnectionScopeWithAttr<HistoryHardwareInfo>().CopyNew();
{ {
var his = new HistoryHardwareInfo() var his = new HistoryHardwareInfo()
{ {
@@ -132,12 +133,12 @@ public class HardwareJob : IJob, IHardwareJob
CpuUsage = (HardwareInfo.MachineInfo.CpuRate * 100).ToInt(), CpuUsage = (HardwareInfo.MachineInfo.CpuRate * 100).ToInt(),
Temperature = (HardwareInfo.MachineInfo.Temperature).ToInt(), Temperature = (HardwareInfo.MachineInfo.Temperature).ToInt(),
}; };
await db.Insertable(his).ExecuteCommandAsync(stoppingToken).ConfigureAwait(false); await _db.Insertable(his).ExecuteCommandAsync(stoppingToken).ConfigureAwait(false);
MemoryCache.Remove(CacheKey); MemoryCache.Remove(CacheKey);
} }
var sevenDaysAgo = TimerX.Now.AddDays(-HardwareInfoOptions.DaysAgo); var sevenDaysAgo = TimerX.Now.AddDays(-HardwareInfoOptions.DaysAgo);
//删除特定信息 //删除特定信息
var result = await db.Deleteable<HistoryHardwareInfo>(a => a.Date <= sevenDaysAgo).ExecuteCommandAsync(stoppingToken).ConfigureAwait(false); var result = await _db.Deleteable<HistoryHardwareInfo>(a => a.Date <= sevenDaysAgo).ExecuteCommandAsync(stoppingToken).ConfigureAwait(false);
if (result > 0) if (result > 0)
{ {
MemoryCache.Remove(CacheKey); MemoryCache.Remove(CacheKey);

View File

@@ -18,7 +18,7 @@ public class SysRelationSeedData : ISqlSugarEntitySeedData<SysRelation>
/// <inheritdoc/> /// <inheritdoc/>
public IEnumerable<SysRelation> SeedData() public IEnumerable<SysRelation> SeedData()
{ {
var db = DbContext.Db.GetConnectionScopeWithAttr<SysRelation>().CopyNew(); using var db = DbContext.Db.GetConnectionScopeWithAttr<SysRelation>().CopyNew();
if (db.Queryable<SysRelation>().Any(a => a.ObjectId == RoleConst.SuperAdminId)) if (db.Queryable<SysRelation>().Any(a => a.ObjectId == RoleConst.SuperAdminId))
return Enumerable.Empty<SysRelation>(); return Enumerable.Empty<SysRelation>();
var data = SeedDataUtil.GetSeedData<SysRelation>(PathExtensions.CombinePathWithOs("SeedData", "Admin", "seed_sys_relation.json")); var data = SeedDataUtil.GetSeedData<SysRelation>(PathExtensions.CombinePathWithOs("SeedData", "Admin", "seed_sys_relation.json"));

View File

@@ -124,16 +124,8 @@ public class SugarAopService : ISugarAopService
//执行时间超过1秒 //执行时间超过1秒
if (db.Ado.SqlExecutionTime.TotalSeconds > 1) if (db.Ado.SqlExecutionTime.TotalSeconds > 1)
{ {
//代码CS文件名 DbContext.WriteLog($"SQL执行时间超过1秒");
var fileName = db.Ado.SqlStackTrace.FirstFileName;
//代码行数
var fileLine = db.Ado.SqlStackTrace.FirstLine;
//方法名
var FirstMethodName = db.Ado.SqlStackTrace.FirstMethodName;
DbContext.WriteLog($"{fileName}-{FirstMethodName}-{fileLine} 执行时间超过1秒");
DbContext.WriteLogWithSql(UtilMethods.GetNativeSql(sql, pars)); DbContext.WriteLogWithSql(UtilMethods.GetNativeSql(sql, pars));
} }
}; };
} }

View File

@@ -1160,7 +1160,7 @@ public class MachineInfo
public static String GetInfo(String path, String property, String? nameSpace = null) public static String GetInfo(String path, String property, String? nameSpace = null)
{ {
// Linux Mono不支持WMI // Linux Mono不支持WMI
if (Runtime.Mono) return ""; if (Runtime.Mono) return string.Empty;
var bbs = new List<String>(); var bbs = new List<String>();
try try
@@ -1181,7 +1181,7 @@ public class MachineInfo
catch (Exception ex) catch (Exception ex)
{ {
if (XTrace.Log.Level <= LogLevel.Debug) XTrace.WriteLine("WMI.GetInfo({0})失败!{1}", path, ex.Message); if (XTrace.Log.Level <= LogLevel.Debug) XTrace.WriteLine("WMI.GetInfo({0})失败!{1}", path, ex.Message);
return ""; return string.Empty;
} }
bbs.Sort(); bbs.Sort();

View File

@@ -854,13 +854,13 @@ public static class IOHelper
/// <returns></returns> /// <returns></returns>
public static String ToHex(this Byte[]? data, Int32 offset = 0, Int32 count = -1) public static String ToHex(this Byte[]? data, Int32 offset = 0, Int32 count = -1)
{ {
if (data == null || data.Length <= 0) return ""; if (data == null || data.Length <= 0) return string.Empty;
if (count < 0) if (count < 0)
count = data.Length - offset; count = data.Length - offset;
else if (offset + count > data.Length) else if (offset + count > data.Length)
count = data.Length - offset; count = data.Length - offset;
if (count == 0) return ""; if (count == 0) return string.Empty;
//return BitConverter.ToString(data).Replace("-", null); //return BitConverter.ToString(data).Replace("-", null);
// 上面的方法要替换-,效率太低 // 上面的方法要替换-,效率太低
@@ -883,7 +883,7 @@ public static class IOHelper
/// <returns></returns> /// <returns></returns>
public static String ToHex(this Byte[]? data, String? separate, Int32 groupSize = 0, Int32 maxLength = -1) public static String ToHex(this Byte[]? data, String? separate, Int32 groupSize = 0, Int32 maxLength = -1)
{ {
if (data == null || data.Length <= 0) return ""; if (data == null || data.Length <= 0) return string.Empty;
if (groupSize < 0) groupSize = 0; if (groupSize < 0) groupSize = 0;

View File

@@ -201,9 +201,9 @@ namespace ThingsGateway.SqlSugar
try try
{ {
if (this.Context.CurrentConnectionConfig?.MoreSettings?.IsNoReadXmlDescription == true) if (this.Context.CurrentConnectionConfig?.MoreSettings?.IsNoReadXmlDescription ?? true == true)
{ {
return ""; return string.Empty;
} }
if (entityType.Assembly.IsDynamic && entityType.Assembly.FullName.StartsWith("Dynamic")) if (entityType.Assembly.IsDynamic && entityType.Assembly.FullName.StartsWith("Dynamic"))
{ {

View File

@@ -17,7 +17,7 @@
public int DefaultCacheDurationInSeconds { get; set; } public int DefaultCacheDurationInSeconds { get; set; }
public bool? TableEnumIsString { get; set; } public bool? TableEnumIsString { get; set; }
public DateTime? DbMinDate { get; set; } = DateTime.MinValue.Date.AddYears(1900 - 1); public DateTime? DbMinDate { get; set; } = DateTime.MinValue.Date.AddYears(1900 - 1);
public bool IsNoReadXmlDescription { get; set; } public bool IsNoReadXmlDescription { get; set; } = true;
public bool SqlServerCodeFirstNvarchar { get; set; } public bool SqlServerCodeFirstNvarchar { get; set; }
public bool OracleCodeFirstNvarchar2 { get; set; } public bool OracleCodeFirstNvarchar2 { get; set; }
public bool SqliteCodeFirstEnableDefaultValue { get; set; } public bool SqliteCodeFirstEnableDefaultValue { get; set; }

View File

@@ -501,7 +501,7 @@ namespace ThingsGateway.SqlSugar
{ {
return GetFirstTypeNameFromExpression(methodCall.Arguments.FirstOrDefault()); return GetFirstTypeNameFromExpression(methodCall.Arguments.FirstOrDefault());
} }
return ""; return string.Empty;
} }
public static string GetMethodName(Expression expression) public static string GetMethodName(Expression expression)

View File

@@ -245,7 +245,7 @@ namespace ThingsGateway.SqlSugar
public string GetMemberName(MemberExpression memberExpression) public string GetMemberName(MemberExpression memberExpression)
{ {
return ""; return string.Empty;
} }
private void ExtMapper(MapperExpressionInfo fillInfo, MapperExpressionInfo mappingFild1Info, MapperExpressionInfo mappingFild1Info2, MapperExpressionInfo selectInfo) private void ExtMapper(MapperExpressionInfo fillInfo, MapperExpressionInfo mappingFild1Info, MapperExpressionInfo mappingFild1Info2, MapperExpressionInfo selectInfo)

View File

@@ -47,7 +47,7 @@ namespace ThingsGateway.SqlSugar
var isWhere = Convert.ToBoolean(value); var isWhere = Convert.ToBoolean(value);
if (!Convert.ToBoolean(isWhere)) if (!Convert.ToBoolean(isWhere))
{ {
return ""; return string.Empty;
} }
var argExp = exp.Arguments[1]; var argExp = exp.Arguments[1];
var copyContext = this.Context; var copyContext = this.Context;

View File

@@ -43,7 +43,7 @@ namespace ThingsGateway.SqlSugar
} }
else else
{ {
return ""; return string.Empty;
} }
} }
} }

View File

@@ -576,7 +576,7 @@ WHERE table_name = '" + tableName + "'");
} }
else else
{ {
return ""; return string.Empty;
} }
} }

View File

@@ -144,7 +144,7 @@ namespace ThingsGateway.SqlSugar
public string DataTableToCsvString(DataTable table) public string DataTableToCsvString(DataTable table)
{ {
if (table.Rows.Count == 0) if (table.Rows.Count == 0)
return ""; return string.Empty;
StringBuilder sb = new StringBuilder(); StringBuilder sb = new StringBuilder();
DataColumn colum; DataColumn colum;
foreach (DataRow row in table.Rows) foreach (DataRow row in table.Rows)

View File

@@ -262,7 +262,7 @@ namespace ThingsGateway.SqlSugar
{ {
get get
{ {
return ""; return string.Empty;
} }
} }
#endregion #endregion

View File

@@ -51,7 +51,7 @@ namespace ThingsGateway.SqlSugar
{ {
get get
{ {
return ""; return string.Empty;
} }
} }
protected override string AddColumnToTableSql protected override string AddColumnToTableSql

View File

@@ -92,12 +92,12 @@ namespace ThingsGateway.SqlSugar
public static string ObjToString(this object thisValue) public static string ObjToString(this object thisValue)
{ {
if (thisValue != null) return thisValue.ToString().Trim(); if (thisValue != null) return thisValue.ToString().Trim();
return ""; return string.Empty;
} }
public static string ObjToStringNoTrim(this object thisValue) public static string ObjToStringNoTrim(this object thisValue)
{ {
if (thisValue != null) return thisValue.ToString(); if (thisValue != null) return thisValue.ToString();
return ""; return string.Empty;
} }
public static string ObjToStringNew(this object thisValue) public static string ObjToStringNew(this object thisValue)
{ {
@@ -110,7 +110,7 @@ namespace ThingsGateway.SqlSugar
return Convert.ToDateTime(thisValue.ToString()).ToString("yyyy-MM-dd"); return Convert.ToDateTime(thisValue.ToString()).ToString("yyyy-MM-dd");
} }
if (thisValue != null) return thisValue.ToString().Trim(); if (thisValue != null) return thisValue.ToString().Trim();
return ""; return string.Empty;
} }
public static string ObjToString(this object thisValue, string errorValue) public static string ObjToString(this object thisValue, string errorValue)

View File

@@ -57,7 +57,7 @@
public static string ObjToString(this object thisValue) public static string ObjToString(this object thisValue)
{ {
if (thisValue != null) return thisValue.ToString().Trim(); if (thisValue != null) return thisValue.ToString().Trim();
return ""; return string.Empty;
} }
public static string ObjToString(this object thisValue, string errorValue) public static string ObjToString(this object thisValue, string errorValue)

View File

@@ -893,42 +893,25 @@ namespace ThingsGateway.SqlSugar
return Guid.NewGuid() + ""; return Guid.NewGuid() + "";
} }
} }
static Type IAsyncStateMachineType = typeof(IAsyncStateMachine);
public static bool IsAsyncMethod(MethodBase method) public static bool IsAsyncMethod(MethodBase method)
{ {
if (method == null) if (method == null) return false;
{
return false; if (method.GetCustomAttribute<AsyncStateMachineAttribute>() != null)
} return true;
if (method.DeclaringType != null)
{ if (method.DeclaringType?.GetInterfaces().Contains(IAsyncStateMachineType) == true)
if (method.DeclaringType.GetInterfaces().Contains(typeof(IAsyncStateMachine))) return true;
{
return true; // 补救方案:有些 async 方法是动态生成的,名字惯例判断
}
}
var name = method.Name; var name = method.Name;
if (name.Contains("OutputAsyncCausalityEvents")) return name.EndsWith("ExecuteAsync") || name.Contains("OutputAsyncCausalityEvents") || name.Contains("OutputWaitEtwEvents");
{
return true;
}
if (name.Contains("OutputWaitEtwEvents"))
{
return true;
}
if (name.Contains("ExecuteAsync"))
{
return true;
}
//if (method?.DeclaringType?.FullName?.Contains("Furion.InternalApp")==true)
//{
// return false;
//}
Type attType = typeof(AsyncStateMachineAttribute);
var attrib = (AsyncStateMachineAttribute)method.GetCustomAttribute(attType);
return (attrib != null);
} }
public static StackTraceInfo GetStackTrace() public static StackTraceInfo GetStackTrace()
{ {

View File

@@ -29,7 +29,7 @@ namespace ThingsGateway.SqlSugar.TDengine
{ {
get get
{ {
return ""; return string.Empty;
} }
} }

View File

@@ -16,7 +16,7 @@
public static string ObjToStringNoTrim(this object thisValue) public static string ObjToStringNoTrim(this object thisValue)
{ {
if (thisValue != null) return thisValue.ToString(); if (thisValue != null) return thisValue.ToString();
return ""; return string.Empty;
} }
public static string ToLower(this string value, bool isLower) public static string ToLower(this string value, bool isLower)
{ {
@@ -78,7 +78,7 @@
public static string ObjToString(this object thisValue) public static string ObjToString(this object thisValue)
{ {
if (thisValue != null) return thisValue.ToString().Trim(); if (thisValue != null) return thisValue.ToString().Trim();
return ""; return string.Empty;
} }
public static string ObjToString(this object thisValue, string errorValue) public static string ObjToString(this object thisValue, string errorValue)

View File

@@ -1,8 +1,8 @@
<Project> <Project>
<PropertyGroup> <PropertyGroup>
<PluginVersion>10.7.55</PluginVersion> <PluginVersion>10.7.56</PluginVersion>
<ProPluginVersion>10.7.55</ProPluginVersion> <ProPluginVersion>10.7.56</ProPluginVersion>
<AuthenticationVersion>2.6.0</AuthenticationVersion> <AuthenticationVersion>2.6.0</AuthenticationVersion>
<NET8Version>8.0.17</NET8Version> <NET8Version>8.0.17</NET8Version>
<NET9Version>9.0.6</NET9Version> <NET9Version>9.0.6</NET9Version>

View File

@@ -23,6 +23,12 @@ public abstract class BusinessBaseWithCacheAlarmModel<VarModel, DevModel, AlarmM
protected ConcurrentQueue<CacheDBItem<AlarmModel>> _memoryAlarmModelQueue = new(); protected ConcurrentQueue<CacheDBItem<AlarmModel>> _memoryAlarmModelQueue = new();
private volatile bool LocalDBCacheAlarmModelInited; private volatile bool LocalDBCacheAlarmModelInited;
private CacheDB DBCacheAlarm;
protected internal override Task InitChannelAsync(IChannel? channel, CancellationToken cancellationToken)
{
DBCacheAlarm = LocalDBCacheAlarmModel();
return base.InitChannelAsync(channel, cancellationToken);
}
/// <summary> /// <summary>
/// 入缓存 /// 入缓存
@@ -161,10 +167,8 @@ public abstract class BusinessBaseWithCacheAlarmModel<VarModel, DevModel, AlarmM
{ {
while (!cancellationToken.IsCancellationRequested) while (!cancellationToken.IsCancellationRequested)
{ {
using var cache = LocalDBCacheAlarmModel();
//循环获取,固定读最大行数量,执行完成需删除行 //循环获取,固定读最大行数量,执行完成需删除行
var varList = await cache.DBProvider.Queryable<CacheDBItem<AlarmModel>>().Take(_businessPropertyWithCache.SplitSize).ToListAsync(cancellationToken).ConfigureAwait(false); var varList = await DBCacheAlarm.DBProvider.Queryable<CacheDBItem<AlarmModel>>().Take(_businessPropertyWithCache.SplitSize).ToListAsync(cancellationToken).ConfigureAwait(false);
if (varList.Count > 0) if (varList.Count > 0)
{ {
try try
@@ -175,7 +179,7 @@ public abstract class BusinessBaseWithCacheAlarmModel<VarModel, DevModel, AlarmM
if (result.IsSuccess) if (result.IsSuccess)
{ {
//删除缓存 //删除缓存
await cache.DBProvider.Deleteable<CacheDBItem<AlarmModel>>(varList).ExecuteCommandAsync(cancellationToken).ConfigureAwait(false); await DBCacheAlarm.DBProvider.Deleteable<CacheDBItem<AlarmModel>>(varList).ExecuteCommandAsync(cancellationToken).ConfigureAwait(false);
} }
else else
break; break;

View File

@@ -24,6 +24,14 @@ public abstract class BusinessBaseWithCacheDeviceModel<VarModel, DevModel> : Bus
private volatile bool LocalDBCacheDevModelInited; private volatile bool LocalDBCacheDevModelInited;
private CacheDB DBCacheDev;
protected internal override Task InitChannelAsync(IChannel? channel, CancellationToken cancellationToken)
{
DBCacheDev = LocalDBCacheDevModel();
return base.InitChannelAsync(channel, cancellationToken);
}
/// <summary> /// <summary>
/// 入缓存 /// 入缓存
/// </summary> /// </summary>
@@ -159,10 +167,9 @@ public abstract class BusinessBaseWithCacheDeviceModel<VarModel, DevModel> : Bus
{ {
while (!cancellationToken.IsCancellationRequested) while (!cancellationToken.IsCancellationRequested)
{ {
using var cache = LocalDBCacheDevModel();
//循环获取 //循环获取
var varList = await cache.DBProvider.Queryable<CacheDBItem<DevModel>>().Take(_businessPropertyWithCache.SplitSize).ToListAsync(cancellationToken).ConfigureAwait(false); var varList = await DBCacheDev.DBProvider.Queryable<CacheDBItem<DevModel>>().Take(_businessPropertyWithCache.SplitSize).ToListAsync(cancellationToken).ConfigureAwait(false);
if (varList.Count > 0) if (varList.Count > 0)
{ {
try try
@@ -173,7 +180,7 @@ public abstract class BusinessBaseWithCacheDeviceModel<VarModel, DevModel> : Bus
if (result.IsSuccess) if (result.IsSuccess)
{ {
//删除缓存 //删除缓存
await cache.DBProvider.Deleteable<CacheDBItem<DevModel>>(varList).ExecuteCommandAsync(cancellationToken).ConfigureAwait(false); await DBCacheDev.DBProvider.Deleteable<CacheDBItem<DevModel>>(varList).ExecuteCommandAsync(cancellationToken).ConfigureAwait(false);
} }
else else
break; break;

View File

@@ -25,6 +25,16 @@ public abstract class BusinessBaseWithCacheVariableModel<VarModel> : BusinessBas
protected volatile bool success = true; protected volatile bool success = true;
private volatile bool LocalDBCacheVarModelInited; private volatile bool LocalDBCacheVarModelInited;
private volatile bool LocalDBCacheVarModelsInited; private volatile bool LocalDBCacheVarModelsInited;
private CacheDB DBCacheVar;
private CacheDB DBCacheVars;
protected internal override Task InitChannelAsync(IChannel? channel, CancellationToken cancellationToken)
{
DBCacheVar = LocalDBCacheVarModel();
DBCacheVars = LocalDBCacheVarModels();
return base.InitChannelAsync(channel, cancellationToken);
}
protected sealed override BusinessPropertyBase _businessPropertyBase => _businessPropertyWithCache; protected sealed override BusinessPropertyBase _businessPropertyBase => _businessPropertyWithCache;
protected abstract BusinessPropertyWithCache _businessPropertyWithCache { get; } protected abstract BusinessPropertyWithCache _businessPropertyWithCache { get; }
@@ -264,8 +274,8 @@ public abstract class BusinessBaseWithCacheVariableModel<VarModel> : BusinessBas
while (!cancellationToken.IsCancellationRequested) while (!cancellationToken.IsCancellationRequested)
{ {
//循环获取 //循环获取
using var cache = LocalDBCacheVarModel();
var varList = await cache.DBProvider.Queryable<CacheDBItem<VarModel>>().Take(_businessPropertyWithCache.SplitSize).ToListAsync(cancellationToken).ConfigureAwait(false); var varList = await DBCacheVar.DBProvider.Queryable<CacheDBItem<VarModel>>().Take(_businessPropertyWithCache.SplitSize).ToListAsync(cancellationToken).ConfigureAwait(false);
if (varList.Count > 0) if (varList.Count > 0)
{ {
try try
@@ -276,7 +286,7 @@ public abstract class BusinessBaseWithCacheVariableModel<VarModel> : BusinessBas
if (result.IsSuccess) if (result.IsSuccess)
{ {
//删除缓存 //删除缓存
await cache.DBProvider.Deleteable<CacheDBItem<VarModel>>(varList).ExecuteCommandAsync(cancellationToken).ConfigureAwait(false); await DBCacheVar.DBProvider.Deleteable<CacheDBItem<VarModel>>(varList).ExecuteCommandAsync(cancellationToken).ConfigureAwait(false);
} }
else else
break; break;
@@ -325,8 +335,8 @@ public abstract class BusinessBaseWithCacheVariableModel<VarModel> : BusinessBas
while (!cancellationToken.IsCancellationRequested) while (!cancellationToken.IsCancellationRequested)
{ {
//循环获取 //循环获取
using var cache = LocalDBCacheVarModels();
var varList = await cache.DBProvider.Queryable<CacheDBItem<List<VarModel>>>().FirstAsync(cancellationToken).ConfigureAwait(false); var varList = await DBCacheVars.DBProvider.Queryable<CacheDBItem<List<VarModel>>>().FirstAsync(cancellationToken).ConfigureAwait(false);
if (varList?.Value?.Count > 0) if (varList?.Value?.Count > 0)
{ {
try try
@@ -337,7 +347,7 @@ public abstract class BusinessBaseWithCacheVariableModel<VarModel> : BusinessBas
if (result.IsSuccess) if (result.IsSuccess)
{ {
//删除缓存 //删除缓存
await cache.DBProvider.Deleteable<CacheDBItem<List<VarModel>>>(varList).ExecuteCommandAsync(cancellationToken).ConfigureAwait(false); await DBCacheVars.DBProvider.Deleteable<CacheDBItem<List<VarModel>>>(varList).ExecuteCommandAsync(cancellationToken).ConfigureAwait(false);
} }
else else
break; break;

View File

@@ -18,6 +18,7 @@ using System.Collections.Concurrent;
using ThingsGateway.Extension; using ThingsGateway.Extension;
using ThingsGateway.Extension.Generic; using ThingsGateway.Extension.Generic;
using ThingsGateway.NewLife.Json.Extension; using ThingsGateway.NewLife.Json.Extension;
using ThingsGateway.SqlSugar;
using TouchSocket.Core; using TouchSocket.Core;
@@ -249,12 +250,13 @@ internal sealed class RpcService : IRpcService
return new(results); return new(results);
} }
private SqlSugarClient _db = DbContext.Db.GetConnectionScopeWithAttr<RpcLog>().CopyNew(); // 创建一个新的数据库上下文实例
/// <summary> /// <summary>
/// 异步执行RPC日志插入操作的方法。 /// 异步执行RPC日志插入操作的方法。
/// </summary> /// </summary>
private async Task RpcLogInsertAsync() private async Task RpcLogInsertAsync()
{ {
var db = DbContext.Db.GetConnectionScopeWithAttr<RpcLog>().CopyNew(); // 创建一个新的数据库上下文实例
var appLifetime = App.RootServices!.GetService<IHostApplicationLifetime>()!; var appLifetime = App.RootServices!.GetService<IHostApplicationLifetime>()!;
while (!appLifetime.ApplicationStopping.IsCancellationRequested) while (!appLifetime.ApplicationStopping.IsCancellationRequested)
{ {
@@ -264,7 +266,7 @@ internal sealed class RpcService : IRpcService
if (data.Count > 0) if (data.Count > 0)
{ {
// 将数据插入到数据库中 // 将数据插入到数据库中
await db.InsertableWithAttr(data).ExecuteCommandAsync(appLifetime.ApplicationStopping).ConfigureAwait(false); await _db.InsertableWithAttr(data).ExecuteCommandAsync(appLifetime.ApplicationStopping).ConfigureAwait(false);
} }
} }
catch (Exception ex) catch (Exception ex)

View File

@@ -47,7 +47,7 @@ namespace ThingsGateway.Gateway.Razor
return (await expressionNode.ExecuteAsync(new NodeInput(){Value=a==null?a:JToken.Parse(a??string.Empty) },default).ConfigureAwait(false)).JToken?.ToString(); return (await expressionNode.ExecuteAsync(new NodeInput(){Value=a==null?a:JToken.Parse(a??string.Empty) },default).ConfigureAwait(false)).JToken?.ToString();
if(Node is IActuatorNode actuatorNode) if(Node is IActuatorNode actuatorNode)
return (await actuatorNode.ExecuteAsync(new NodeInput(){Value=a==null?a:JToken.Parse(a??string.Empty) },default).ConfigureAwait(false)).JToken?.ToString(); return (await actuatorNode.ExecuteAsync(new NodeInput(){Value=a==null?a:JToken.Parse(a??string.Empty) },default).ConfigureAwait(false)).JToken?.ToString();
return ""; return string.Empty;
}) }, }) },
{nameof(ScriptEdit.Script),Node.Text }, {nameof(ScriptEdit.Script),Node.Text },
{nameof(ScriptEdit.ScriptChanged),EventCallback.Factory.Create<string>(this, v => {nameof(ScriptEdit.ScriptChanged),EventCallback.Factory.Create<string>(this, v =>

View File

@@ -188,7 +188,7 @@ public struct PropertyID : ISerializable
return $"{Code}"; return $"{Code}";
} }
return ""; return string.Empty;
} }
private sealed class Names private sealed class Names

View File

@@ -14,6 +14,7 @@ using Mapster;
using ThingsGateway.Admin.Application; using ThingsGateway.Admin.Application;
using ThingsGateway.Foundation; using ThingsGateway.Foundation;
using ThingsGateway.NewLife;
using ThingsGateway.NewLife.Extension; using ThingsGateway.NewLife.Extension;
using ThingsGateway.Plugin.DB; using ThingsGateway.Plugin.DB;
using ThingsGateway.SqlSugar; using ThingsGateway.SqlSugar;
@@ -45,6 +46,13 @@ public partial class QuestDBProducer : BusinessBaseWithCacheIntervalVariableMode
public override VariablePropertyBase VariablePropertys => _variablePropertys; public override VariablePropertyBase VariablePropertys => _variablePropertys;
protected override BusinessPropertyWithCacheInterval _businessPropertyWithCacheInterval => _driverPropertys; protected override BusinessPropertyWithCacheInterval _businessPropertyWithCacheInterval => _driverPropertys;
private SqlSugarClient _db;
protected override void Dispose(bool disposing)
{
_db?.TryDispose();
base.Dispose(disposing);
}
public async Task<SqlSugarPagedList<IDBHistoryValue>> GetDBHistoryValuePagesAsync(DBHistoryValuePageInput input) public async Task<SqlSugarPagedList<IDBHistoryValue>> GetDBHistoryValuePagesAsync(DBHistoryValuePageInput input)
{ {
@@ -60,7 +68,7 @@ public partial class QuestDBProducer : BusinessBaseWithCacheIntervalVariableMode
protected override async Task InitChannelAsync(IChannel? channel, CancellationToken cancellationToken) protected override async Task InitChannelAsync(IChannel? channel, CancellationToken cancellationToken)
{ {
_db = BusinessDatabaseUtil.GetDb(_driverPropertys.DbType, _driverPropertys.BigTextConnectStr);
_config = new TypeAdapterConfig(); _config = new TypeAdapterConfig();
DateTime utcTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); DateTime utcTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
_config.ForType<VariableRuntime, QuestDBHistoryValue>() _config.ForType<VariableRuntime, QuestDBHistoryValue>()
@@ -153,20 +161,19 @@ public partial class QuestDBProducer : BusinessBaseWithCacheIntervalVariableMode
protected override async Task ProtectedStartAsync(CancellationToken cancellationToken) protected override async Task ProtectedStartAsync(CancellationToken cancellationToken)
{ {
var db = BusinessDatabaseUtil.GetDb(_driverPropertys.DbType, _driverPropertys.BigTextConnectStr); _db.DbMaintenance.CreateDatabase();
db.DbMaintenance.CreateDatabase();
//必须为间隔上传 //必须为间隔上传
if (!_driverPropertys.BigTextScriptHistoryTable.IsNullOrEmpty()) if (!_driverPropertys.BigTextScriptHistoryTable.IsNullOrEmpty())
{ {
DynamicSQLBase? hisModel = CSharpScriptEngineExtension.Do<DynamicSQLBase>(_driverPropertys.BigTextScriptHistoryTable); DynamicSQLBase? hisModel = CSharpScriptEngineExtension.Do<DynamicSQLBase>(_driverPropertys.BigTextScriptHistoryTable);
hisModel.Logger = LogMessage; hisModel.Logger = LogMessage;
await hisModel.DBInit(db, cancellationToken).ConfigureAwait(false); await hisModel.DBInit(_db, cancellationToken).ConfigureAwait(false);
} }
else else
{ {
db.CodeFirst.As<QuestDBHistoryValue>(_driverPropertys.TableName).InitTables(typeof(QuestDBHistoryValue)); _db.CodeFirst.As<QuestDBHistoryValue>(_driverPropertys.TableName).InitTables(typeof(QuestDBHistoryValue));
} }
await base.ProtectedStartAsync(cancellationToken).ConfigureAwait(false); await base.ProtectedStartAsync(cancellationToken).ConfigureAwait(false);

View File

@@ -105,14 +105,13 @@ public partial class QuestDBProducer : BusinessBaseWithCacheIntervalVariableMode
{ {
try try
{ {
var db = BusinessDatabaseUtil.GetDb(_driverPropertys.DbType, _driverPropertys.BigTextConnectStr); _db.Ado.CancellationToken = cancellationToken;
db.Ado.CancellationToken = cancellationToken;
if (!_driverPropertys.BigTextScriptHistoryTable.IsNullOrEmpty()) if (!_driverPropertys.BigTextScriptHistoryTable.IsNullOrEmpty())
{ {
var getDeviceModel = CSharpScriptEngineExtension.Do<DynamicSQLBase>(_driverPropertys.BigTextScriptHistoryTable); var getDeviceModel = CSharpScriptEngineExtension.Do<DynamicSQLBase>(_driverPropertys.BigTextScriptHistoryTable);
getDeviceModel.Logger = LogMessage; getDeviceModel.Logger = LogMessage;
await getDeviceModel.DBInsertable(db, dbInserts, cancellationToken).ConfigureAwait(false); await getDeviceModel.DBInsertable(_db, dbInserts, cancellationToken).ConfigureAwait(false);
} }
else else
@@ -120,7 +119,7 @@ public partial class QuestDBProducer : BusinessBaseWithCacheIntervalVariableMode
Stopwatch stopwatch = new(); Stopwatch stopwatch = new();
stopwatch.Start(); stopwatch.Start();
var result = await db.Insertable(dbInserts).AS(_driverPropertys.TableName).ExecuteCommandAsync(cancellationToken).ConfigureAwait(false);//不要加分表 var result = await _db.Insertable(dbInserts).AS(_driverPropertys.TableName).ExecuteCommandAsync(cancellationToken).ConfigureAwait(false);//不要加分表
stopwatch.Stop(); stopwatch.Stop();
//var result = await db.Insertable(dbInserts).SplitTable().ExecuteCommandAsync().ConfigureAwait(false); //var result = await db.Insertable(dbInserts).SplitTable().ExecuteCommandAsync().ConfigureAwait(false);

View File

@@ -15,6 +15,7 @@ using Mapster;
using ThingsGateway.Admin.Application; using ThingsGateway.Admin.Application;
using ThingsGateway.Debug; using ThingsGateway.Debug;
using ThingsGateway.Foundation; using ThingsGateway.Foundation;
using ThingsGateway.NewLife;
using ThingsGateway.NewLife.Extension; using ThingsGateway.NewLife.Extension;
using ThingsGateway.Plugin.DB; using ThingsGateway.Plugin.DB;
using ThingsGateway.SqlSugar; using ThingsGateway.SqlSugar;
@@ -46,7 +47,12 @@ public partial class SqlDBProducer : BusinessBaseWithCacheIntervalVariableModel<
public override VariablePropertyBase VariablePropertys => _variablePropertys; public override VariablePropertyBase VariablePropertys => _variablePropertys;
protected override BusinessPropertyWithCacheInterval _businessPropertyWithCacheInterval => _driverPropertys; protected override BusinessPropertyWithCacheInterval _businessPropertyWithCacheInterval => _driverPropertys;
private SqlSugarClient _db;
protected override void Dispose(bool disposing)
{
_db?.TryDispose();
base.Dispose(disposing);
}
public async Task<SqlSugarPagedList<IDBHistoryValue>> GetDBHistoryValuePagesAsync(DBHistoryValuePageInput input) public async Task<SqlSugarPagedList<IDBHistoryValue>> GetDBHistoryValuePagesAsync(DBHistoryValuePageInput input)
{ {
var data = await Query(input).ToPagedListAsync<SQLHistoryValue, IDBHistoryValue>(input.Current, input.Size).ConfigureAwait(false);//分页 var data = await Query(input).ToPagedListAsync<SQLHistoryValue, IDBHistoryValue>(input.Current, input.Size).ConfigureAwait(false);//分页
@@ -151,6 +157,8 @@ public partial class SqlDBProducer : BusinessBaseWithCacheIntervalVariableModel<
protected override async Task InitChannelAsync(IChannel? channel, CancellationToken cancellationToken) protected override async Task InitChannelAsync(IChannel? channel, CancellationToken cancellationToken)
{ {
_db = SqlDBBusinessDatabaseUtil.GetDb(_driverPropertys);
_config = new TypeAdapterConfig(); _config = new TypeAdapterConfig();
_config.ForType<VariableRuntime, SQLHistoryValue>() _config.ForType<VariableRuntime, SQLHistoryValue>()
//.Map(dest => dest.Id, (src) =>CommonUtils.GetSingleId()) //.Map(dest => dest.Id, (src) =>CommonUtils.GetSingleId())
@@ -173,11 +181,9 @@ public partial class SqlDBProducer : BusinessBaseWithCacheIntervalVariableModel<
_initRealData = false; _initRealData = false;
return base.AfterVariablesChangedAsync(cancellationToken); return base.AfterVariablesChangedAsync(cancellationToken);
} }
protected override async Task ProtectedStartAsync(CancellationToken cancellationToken) protected override async Task ProtectedStartAsync(CancellationToken cancellationToken)
{ {
var db = SqlDBBusinessDatabaseUtil.GetDb(_driverPropertys); _db.DbMaintenance.CreateDatabase();
db.DbMaintenance.CreateDatabase();
//必须为间隔上传 //必须为间隔上传
if (!_driverPropertys.BigTextScriptHistoryTable.IsNullOrEmpty()) if (!_driverPropertys.BigTextScriptHistoryTable.IsNullOrEmpty())
@@ -186,14 +192,14 @@ public partial class SqlDBProducer : BusinessBaseWithCacheIntervalVariableModel<
if (_driverPropertys.IsHistoryDB) if (_driverPropertys.IsHistoryDB)
{ {
await hisModel.DBInit(db, cancellationToken).ConfigureAwait(false); await hisModel.DBInit(_db, cancellationToken).ConfigureAwait(false);
} }
} }
else else
{ {
if (_driverPropertys.IsHistoryDB) if (_driverPropertys.IsHistoryDB)
db.CodeFirst.InitTables(typeof(SQLHistoryValue)); _db.CodeFirst.InitTables(typeof(SQLHistoryValue));
} }
if (!_driverPropertys.BigTextScriptRealTable.IsNullOrEmpty()) if (!_driverPropertys.BigTextScriptRealTable.IsNullOrEmpty())
{ {
@@ -201,14 +207,14 @@ public partial class SqlDBProducer : BusinessBaseWithCacheIntervalVariableModel<
if (_driverPropertys.IsReadDB) if (_driverPropertys.IsReadDB)
{ {
await realModel.DBInit(db, cancellationToken).ConfigureAwait(false); await realModel.DBInit(_db, cancellationToken).ConfigureAwait(false);
} }
} }
else else
{ {
if (_driverPropertys.IsReadDB) if (_driverPropertys.IsReadDB)
db.CodeFirst.As<SQLRealValue>(_driverPropertys.ReadDBTableName).InitTables<SQLRealValue>(); _db.CodeFirst.As<SQLRealValue>(_driverPropertys.ReadDBTableName).InitTables<SQLRealValue>();
} }
await base.ProtectedStartAsync(cancellationToken).ConfigureAwait(false); await base.ProtectedStartAsync(cancellationToken).ConfigureAwait(false);

View File

@@ -120,22 +120,21 @@ public partial class SqlDBProducer : BusinessBaseWithCacheIntervalVariableModel<
{ {
try try
{ {
var db = SqlDBBusinessDatabaseUtil.GetDb(_driverPropertys); _db.Ado.CancellationToken = cancellationToken;
db.Ado.CancellationToken = cancellationToken;
if (!_driverPropertys.BigTextScriptHistoryTable.IsNullOrEmpty()) if (!_driverPropertys.BigTextScriptHistoryTable.IsNullOrEmpty())
{ {
var getDeviceModel = CSharpScriptEngineExtension.Do<DynamicSQLBase>(_driverPropertys.BigTextScriptHistoryTable); var getDeviceModel = CSharpScriptEngineExtension.Do<DynamicSQLBase>(_driverPropertys.BigTextScriptHistoryTable);
getDeviceModel.Logger = LogMessage; getDeviceModel.Logger = LogMessage;
await getDeviceModel.DBInsertable(db, dbInserts, cancellationToken).ConfigureAwait(false); await getDeviceModel.DBInsertable(_db, dbInserts, cancellationToken).ConfigureAwait(false);
} }
else else
{ {
Stopwatch stopwatch = new(); Stopwatch stopwatch = new();
stopwatch.Start(); stopwatch.Start();
var result = await db.Fastest<SQLHistoryValue>().PageSize(50000).SplitTable().BulkCopyAsync(dbInserts).ConfigureAwait(false); var result = await _db.Fastest<SQLHistoryValue>().PageSize(50000).SplitTable().BulkCopyAsync(dbInserts).ConfigureAwait(false);
//var result = await db.Insertable(dbInserts).SplitTable().ExecuteCommandAsync().ConfigureAwait(false); //var result = await db.Insertable(dbInserts).SplitTable().ExecuteCommandAsync().ConfigureAwait(false);
stopwatch.Stop(); stopwatch.Stop();
if (result > 0) if (result > 0)
@@ -157,15 +156,14 @@ public partial class SqlDBProducer : BusinessBaseWithCacheIntervalVariableModel<
{ {
try try
{ {
var db = SqlDBBusinessDatabaseUtil.GetDb(_driverPropertys); _db.Ado.CancellationToken = cancellationToken;
db.Ado.CancellationToken = cancellationToken;
if (!_driverPropertys.BigTextScriptRealTable.IsNullOrEmpty()) if (!_driverPropertys.BigTextScriptRealTable.IsNullOrEmpty())
{ {
var getDeviceModel = CSharpScriptEngineExtension.Do<DynamicSQLBase>(_driverPropertys.BigTextScriptRealTable); var getDeviceModel = CSharpScriptEngineExtension.Do<DynamicSQLBase>(_driverPropertys.BigTextScriptRealTable);
getDeviceModel.Logger = LogMessage; getDeviceModel.Logger = LogMessage;
await getDeviceModel.DBInsertable(db, datas, cancellationToken).ConfigureAwait(false); await getDeviceModel.DBInsertable(_db, datas, cancellationToken).ConfigureAwait(false);
return OperResult.Success; return OperResult.Success;
} }
@@ -176,9 +174,9 @@ public partial class SqlDBProducer : BusinessBaseWithCacheIntervalVariableModel<
{ {
Stopwatch stopwatch = new(); Stopwatch stopwatch = new();
stopwatch.Start(); stopwatch.Start();
var ids = (await db.Queryable<SQLRealValue>().AS(_driverPropertys.ReadDBTableName).Select(a => a.Id).ToListAsync(cancellationToken).ConfigureAwait(false)).ToHashSet(); var ids = (await _db.Queryable<SQLRealValue>().AS(_driverPropertys.ReadDBTableName).Select(a => a.Id).ToListAsync(cancellationToken).ConfigureAwait(false)).ToHashSet();
var InsertData = IdVariableRuntimes.Where(a => !ids.Contains(a.Key)).Select(a => a.Value).Adapt<List<SQLRealValue>>(); var InsertData = IdVariableRuntimes.Where(a => !ids.Contains(a.Key)).Select(a => a.Value).Adapt<List<SQLRealValue>>();
var result = await db.Fastest<SQLRealValue>().AS(_driverPropertys.ReadDBTableName).PageSize(100000).BulkCopyAsync(InsertData).ConfigureAwait(false); var result = await _db.Fastest<SQLRealValue>().AS(_driverPropertys.ReadDBTableName).PageSize(100000).BulkCopyAsync(InsertData).ConfigureAwait(false);
_initRealData = true; _initRealData = true;
stopwatch.Stop(); stopwatch.Stop();
if (result > 0) if (result > 0)
@@ -192,7 +190,7 @@ public partial class SqlDBProducer : BusinessBaseWithCacheIntervalVariableModel<
Stopwatch stopwatch = new(); Stopwatch stopwatch = new();
stopwatch.Start(); stopwatch.Start();
var result = await db.Fastest<SQLRealValue>().AS(_driverPropertys.ReadDBTableName).PageSize(100000).BulkUpdateAsync(datas).ConfigureAwait(false); var result = await _db.Fastest<SQLRealValue>().AS(_driverPropertys.ReadDBTableName).PageSize(100000).BulkUpdateAsync(datas).ConfigureAwait(false);
stopwatch.Stop(); stopwatch.Stop();
if (result > 0) if (result > 0)

View File

@@ -15,6 +15,7 @@ using Mapster;
using ThingsGateway.Admin.Application; using ThingsGateway.Admin.Application;
using ThingsGateway.Extension.Generic; using ThingsGateway.Extension.Generic;
using ThingsGateway.Foundation; using ThingsGateway.Foundation;
using ThingsGateway.NewLife;
using ThingsGateway.SqlSugar; using ThingsGateway.SqlSugar;
using TouchSocket.Core; using TouchSocket.Core;
@@ -36,8 +37,13 @@ public partial class SqlHistoryAlarm : BusinessBaseWithCacheVariableModel<Histor
protected override BusinessPropertyWithCache _businessPropertyWithCache => _driverPropertys; protected override BusinessPropertyWithCache _businessPropertyWithCache => _driverPropertys;
private SqlSugarClient _db;
protected override async Task InitChannelAsync(IChannel? channel, CancellationToken cancellationToken) protected override async Task InitChannelAsync(IChannel? channel, CancellationToken cancellationToken)
{ {
_db = BusinessDatabaseUtil.GetDb(_driverPropertys.DbType, _driverPropertys.BigTextConnectStr);
_config.ForType<AlarmVariable, HistoryAlarm>().Map(dest => dest.Id, (src) => CommonUtils.GetSingleId()); _config.ForType<AlarmVariable, HistoryAlarm>().Map(dest => dest.Id, (src) => CommonUtils.GetSingleId());
GlobalData.AlarmChangedEvent -= AlarmWorker_OnAlarmChanged; GlobalData.AlarmChangedEvent -= AlarmWorker_OnAlarmChanged;
@@ -73,15 +79,15 @@ public partial class SqlHistoryAlarm : BusinessBaseWithCacheVariableModel<Histor
protected override void Dispose(bool disposing) protected override void Dispose(bool disposing)
{ {
_db?.TryDispose();
GlobalData.AlarmChangedEvent -= AlarmWorker_OnAlarmChanged; GlobalData.AlarmChangedEvent -= AlarmWorker_OnAlarmChanged;
base.Dispose(disposing); base.Dispose(disposing);
} }
protected override Task ProtectedStartAsync(CancellationToken cancellationToken) protected override Task ProtectedStartAsync(CancellationToken cancellationToken)
{ {
using var db = BusinessDatabaseUtil.GetDb(_driverPropertys.DbType, _driverPropertys.BigTextConnectStr); _db.DbMaintenance.CreateDatabase();
db.DbMaintenance.CreateDatabase(); _db.CodeFirst.As<HistoryAlarm>(_driverPropertys.TableName).InitTables<HistoryAlarm>();
db.CodeFirst.As<HistoryAlarm>(_driverPropertys.TableName).InitTables<HistoryAlarm>();
return base.ProtectedStartAsync(cancellationToken); return base.ProtectedStartAsync(cancellationToken);
} }

View File

@@ -60,17 +60,16 @@ public partial class SqlHistoryAlarm : BusinessBaseWithCacheVariableModel<Histor
{ {
try try
{ {
using var db = BusinessDatabaseUtil.GetDb(_driverPropertys.DbType, _driverPropertys.BigTextConnectStr);
int result = 0; int result = 0;
//.SplitTable() //.SplitTable()
Stopwatch stopwatch = new(); Stopwatch stopwatch = new();
stopwatch.Start(); stopwatch.Start();
if (db.CurrentConnectionConfig.DbType == SqlSugar.DbType.QuestDB) if (_db.CurrentConnectionConfig.DbType == SqlSugar.DbType.QuestDB)
result = await db.Insertable(dbInserts).AS(_driverPropertys.TableName).ExecuteCommandAsync(cancellationToken).ConfigureAwait(false);//不要加分表 result = await _db.Insertable(dbInserts).AS(_driverPropertys.TableName).ExecuteCommandAsync(cancellationToken).ConfigureAwait(false);//不要加分表
else else
result = await db.Fastest<HistoryAlarm>().AS(_driverPropertys.TableName).PageSize(50000).BulkCopyAsync(dbInserts).ConfigureAwait(false); result = await _db.Fastest<HistoryAlarm>().AS(_driverPropertys.TableName).PageSize(50000).BulkCopyAsync(dbInserts).ConfigureAwait(false);
stopwatch.Stop(); stopwatch.Stop();

View File

@@ -18,6 +18,7 @@ using System.Reflection;
using ThingsGateway.Admin.Application; using ThingsGateway.Admin.Application;
using ThingsGateway.Foundation; using ThingsGateway.Foundation;
using ThingsGateway.NewLife;
using ThingsGateway.NewLife.Extension; using ThingsGateway.NewLife.Extension;
using ThingsGateway.Plugin.DB; using ThingsGateway.Plugin.DB;
using ThingsGateway.SqlSugar; using ThingsGateway.SqlSugar;
@@ -58,7 +59,11 @@ public partial class TDengineDBProducer : BusinessBaseWithCacheIntervalVariableM
var data = await Query(input).ToPagedListAsync<TDengineDBHistoryValue, IDBHistoryValue>(input.Current, input.Size).ConfigureAwait(false);//分页 var data = await Query(input).ToPagedListAsync<TDengineDBHistoryValue, IDBHistoryValue>(input.Current, input.Size).ConfigureAwait(false);//分页
return data; return data;
} }
protected override void Dispose(bool disposing)
{
_db?.TryDispose();
base.Dispose(disposing);
}
public async Task<List<IDBHistoryValue>> GetDBHistoryValuesAsync(DBHistoryValuePageInput input) public async Task<List<IDBHistoryValue>> GetDBHistoryValuesAsync(DBHistoryValuePageInput input)
{ {
var data = await Query(input).ToListAsync().ConfigureAwait(false); var data = await Query(input).ToListAsync().ConfigureAwait(false);
@@ -67,6 +72,7 @@ public partial class TDengineDBProducer : BusinessBaseWithCacheIntervalVariableM
protected override async Task InitChannelAsync(IChannel? channel, CancellationToken cancellationToken) protected override async Task InitChannelAsync(IChannel? channel, CancellationToken cancellationToken)
{ {
InstanceFactory.RemoveCache(); InstanceFactory.RemoveCache();
_db = TDengineDBUtil.GetDb(_driverPropertys.DbType, _driverPropertys.BigTextConnectStr, _driverPropertys.TableNameLow);
List<Assembly> assemblies = new(); List<Assembly> assemblies = new();
foreach (var item in InstanceFactory.CustomAssemblies) foreach (var item in InstanceFactory.CustomAssemblies)
{ {
@@ -160,11 +166,11 @@ public partial class TDengineDBProducer : BusinessBaseWithCacheIntervalVariableM
} }
return ret; return ret;
} }
private SqlSugarClient _db;
protected override async Task ProtectedStartAsync(CancellationToken cancellationToken) protected override async Task ProtectedStartAsync(CancellationToken cancellationToken)
{ {
var db = TDengineDBUtil.GetDb(_driverPropertys.DbType, _driverPropertys.BigTextConnectStr, _driverPropertys.TableNameLow); _db.DbMaintenance.CreateDatabase();
db.DbMaintenance.CreateDatabase();
//必须为间隔上传 //必须为间隔上传
@@ -172,7 +178,7 @@ public partial class TDengineDBProducer : BusinessBaseWithCacheIntervalVariableM
{ {
var hisModel = CSharpScriptEngineExtension.Do<DynamicSQLBase>(_driverPropertys.BigTextScriptHistoryTable); var hisModel = CSharpScriptEngineExtension.Do<DynamicSQLBase>(_driverPropertys.BigTextScriptHistoryTable);
{ {
await hisModel.DBInit(db, cancellationToken).ConfigureAwait(false); await hisModel.DBInit(_db, cancellationToken).ConfigureAwait(false);
} }
} }
@@ -187,7 +193,7 @@ public partial class TDengineDBProducer : BusinessBaseWithCacheIntervalVariableM
`isonline` BOOL , `isonline` BOOL ,
`value` VARCHAR(255) ) TAGS(`devicename` VARCHAR(100) ,`name` VARCHAR(100)) `value` VARCHAR(255) ) TAGS(`devicename` VARCHAR(100) ,`name` VARCHAR(100))
"""; """;
await db.Ado.ExecuteCommandAsync(sql, default, cancellationToken: cancellationToken).ConfigureAwait(false); await _db.Ado.ExecuteCommandAsync(sql, default, cancellationToken: cancellationToken).ConfigureAwait(false);
} }
await base.ProtectedStartAsync(cancellationToken).ConfigureAwait(false); await base.ProtectedStartAsync(cancellationToken).ConfigureAwait(false);
} }

View File

@@ -107,14 +107,13 @@ public partial class TDengineDBProducer : BusinessBaseWithCacheIntervalVariableM
{ {
try try
{ {
var db = TDengineDBUtil.GetDb(_driverPropertys.DbType, _driverPropertys.BigTextConnectStr, _driverPropertys.TableNameLow); _db.Ado.CancellationToken = cancellationToken;
db.Ado.CancellationToken = cancellationToken;
if (!_driverPropertys.BigTextScriptHistoryTable.IsNullOrEmpty()) if (!_driverPropertys.BigTextScriptHistoryTable.IsNullOrEmpty())
{ {
var getDeviceModel = CSharpScriptEngineExtension.Do<DynamicSQLBase>(_driverPropertys.BigTextScriptHistoryTable); var getDeviceModel = CSharpScriptEngineExtension.Do<DynamicSQLBase>(_driverPropertys.BigTextScriptHistoryTable);
getDeviceModel.Logger = LogMessage; getDeviceModel.Logger = LogMessage;
await getDeviceModel.DBInsertable(db, dbInserts, cancellationToken).ConfigureAwait(false); await getDeviceModel.DBInsertable(_db, dbInserts, cancellationToken).ConfigureAwait(false);
} }
else else
@@ -149,7 +148,7 @@ public partial class TDengineDBProducer : BusinessBaseWithCacheIntervalVariableM
stringBuilder.Append(';'); stringBuilder.Append(';');
stringBuilder.AppendLine(); stringBuilder.AppendLine();
await db.Ado.ExecuteCommandAsync(stringBuilder.ToString(), default, cancellationToken: cancellationToken).ConfigureAwait(false); await _db.Ado.ExecuteCommandAsync(stringBuilder.ToString(), default, cancellationToken: cancellationToken).ConfigureAwait(false);
stopwatch.Stop(); stopwatch.Stop();
//var result = await db.Insertable(dbInserts).SplitTable().ExecuteCommandAsync().ConfigureAwait(false); //var result = await db.Insertable(dbInserts).SplitTable().ExecuteCommandAsync().ConfigureAwait(false);

View File

@@ -38,6 +38,9 @@
<!--打包复制--> <!--打包复制-->
<Import Project="targets\PluginPublish.targets" /> <Import Project="targets\PluginPublish.targets" />
<PropertyGroup> <PropertyGroup>
<GenerateDocumentationFile>false</GenerateDocumentationFile>
<TargetFrameworks>net8.0;net9.0;</TargetFrameworks> <TargetFrameworks>net8.0;net9.0;</TargetFrameworks>
<CustomTargetFramework>$(TargetFramework)</CustomTargetFramework> <CustomTargetFramework>$(TargetFramework)</CustomTargetFramework>
<OpenApiGenerateDocuments>false</OpenApiGenerateDocuments> <OpenApiGenerateDocuments>false</OpenApiGenerateDocuments>

View File

@@ -22,7 +22,7 @@
</ItemGroup> </ItemGroup>
<PropertyGroup> <PropertyGroup>
<RulesEngineApplicationFolder>$(TargetDir)SeedData\RulesEngine\</RulesEngineApplicationFolder> <RulesEngineApplicationFolder>$(TargetDir)SeedData\RulesEngine\</RulesEngineApplicationFolder>
<ManagementApplicationFolder>$(TargetDir)SeedData\SeedData\</ManagementApplicationFolder> <ManagementApplicationFolder>$(TargetDir)SeedData\Management\</ManagementApplicationFolder>
<GatewayApplicationFolder>$(TargetDir)SeedData\Gateway\</GatewayApplicationFolder> <GatewayApplicationFolder>$(TargetDir)SeedData\Gateway\</GatewayApplicationFolder>
</PropertyGroup> </PropertyGroup>
<RemoveDir Directories="$(RulesEngineApplicationFolder)" /> <RemoveDir Directories="$(RulesEngineApplicationFolder)" />
@@ -48,4 +48,8 @@
<!--Gateway--> <!--Gateway-->
</Project> </Project>

View File

@@ -16,4 +16,12 @@
</Target> </Target>
<Target Name="RemoveXmlDocs" AfterTargets="Build">
<ItemGroup>
<XmlFilesToDelete Include="$(OutputPath)*.xml" />
</ItemGroup>
<Delete Files="@(XmlFilesToDelete)" />
</Target>
</Project> </Project>

View File

@@ -10,7 +10,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "other", "other", "{0B748352
ProjectSection(SolutionItems) = preProject ProjectSection(SolutionItems) = preProject
.editorconfig = .editorconfig .editorconfig = .editorconfig
Directory.Build.props = Directory.Build.props Directory.Build.props = Directory.Build.props
..\git_pull.bat = ..\git_pull.bat
PluginVersion.props = PluginVersion.props PluginVersion.props = PluginVersion.props
Version.props = Version.props Version.props = Version.props
EndProjectSection EndProjectSection
@@ -319,8 +318,8 @@ Global
{AFC0BEE4-E682-BCED-F631-99707421015A} = {5948EA23-4B42-4C22-A266-2E0AE5FA575F} {AFC0BEE4-E682-BCED-F631-99707421015A} = {5948EA23-4B42-4C22-A266-2E0AE5FA575F}
EndGlobalSection EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {199B1B96-4F56-4828-9531-813BA02DB282}
RESX_NeutralResourcesLanguage = zh-Hans
RESX_Rules = {"EnabledRules":[]} RESX_Rules = {"EnabledRules":[]}
RESX_NeutralResourcesLanguage = zh-Hans
SolutionGuid = {199B1B96-4F56-4828-9531-813BA02DB282}
EndGlobalSection EndGlobalSection
EndGlobal EndGlobal

View File

@@ -1,6 +1,6 @@
<Project> <Project>
<PropertyGroup> <PropertyGroup>
<Version>10.7.55</Version> <Version>10.7.56</Version>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>