Load cache during in first call (#158)

* Load cache during in first call
This commit is contained in:
Pravakar Garnayak 2019-04-29 15:47:39 -07:00 коммит произвёл GitHub
Родитель d7e98f270a
Коммит 06c123c88e
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
2 изменённых файлов: 31 добавлений и 48 удалений

Просмотреть файл

@ -10,22 +10,21 @@ using System.Threading.Tasks;
namespace ServerlessLibrary
{
public interface ICacheService {
public interface ICacheService
{
IList<LibraryItemWithStats> GetCachedItems();
}
//https://stackoverflow.com/questions/44723017/in-memory-caching-with-auto-regeneration-on-asp-net-core
public class CacheService:ICacheService
public class CacheService : ICacheService
{
protected readonly IMemoryCache _cache;
private IHostingEnvironment _env;
private readonly ILibraryStore libraryStore;
private readonly ILogger logger;
public CacheService(IMemoryCache cache, IHostingEnvironment env, ILibraryStore libraryStore, ILogger<CacheService> logger)
public CacheService(IMemoryCache cache, ILibraryStore libraryStore, ILogger<CacheService> logger)
{
this._cache = cache;
this._env = env;
this.libraryStore = libraryStore;
this.logger = logger;
InitTimer();
@ -41,13 +40,32 @@ namespace ServerlessLibrary
public Task LoadingTask = Task.CompletedTask;
public Timer Timer { get; set; }
public bool LoadingBusy = false;
private bool isCacheLoadedOnce = false;
public IList<LibraryItemWithStats> GetCachedItems() {
public IList<LibraryItemWithStats> GetCachedItems()
{
// Make a blocking call to load cache on first time call.
if (!isCacheLoadedOnce)
{
try
{
IList<LibraryItemWithStats> items = this.ConstructCache().Result;
_cache.Set(ServerlessLibrarySettings.CACHE_ENTRY, new LibraryItemsResult() { Result = items, IsBusy = false });
}
catch (Exception ex)
{
this.logger.LogError(ex, "Failed to load cache in first call");
}
}
isCacheLoadedOnce = true;
return _cache.Get<LibraryItemsResult>(ServerlessLibrarySettings.CACHE_ENTRY).Result;
}
private async void TimerTickAsync(object state)
{
if (LoadingBusy) return;
if (!isCacheLoadedOnce || LoadingBusy) return;
try
{
LoadingBusy = true;
@ -70,7 +88,7 @@ namespace ServerlessLibrary
var items = await ConstructCache();
_cache.Set<LibraryItemsResult>(ServerlessLibrarySettings.CACHE_ENTRY, new LibraryItemsResult() { Result = items, IsBusy = false });
}
catch(Exception ex)
catch (Exception ex)
{
this.logger.LogError(ex, "Failed to load cache");
}
@ -79,8 +97,8 @@ namespace ServerlessLibrary
{
IList<LibraryItem> libraryItems;
IList<LibraryItemWithStats> libraryItemsWithStats = new List<LibraryItemWithStats>();
libraryItems = await this.libraryStore.GetAllItems();
var stats = await StorageHelper.getSLItemRecordsAsync();
libraryItems = await this.libraryStore.GetAllItems();
var stats = await StorageHelper.getSLItemRecordsAsync();
foreach (var storeItem in libraryItems)
{
var item = storeItem.ConvertTo<LibraryItemWithStats>();
@ -95,9 +113,10 @@ namespace ServerlessLibrary
}
}
public class LibraryItemsResult {
public class LibraryItemsResult
{
public IList<LibraryItemWithStats> Result { get; set; }
public bool IsBusy{ get; set; }
public bool IsBusy { get; set; }
}
}

Просмотреть файл

@ -1,36 +0,0 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Newtonsoft.Json;
using ServerlessLibrary.Models;
namespace ServerlessLibrary
{
/// <summary>
/// File library store. This storewill be useful for dev environement as well as untill cosmos db is onboarded
/// </summary>
public class FileLibraryStore : ILibraryStore
{
private IHostingEnvironment _env;
public FileLibraryStore(IHostingEnvironment env)
{
_env = env;
}
public Task Add(LibraryItem libraryItem)
{
throw new NotImplementedException();
}
public async Task<IList<LibraryItem>> GetAllItems()
{
var webRoot = _env.WebRootPath;
var file = System.IO.Path.Combine(webRoot, "items.json");
var fileContent = JsonConvert.DeserializeObject<List<LibraryItem>>(await System.IO.File.ReadAllTextAsync(file));
return fileContent;
}
}
}