Update metodi WASM Server

This commit is contained in:
Samuele Locatelli
2022-07-12 17:07:56 +02:00
parent 4bfba522ce
commit 77f06c465e
7 changed files with 144 additions and 55 deletions
+38 -34
View File
@@ -1,26 +1,18 @@
using Microsoft.AspNetCore.Mvc;
using MP.Data.Conf;
using MP.Data.DatabaseModels;
using MP.WASM.Mon.Data;
using MP.WASM.Mon.Server.Data;
using Newtonsoft.Json;
using NLog;
using StackExchange.Redis;
namespace MP.WASM.Mon.Server.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class MSEController : ControllerBase, IDisposable
public class MSEController : ControllerBase //, IDisposable
{
#region Public Constructors
/// <summary>
/// Dataservice x accesso DB
/// </summary>
protected MpDataService _DataService { get; set; }
/// <summary>
/// Avvio controller dei dati MSE
/// </summary>
@@ -31,15 +23,6 @@ namespace MP.WASM.Mon.Server.Controllers
Log.Trace("Avviata classe MSEController");
}
/// <summary>
/// Dispone delle risorse quando non necessarie
/// </summary>
public void Dispose()
{
_DataService.Dispose();
Log.Trace("Dispose classe MSEController");
}
#endregion Public Constructors
#region Public Properties
@@ -53,12 +36,26 @@ namespace MP.WASM.Mon.Server.Controllers
#region Public Methods
[HttpGet("checkAlive")]
public Task<string> checkAlive()
{
Log.Trace("Check Alive");
//string answ = (DateTime.Now.Second % 3 == 0) ? "KO": "OK";
return Task.FromResult(JsonConvert.SerializeObject("OK"));
}
[HttpGet("getConfig")]
public Task<List<ConfigModel>> ConfigGetAll()
{
return _DataService.ConfigGetAll();
}
[HttpGet("getAllTagConf")]
public Task<Dictionary<string, List<TagData>>> getAllTags()
{
return _DataService.getAllTags();
}
/// <summary>
/// restituisce il valore da REDIS associato al tag richeisto
/// </summary>
@@ -76,35 +73,42 @@ namespace MP.WASM.Mon.Server.Controllers
return _DataService.MacchineGetAll();
}
[HttpGet("getAllTagConf")]
public Task<Dictionary<string, List<TagData>>> getAllTags()
{
return _DataService.getAllTags();
}
/// <summary>
/// Metodo principale x ricevere tutte i dati MSE di tutti gli impianti
/// </summary>
/// <returns></returns>
[HttpGet()]
public Task<List<MappaStatoExpl>> MseGetAll()
public async Task<List<MappaStatoExpl>> MseGetAll()
{
return _DataService.MseGetAll();
return await _DataService.MseGetAll();
}
#endregion Public Methods
#region Protected Properties
/// <summary>
/// Dataservice x accesso DB
/// </summary>
protected MpDataService _DataService { get; set; }
#endregion Protected Properties
#if fase
/// <summary>
/// Dispone delle risorse quando non necessarie
/// </summary>
public void Dispose()
{
_DataService.Dispose();
Log.Trace("Dispose classe MSEController");
}
#endif
#region Private Fields
private static NLog.Logger Log = LogManager.GetCurrentClassLogger();
#endregion Private Fields
#region Private Methods
#endregion Private Methods
}
}
@@ -0,0 +1,12 @@
namespace MP.WASM.Mon.Server.Controllers
{
public class MessageService
{
public static DateTime lastRead { get; set; }
public MessageService()
{
lastRead = DateTime.MinValue;
}
}
}
+82 -19
View File
@@ -1,33 +1,28 @@
using MP.Data.Conf;
using MP.Data.DatabaseModels;
using MP.WASM.Mon.Server.Controllers;
using Newtonsoft.Json;
using NLog;
using StackExchange.Redis;
using System.Diagnostics;
using System.Text;
namespace MP.WASM.Mon.Data
namespace MP.WASM.Mon.Server.Data
{
public class MpDataService : IDisposable
{
#region Public Constructors
private int fastRefreshSec = 2;
public MpDataService(IConfiguration configuration, ILogger<MpDataService> logger)
public MpDataService(IConfiguration configuration, ILogger<MpDataService> logger, IConnectionMultiplexer redConn, MessageService MServ)
{
_logger = logger;
_configuration = configuration;
_MServ = MServ;
// setup compoenti REDIS
//this.redisConn = redConn;
this.redisConn = ConnectionMultiplexer.Connect(_configuration.GetConnectionString("Redis"));
this.redisDb = this.redisConn.GetDatabase();
//// setup canali pub/sub
//actLogPipe = new MessagePipe(redisConn, Constants.ACT_LOG_M_QUEUE);
//getConfValInt("MSE_cacheDuration", ref fastRefreshSec);
// conf DB
string connStr = _configuration.GetConnectionString("Mp.Mon");
@@ -39,11 +34,11 @@ namespace MP.WASM.Mon.Data
{
dbController = new MP.Data.Controllers.MpMonController(configuration);
StringBuilder sb = new StringBuilder();
sb.AppendLine($"DbController OK");
//sb.AppendLine($"CST: {dbController.CustomersCount()} | CNT: {dbController.CountersCount()} | BSK: {dbController.BasketsCount()} | NGT: {dbController.NegotiationsCount()} | DOC: {dbController.DocsCount()} | ITM: {dbController.ItemsCount()} | RES: {dbController.ResourcesCount()}");
sb.AppendLine($"MpDataService: DbController OK");
_logger.LogInformation(sb.ToString());
}
// setup parametri opzionali
setupConf();
// setup conf IOB da dizionario
tryLoadIobTags();
}
@@ -72,6 +67,7 @@ namespace MP.WASM.Mon.Data
{
// Clear database controller
dbController.Dispose();
_logger.LogInformation("MpDataService disposed!");
}
/// <summary>
@@ -107,9 +103,16 @@ namespace MP.WASM.Mon.Data
public async Task<List<MappaStatoExpl>> MseGetAll()
{
List<MappaStatoExpl> result = new List<MappaStatoExpl>();
// se lettura in corso... attendo 10..50ms...
if (DateTime.Now.Subtract(MessageService.lastRead).TotalMilliseconds < 100)
{
Random rnd = new Random();
await Task.Delay(rnd.Next(10, 50));
}
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
List<MappaStatoExpl> result = new List<MappaStatoExpl>();
// cerco in redis...
var rawData = await redisDb.StringGetAsync(redisMseKey);
if (!string.IsNullOrEmpty(rawData))
@@ -117,40 +120,89 @@ namespace MP.WASM.Mon.Data
result = JsonConvert.DeserializeObject<List<MappaStatoExpl>>(rawData);
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Trace($"Read from REDIS: {ts.TotalMilliseconds}ms");
Log.Trace($"REDIS Read: {ts.TotalMilliseconds:N2}ms");
}
else
{
result = await Task.FromResult(dbController.MseGetAll());
// serializzp e salvo...
rawData = JsonConvert.SerializeObject(result);
await redisDb.StringSetAsync(redisMseKey, rawData, TimeSpan.FromSeconds(2));
await redisDb.StringSetAsync(redisMseKey, rawData, TimeSpan.FromSeconds(fastRefreshSec));
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
Log.Trace($"Read from DB: {ts.TotalMilliseconds}ms");
Log.Trace($"DB Read: {ts.TotalMilliseconds:N2}ms");
}
if (result == null)
{
result = new List<MappaStatoExpl>();
}
MessageService.lastRead = DateTime.Now;
return result;
}
#endregion Public Methods
#region Protected Methods
/// <summary>
/// Recupera il valore e se trovato aggiorna
/// </summary>
/// <param name="chiave">Valore da cercare</param>
/// <param name="varObj">String in cui salvare il valore se trovato</param>
/// <returns></returns>
protected bool getConfVal(string chiave, ref string varObj)
{
bool answ = false;
if (CurrConfig != null && CurrConfig.Count > 0)
{
// sistemo i parametri opzionali...
ConfigModel? risultato = CurrConfig.FirstOrDefault(x => x.Chiave == chiave);
if (risultato != null)
{
varObj = risultato.Valore;
answ = !string.IsNullOrEmpty(risultato.Valore);
}
}
return answ;
}
/// <summary>
/// Recupera il valore e se trovato aggiorna
/// </summary>
/// <param name="chiave">Valore da cercare</param>
/// <param name="varObj">Int in cui salvare il valore se trovato</param>
/// <returns></returns>
protected bool getConfValInt(string chiave, ref int varObj)
{
bool answ = false;
if (CurrConfig != null && CurrConfig.Count > 0)
{
// sistemo i parametri opzionali...
ConfigModel? risultato = CurrConfig.FirstOrDefault(x => x.Chiave == chiave);
if (risultato != null)
{
answ = int.TryParse(risultato.Valore, out varObj);
}
}
return answ;
}
#endregion Protected Methods
#region Private Fields
private static IConfiguration _configuration = null!;
private static ILogger<MpDataService> _logger = null!;
private static NLog.Logger Log = LogManager.GetCurrentClassLogger();
private List<ConfigModel>? CurrConfig = null;
private int fastRefreshSec = 2;
private static MessageService _MServ = null!;
/// <summary>
/// Oggetto per connessione a REDIS
/// </summary>
private ConnectionMultiplexer redisConn = null!;
//ISubscriber sub = redis.GetSubscriber();
/// <summary>
/// Oggetto DB redis da impiegare x chiamate R/W
/// </summary>
@@ -162,6 +214,17 @@ namespace MP.WASM.Mon.Data
#region Private Methods
private void setupConf()
{
CurrConfig = dbController.ConfigGetAll();
if (CurrConfig != null && CurrConfig.Count > 0)
{
// sistemo i parametri opzionali...
getConfValInt("MSE_cacheDuration", ref fastRefreshSec);
Log.Info($"Effettuato setup parametri | MSE_cacheDuration: {fastRefreshSec}");
}
}
/// <summary>
/// Prova a caricare da file la conf degli IOB se presente
/// </summary>
@@ -25,6 +25,12 @@
<ProjectReference Include="..\Client\MP.WASM.Mon.Client.csproj" />
</ItemGroup>
<ItemGroup>
<None Update="logs\.placeholder">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
<ProjectExtensions><VisualStudio><UserProperties properties_4launchsettings_1json__JsonSchema="" /></VisualStudio></ProjectExtensions>
+1 -1
View File
@@ -41,6 +41,6 @@
-->
<logger name="*" minlevel="Trace" writeTo="consoleTarget" />
<!--<logger name="Microsoft.*" maxlevel="Info" final="true" />-->
<logger name="*" minlevel="Info" writeTo="fileTarget" />
<logger name="*" minlevel="Trace" writeTo="fileTarget" />
</rules>
</nlog>
+4 -1
View File
@@ -1,5 +1,6 @@
using Microsoft.AspNetCore.ResponseCompression;
using MP.WASM.Mon.Data;
using MP.WASM.Mon.Server.Controllers;
using MP.WASM.Mon.Server.Data;
using StackExchange.Redis;
var builder = WebApplication.CreateBuilder(args);
@@ -21,6 +22,8 @@ var redisMultiplexer = ConnectionMultiplexer.Connect(connStringRedis);
// aggiunta oggetti Singleton
builder.Services.AddSingleton<IConnectionMultiplexer>(redisMultiplexer);
builder.Services.AddSingleton<MpDataService>();
builder.Services.AddSingleton<MessageService>();
//builder.Services.AddScoped<MpDataService>();
var app = builder.Build();
+1
View File
@@ -0,0 +1 @@