roadie/RoadieLibrary/Caching/MemoryCacheManager.cs

114 lines
3.2 KiB
C#
Raw Normal View History

2018-11-02 21:04:49 +00:00
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
using System;
namespace Roadie.Library.Caching
{
public class MemoryCacheManager : CacheManagerBase
{
private MemoryCache _cache;
2018-11-04 20:33:37 +00:00
public MemoryCacheManager(ILogger logger, CachePolicy defaultPolicy)
2018-11-02 21:04:49 +00:00
: base(logger, defaultPolicy)
{
this._cache = new MemoryCache(new MemoryCacheOptions());
}
public override bool Add<TCacheValue>(string key, TCacheValue value)
{
using (var entry = _cache.CreateEntry(key))
{
_cache.Set(key, value);
return true;
}
}
2018-11-06 21:55:31 +00:00
public override bool Add<TCacheValue>(string key, TCacheValue value, string region)
{
using (var entry = _cache.CreateEntry(key))
{
_cache.Set(key, value, DateTimeOffset.MaxValue);
return true;
}
}
2018-11-02 21:04:49 +00:00
public override bool Add<TCacheValue>(string key, TCacheValue value, CachePolicy policy)
{
using (var entry = _cache.CreateEntry(key))
{
_cache.Set(key, value, new MemoryCacheEntryOptions
{
2018-11-04 20:33:37 +00:00
AbsoluteExpiration = DateTimeOffset.UtcNow.Add(policy.ExpiresAfter) // new DateTimeOffset(DateTime.UtcNow, policy.ExpiresAfter)
2018-11-02 21:04:49 +00:00
});
return true;
}
}
public override bool Add<TCacheValue>(string key, TCacheValue value, string region, CachePolicy policy)
{
return this.Add(key, value, policy);
}
public override void Clear()
{
this._cache = new MemoryCache(new MemoryCacheOptions());
}
public override void ClearRegion(string region)
{
this.Clear();
}
public override void Dispose()
{
2018-11-04 20:33:37 +00:00
// throw new NotImplementedException();
2018-11-02 21:04:49 +00:00
}
public override bool Exists<TOut>(string key)
{
return this.Get<TOut>(key) != null;
}
public override bool Exists<TOut>(string key, string region)
{
return this.Exists<TOut>(key);
}
public override TOut Get<TOut>(string key)
{
return this._cache.Get<TOut>(key);
}
public override TOut Get<TOut>(string key, string region)
{
return this.Get<TOut>(key);
}
public override TOut Get<TOut>(string key, Func<TOut> getItem, string region)
{
return this.Get<TOut>(key, getItem, region, this._defaultPolicy);
}
public override TOut Get<TOut>(string key, Func<TOut> getItem, string region, CachePolicy policy)
{
var r = this.Get<TOut>(key, region);
if (r == null)
{
r = getItem();
this.Add(key, r, region, policy);
}
return r;
}
public override bool Remove(string key)
{
this._cache.Remove(key);
return true;
}
public override bool Remove(string key, string region)
{
return this.Remove(key);
}
}
2018-11-04 20:33:37 +00:00
}