48 lines
1.5 KiB
C#
48 lines
1.5 KiB
C#
using Microsoft.Extensions.Caching.Distributed;
|
|
using System;
|
|
using System.Collections.Concurrent;
|
|
using System.Linq;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace Netmash.Extensions.Caching.Services
|
|
{
|
|
internal class CacheService : ICacheService
|
|
{
|
|
private readonly IDistributedCache _cache;
|
|
private static readonly ConcurrentDictionary<string, string> _keys = new ConcurrentDictionary<string, string>();
|
|
|
|
const int expirationTimeFromNow = 24;
|
|
|
|
public CacheService(IDistributedCache cache)
|
|
{
|
|
_cache = cache;
|
|
}
|
|
|
|
public async Task<T> GetAsync<T>(string key, CancellationToken token = default(CancellationToken)) where T : class
|
|
{
|
|
var result = await _cache.GetAsync<T>(key, token);
|
|
return result;
|
|
}
|
|
|
|
public async Task SetApplicationDataAsync<T>(string key, T value, CancellationToken token = default(CancellationToken)) where T : class
|
|
{
|
|
_keys.TryAdd(key, string.Empty);
|
|
await _cache.SetAsync<T>(key, value, new DistributedCacheEntryOptions() { AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(expirationTimeFromNow) }, token);
|
|
}
|
|
|
|
public void Reset()
|
|
{
|
|
lock (_keys)
|
|
{
|
|
var list = _keys.Keys.ToList();
|
|
foreach (var s in list)
|
|
{
|
|
_cache.Remove(s);
|
|
}
|
|
_keys.Clear();
|
|
}
|
|
}
|
|
}
|
|
}
|