Files
ThingsGateway/framework/plugin/ThingsGateway.Plugin.SQLHisAlarm/SQLHisAlarm/SQLHisAlarmMed.cs
T
2023-11-19 22:19:05 +08:00

223 lines
7.7 KiB
C#

#region copyright
//------------------------------------------------------------------------------
// 此代码版权声明为全文件覆盖,如有原作者特别声明,会在下方手动补充
// 此代码版权(除特别声明外的代码)归作者本人Diego所有
// 源代码使用协议遵循本仓库的开源协议及附加协议
// Gitee源代码仓库:https://gitee.com/diego2098/ThingsGateway
// Github源代码仓库:https://github.com/kimdiego2098/ThingsGateway
// 使用文档:https://diego2098.gitee.io/thingsgateway-docs/
// QQ群:605534569
//------------------------------------------------------------------------------
#endregion
using Furion;
using Mapster;
using Microsoft.Extensions.Hosting;
using SqlSugar;
using System.Collections.Concurrent;
using System.ComponentModel.DataAnnotations;
using System.Reflection;
using ThingsGateway.Foundation.Extension.ConcurrentQueue;
using ThingsGateway.Foundation.Extension.Generic;
using Yitter.IdGenerator;
namespace ThingsGateway.Plugin.SQLHisAlarm;
/// <summary>
/// MqttClient
/// </summary>
public partial class SQLHisAlarm : UpLoadBaseWithCache
{
private const string devType = "dev";
private const string varType = "var";
private readonly SQLHisAlarmProperty _driverPropertys = new();
//private readonly SQLHisAlarmVariableProperty _variablePropertys = new();
private readonly EasyLock easyLock = new();
private ConcurrentQueue<HistoryAlarm> _alarmVariables = new();
private volatile bool success = true;
/// <summary>
/// Aop设置
/// </summary>
/// <param name="db"></param>
private static void AopSetting(SqlSugarClient db)
{
var config = db.CurrentConnectionConfig;
// 设置超时时间
db.Ado.CommandTimeOut = 30;
// 打印SQL语句
db.Aop.OnLogExecuting = (sql, pars) =>
{
//如果是开发环境就打印sql
if (App.HostEnvironment.IsDevelopment())
{
//if (sql.StartsWith("SELECT"))
//{
// Console.ForegroundColor = ConsoleColor.Green;
//}
//if (sql.StartsWith("UPDATE"))
//{
// Console.ForegroundColor = ConsoleColor.Yellow;
//}
//if (sql.StartsWith("INSERT"))
//{
// Console.ForegroundColor = ConsoleColor.Blue;
//}
//if (sql.StartsWith("DELETE"))
//{
// Console.ForegroundColor = ConsoleColor.Red;
//}
//WriteSqlLog(UtilMethods.GetSqlString(config.DbType, sql, pars));
//Console.ForegroundColor = ConsoleColor.White;
//Console.WriteLine();
}
};
//异常
db.Aop.OnError = (ex) =>
{
//如果是开发环境就打印日志
if (App.WebHostEnvironment.IsDevelopment())
{
if (ex.Parametres == null) return;
Console.ForegroundColor = ConsoleColor.Red;
var pars = db.Utilities.SerializeObject(((SugarParameter[])ex.Parametres).ToDictionary(it => it.ParameterName, it => it.Value));
WriteSqlLogError(UtilMethods.GetSqlString(config.DbType, ex.Sql, (SugarParameter[])ex.Parametres));
Console.ForegroundColor = ConsoleColor.White;
}
};
}
private static void WriteSqlLog(string msg)
{
Console.WriteLine("【Sql执行时间】:" + DateTimeExtensions.CurrentDateTime.ToDefaultDateTimeFormat());
Console.WriteLine("【Sql语句】:" + msg + Environment.NewLine);
}
private static void WriteSqlLogError(string msg)
{
Console.WriteLine("【Sql执行错误时间】:" + DateTimeExtensions.CurrentDateTime.ToDefaultDateTimeFormat());
Console.WriteLine("【Sql语句】:" + msg + Environment.NewLine);
}
private void AddCache(List<CacheItem> cacheItems, IEnumerable<HistoryAlarm> dev)
{
var data = dev.ChunkBetter(_driverPropertys.CacheItemCount);
foreach (var item in data)
{
var cacheItem = new CacheItem()
{
Id = YitIdHelper.NextId(),
Type = varType,
Value = item.ToJsonString(),
};
cacheItems.Add(cacheItem);
}
}
private void AddCache(IEnumerable<IEnumerable<HistoryAlarm>> devData, List<CacheItem> cacheItems)
{
try
{
foreach (var dev in devData)
{
AddCache(cacheItems, dev);
}
}
catch (Exception ex)
{
LogMessage.LogWarning(ex, "缓存失败");
}
}
/// <summary>
/// 添加变量队列,超限后会入缓存
/// </summary>
/// <param name="variableData"></param>
private void AddVariableQueue(HistoryAlarm variableData)
{
//检测队列长度,超限存入缓存数据库
if (_alarmVariables.Count > _uploadPropertyWithCache.QueueMaxCount)
{
List<HistoryAlarm> list = null;
lock (_alarmVariables)
{
if (_alarmVariables.Count > _uploadPropertyWithCache.QueueMaxCount)
{
list = _alarmVariables.ToListWithDequeue();
}
}
if (list != null)
{
var devData = list.ChunkBetter(_uploadPropertyWithCache.SplitSize);
var cacheItems = new List<CacheItem>();
AddCache(devData, cacheItems);
if (cacheItems.Count > 0)
CacheDb.Cache.Insert(cacheItems);
}
}
_alarmVariables.Enqueue(variableData);
}
/// <summary>
/// 获取数据库链接
/// </summary>
/// <returns></returns>
private SqlSugarClient GetDb()
{
var configureExternalServices = new ConfigureExternalServices
{
EntityService = (type, column) => // 修改列可空-1、带?问号 2、String类型若没有Required
{
if ((type.PropertyType.IsGenericType && type.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
|| (type.PropertyType == typeof(string) && type.GetCustomAttribute<RequiredAttribute>() == null))
column.IsNullable = true;
},
};
var sqlSugarClient = new SqlSugarClient(new ConnectionConfig()
{
ConnectionString = _driverPropertys.BigTextConnectStr,//连接字符串
DbType = _driverPropertys.DbType,//数据库类型
IsAutoCloseConnection = true, //不设成true要手动close
ConfigureExternalServices = configureExternalServices,
}
);
AopSetting(sqlSugarClient);//aop配置
return sqlSugarClient;
}
private async Task<OperResult> InserableAsync(SqlSugarClient db, List<HistoryAlarm> dbInserts, CancellationToken cancellationToken)
{
try
{
//.SplitTable()
var result = await db.Fastest<HistoryAlarm>().PageSize(50000).BulkCopyAsync(dbInserts);
//var result = await db.Insertable(dbInserts).SplitTable().ExecuteCommandAsync();
if (result > 0)
{
CurrentDevice.SetDeviceStatus(DateTimeExtensions.CurrentDateTime, 0);
LogMessage.Trace($"{FoundationConst.LogMessageHeader}主题:{nameof(HistoryAlarm)}");
}
return OperResult.CreateSuccessResult();
}
catch (Exception ex)
{
CurrentDevice.SetDeviceStatus(DateTimeExtensions.CurrentDateTime, 999);
return new(ex);
}
}
}