51 lines
1.4 KiB
C#
51 lines
1.4 KiB
C#
using System.Collections.Concurrent;
|
|
|
|
namespace MesETL.App.Cache;
|
|
|
|
public class MemoryCache : ICacher
|
|
{
|
|
private readonly ConcurrentDictionary<string, string> _stringCache = new();
|
|
private readonly ConcurrentDictionary<string, Dictionary<string, string>> _hashCache = new();
|
|
|
|
public static MemoryCache? Instance { get; private set; }
|
|
|
|
public MemoryCache()
|
|
{
|
|
Instance = this;
|
|
}
|
|
|
|
public Task<string?> GetStringAsync(string key)
|
|
{
|
|
return _stringCache.TryGetValue(key, out var value) ? Task.FromResult<string?>(value) : Task.FromResult((string?)null);
|
|
}
|
|
|
|
public Task SetStringAsync(string key, string value)
|
|
{
|
|
_stringCache[key] = value;
|
|
return Task.CompletedTask;
|
|
}
|
|
|
|
public Task<bool> ExistsAsync(string key)
|
|
{
|
|
return Task.FromResult(_stringCache.ContainsKey(key));
|
|
}
|
|
|
|
public Task SetHashAsync(string key, IReadOnlyDictionary<string, string> hash)
|
|
{
|
|
_hashCache[key] = hash.ToDictionary(x => x.Key, x => x.Value);
|
|
return Task.CompletedTask;
|
|
}
|
|
|
|
public Task<Dictionary<string, string>> GetHashAsync(string key)
|
|
{
|
|
return Task.FromResult(_hashCache[key]);
|
|
}
|
|
|
|
public void Delete(Func<string,bool> keySelector)
|
|
{
|
|
foreach (var k in _stringCache.Keys.Where(keySelector))
|
|
{
|
|
_stringCache.TryRemove(k, out _);
|
|
}
|
|
}
|
|
} |