54 lines
1.8 KiB
C#
54 lines
1.8 KiB
C#
using AS1024.GeoFeed.Core.Interfaces;
|
|
using Microsoft.Extensions.Caching.Memory;
|
|
using Microsoft.Extensions.Hosting;
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
namespace AS1024.GeoFeed.Core.GeoFeedPreloader
|
|
{
|
|
public class PreLoadGeoFeed : IHostedService
|
|
{
|
|
private readonly ILogger<PreLoadGeoFeed> logger;
|
|
private readonly IGeoFeedProvider provider;
|
|
private readonly IMemoryCache memoryCache;
|
|
private readonly IHostEnvironment environment;
|
|
private const string GeoFeedCacheKey = "GeoFeedData";
|
|
|
|
public PreLoadGeoFeed(ILogger<PreLoadGeoFeed> logger,
|
|
IGeoFeedProvider provider,
|
|
IMemoryCache memoryCache,
|
|
IHostEnvironment environment)
|
|
{
|
|
this.logger = logger;
|
|
this.provider = provider;
|
|
this.memoryCache = memoryCache;
|
|
this.environment = environment;
|
|
}
|
|
|
|
async Task IHostedService.StartAsync(CancellationToken cancellationToken)
|
|
{
|
|
try
|
|
{
|
|
if (environment.IsProduction())
|
|
await StartPreLoad();
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
logger.LogWarning($"Failed to preload, exception settings below:\n{ex}");
|
|
}
|
|
}
|
|
|
|
private async Task StartPreLoad()
|
|
{
|
|
logger.LogInformation("Preloading GeoFeed data in memory...");
|
|
List<Models.IPGeoFeed> feed = await provider.GetGeoFeedData();
|
|
MemoryCacheEntryOptions cacheEntryOptions = new MemoryCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromMinutes(45));
|
|
memoryCache.Set(GeoFeedCacheKey, feed, cacheEntryOptions);
|
|
}
|
|
|
|
Task IHostedService.StopAsync(CancellationToken cancellationToken)
|
|
{
|
|
return Task.CompletedTask;
|
|
}
|
|
}
|
|
}
|