Gossage dans API

This commit is contained in:
MarcEricMartel
2022-10-27 09:37:13 -07:00
parent 04c7d68a44
commit 83331a4a08
10 changed files with 213 additions and 39 deletions

View File

@@ -8,6 +8,7 @@ namespace GrossesMitainesAPI.Services {
private readonly ILogger<DatabaseCacheService> _logger;
private Product[] _cache = new Product[1];
private Dictionary<uint, uint> _hits = new();
private bool _ok = false, _needUpd = true;
private PeriodicTimer _timer = new PeriodicTimer(TimeSpan.FromSeconds(10));
@@ -20,11 +21,14 @@ namespace GrossesMitainesAPI.Services {
}
private async void UpdateJob() {
while (await _timer.WaitForNextTickAsync())
if (_needUpd) {
while (await _timer.WaitForNextTickAsync()) {
if (_needUpd) {
_ok = UpdateCache();
_needUpd = !_ok;
}
}
if (_hits.Count > 0 && _ok)
UpdateMetrics();
}
}
private bool UpdateCache() {
try {
@@ -42,10 +46,47 @@ namespace GrossesMitainesAPI.Services {
}
return true;
}
private bool UpdateMetrics() {
try {
Dictionary<uint, uint> hits;
lock (_hits) {
hits = new(_hits);
_hits.Clear();
}
List<uint> ids = hits.Keys.ToList();
using (var scope = _contextFactory.CreateScope()) {
var db = scope.ServiceProvider.GetRequiredService<InventoryContext>();
List<Product> lst = db.Products.Where(x => ids.Contains((uint)x.Id)).ToList();
foreach (var x in hits) {
//Product prod = lst.First(x => x.Id == x.Id);
lst.First(x => x.Id == x.Id).Hits += x.Value;
// prod.Hits = prod.Hits + x.Value;
// db.Products.Update(prod);
}
db.UpdateRange(lst);
db.SaveChanges();
}
} catch (Exception e) {
_logger.LogError(e, "Erreur de mise à jour de cache.");
return false;
}
return true;
}
public bool isOk() { return _ok; }
public void askForRefresh() { _needUpd = true; }
public void addHit(uint id) {
lock (_hits) {
if (_hits.ContainsKey(id))
_hits[id] = _hits[id] + 1;
else _hits[id] = 1;
}
}
public Product[]? GetCacheCopy() {
if (!_ok) return null;
if (!_ok)
return null;
Product[] copy;
try {
@@ -59,9 +100,10 @@ namespace GrossesMitainesAPI.Services {
}
return copy;
}
public IQueryable<Product> queryCache() {
if (!_ok) return null;
public IQueryable<Product> queryCache() {
if (!_ok)
return null;
try {
return _cache.AsQueryable();
} catch (Exception e) {