using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Options; using MP.Core.Objects; using Newtonsoft.Json; using NLog; using StackExchange.Redis; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MP.Data.Services { /// /// Classe di partenza x costruzione servizi di accesso dati + cache /// public class BaseServ { #region Public Constructors public BaseServ(IConfiguration configuration) { _configuration = configuration; // setup compoenti REDIS redisConn = ConnectionMultiplexer.Connect(_configuration.GetConnectionString("Redis")); redisDb = redisConn.GetDatabase(); // json serializer... FIX errore loop circolare https://www.ryadel.com/en/jsonserializationexception-self-referencing-loop-detected-error-fix-entity-framework-asp-net-core/ JSSettings = new JsonSerializerSettings() { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }; // recupero conf speciali MpIoNS = _configuration.GetValue("ServerConf:MpIoNS"); } #endregion Public Constructors #region Public Methods /// /// Recupero info IOB x TAB (da info registrate IOB-WIN--> MP-IO) /// /// /// public IOB_data IobInfo(string IdxMacchina) { string source = "DB"; Stopwatch sw = new Stopwatch(); sw.Start(); IOB_data? result = new IOB_data(); // cerco in redis... string currKey = RedHashMpIO($"hM2IOB:{IdxMacchina}"); RedisValue rawData = redisDb.StringGet(currKey); //if (!string.IsNullOrEmpty($"{rawData}")) if (rawData.HasValue) { result = JsonConvert.DeserializeObject($"{rawData}"); source = "REDIS"; } else { Log.Error($"Errore: non trovato valore valido in REDIS | key: {currKey}"); Log.Info($"REDIS | conf: {redisConn.Configuration}"); Log.Info($" --> Valore trovato:{Environment.NewLine}{rawData}"); } if (result == null) { result = new IOB_data(); Log.Debug($"Init valore default | IdxMacchina: {IdxMacchina}"); } sw.Stop(); Log.Debug($"IobInfo per {IdxMacchina} | {source} | {sw.Elapsed.TotalMilliseconds}ms"); return result; } /// /// Recupero info Machine-IOB x TAB (da info registrate IOB-WIN --> MP-IO) /// /// /// public Dictionary MachIobConf(string IdxMacchina) { string source = "NA"; Stopwatch sw = new Stopwatch(); sw.Start(); Dictionary result = new Dictionary(); // cerco in redis... string currKey = RedHashMpIO($"IOB:{IdxMacchina}:MachIobConf"); try { result = redisDb .HashGetAll(currKey) .ToDictionary(x => $"{x.Name}", x => $"{x.Value}"); source = "REDIS"; } catch (Exception exc) { Log.Error($"Errore in MachIobConf{Environment.NewLine}{exc}"); } if (result == null) { result = new Dictionary(); Log.Debug($"Init valore default MachIobConf | IdxMacchina: {IdxMacchina}"); } sw.Stop(); Log.Debug($"MachIobConf per {IdxMacchina} | {source} | {sw.Elapsed.TotalMilliseconds}ms"); return result; } /// /// Recupero Conf Yaml Machine-IOB /// /// /// public string MachIobYamlConf(string IdxMacchina) { string source = "NA"; Stopwatch sw = new Stopwatch(); sw.Start(); string result = ""; // cerco in redis... string currKey = RedHashMpIO($"IOB:{IdxMacchina}:ConfYaml"); try { result = redisDb.StringGet(currKey); source = "REDIS"; } catch (Exception exc) { Log.Error($"Errore in MachIobYamlConf{Environment.NewLine}{exc}"); } if (result == null) { result = ""; Log.Debug($"Init valore default MachIobYamlConf | IdxMacchina: {IdxMacchina}"); } sw.Stop(); Log.Debug($"MachIobYamlConf per {IdxMacchina} | {source} | {sw.Elapsed.TotalMilliseconds}ms"); return result; } #endregion Public Methods #region Protected Fields protected static IConfiguration _configuration = null!; protected JsonSerializerSettings? JSSettings; protected string MpIoNS = ""; /// /// Oggetto per connessione a REDIS /// protected ConnectionMultiplexer redisConn = null!; //ISubscriber sub = redis.GetSubscriber(); /// /// Oggetto DB redis da impiegare x chiamate R/W /// protected IDatabase redisDb = null!; #endregion Protected Fields #region Protected Properties /// /// Durata cache breve (1 min circa + perturbazione percentuale +/-10%) /// protected TimeSpan FastCache { get => TimeSpan.FromSeconds(cacheTtlShort * rnd.Next(900, 1100) / 1000); } /// /// Durata cache lunga (+ perturbazione percentuale +/-10%) /// protected TimeSpan LongCache { get => TimeSpan.FromSeconds(cacheTtlLong * rnd.Next(900, 1100) / 1000); } /// /// Durata cache MOLTO breve (10 sec circa + perturbazione percentuale +/-10%) /// protected TimeSpan UltraFastCache { get => TimeSpan.FromSeconds(cacheTtlShort / 6 * rnd.Next(900, 1100) / 1000); } /// /// Durata cache MOLTO lunga (+ perturbazione percentuale +/-10%) /// protected TimeSpan UltraLongCache { get => TimeSpan.FromSeconds(cacheTtlLong * 10 * rnd.Next(900, 1100) / 1000); } #endregion Protected Properties #region Protected Methods protected string RedHashMpIO(string keyName) { string result = keyName; try { result = $"{MpIoNS}:{keyName}".Replace("\\", "_"); } catch (Exception exc) { Log.Error($"Errore in RedHashMpIO{Environment.NewLine}{exc}"); } return result; } #endregion Protected Methods #region Private Fields private static Logger Log = LogManager.GetCurrentClassLogger(); /// /// Durata cache lunga IN SECONDI /// private int cacheTtlLong = 60 * 5; /// /// Durata cache breve IN SECONDI /// private int cacheTtlShort = 60 * 1; private Random rnd = new Random(); #endregion Private Fields } }