Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(memory): support evicted event hook(#294) #414

Merged
merged 1 commit into from
Nov 6, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions src/EasyCaching.InMemory/Internal/IInMemoryCaching.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,5 +24,17 @@ public interface IInMemoryCaching
bool Replace<T>(string key, T value, TimeSpan? expiresIn = null);
void Clear(string prefix = "");
TimeSpan GetExpiration(string key);

event EventHandler<EvictedEventArgs> Evicted;
}

public class EvictedEventArgs : EventArgs
{
public EvictedEventArgs(string key )
{
this.Key = key;
}

public string Key { get; private set; }
}
}
33 changes: 21 additions & 12 deletions src/EasyCaching.InMemory/Internal/InMemoryCaching.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ public class InMemoryCaching : IInMemoryCaching
private long _cacheSize = 0L;
private const string _UPTOLIMIT_KEY = "inter_up_to_limit_key";

public event EventHandler<EvictedEventArgs> Evicted;

public InMemoryCaching(string name, InMemoryCachingOptions optionsAccessor)
{
ArgumentCheck.NotNull(optionsAccessor, nameof(optionsAccessor));
Expand All @@ -32,7 +34,7 @@ public InMemoryCaching(string name, InMemoryCachingOptions optionsAccessor)
public void Clear(string prefix = "")
{
if (string.IsNullOrWhiteSpace(prefix))
{
{
_memory.Clear();

if (_options.SizeLimit.HasValue)
Expand All @@ -53,9 +55,13 @@ public int GetCount(string prefix = "")

internal void RemoveExpiredKey(string key)
{
bool flag = _memory.TryRemove(key, out _);
if (_options.SizeLimit.HasValue && flag)
Interlocked.Decrement(ref _cacheSize);
if (_memory.TryRemove(key, out _))
{
Evicted?.Invoke(this, new EvictedEventArgs(key));

if (_options.SizeLimit.HasValue)
Interlocked.Decrement(ref _cacheSize);
}
}

public CacheValue<T> Get<T>(string key)
Expand Down Expand Up @@ -189,7 +195,7 @@ private bool SetInternal(CacheEntry entry, bool addOnly = false)

_memory.AddOrUpdate(deep.Key, deep, (k, cacheEntry) => deep);

if(_options.SizeLimit.HasValue)
if (_options.SizeLimit.HasValue)
Interlocked.Increment(ref _cacheSize);
}
}
Expand Down Expand Up @@ -239,7 +245,7 @@ public int RemoveAll(IEnumerable<string> keys = null)
continue;

if (_memory.TryRemove(key, out _))
{
{
removed++;
if (_options.SizeLimit.HasValue)
Interlocked.Decrement(ref _cacheSize);
Expand All @@ -254,7 +260,7 @@ public bool Remove(string key)
bool flag = _memory.TryRemove(key, out _);

if (_options.SizeLimit.HasValue && !key.Equals(_UPTOLIMIT_KEY) && flag)
{
{
Interlocked.Decrement(ref _cacheSize);
}

Expand All @@ -270,10 +276,10 @@ public int RemoveByPrefix(string prefix)
public int RemoveByPattern(string searchKey, SearchKeyPattern searchPattern)
{
var keysToRemove = _memory.Keys.Where(x => FilterByPattern(x, searchKey, searchPattern)).ToList();

return RemoveAll(keysToRemove);
}

private static bool FilterByPattern(string key, string searchKey, SearchKeyPattern searchKeyPattern)
{
switch (searchKeyPattern)
Expand Down Expand Up @@ -336,7 +342,10 @@ private void ScanForExpiredItems(InMemoryCaching cache)
var now = SystemClock.UtcNow;
foreach (var entry in cache._memory.Values.Where(x => x.ExpiresAt < now))
{
cache.Remove(entry.Key);
if (cache.Remove(entry.Key))
{
Evicted?.Invoke(this, new EvictedEventArgs(entry.Key));
}
}
}

Expand Down Expand Up @@ -403,7 +412,7 @@ internal object Value
public T GetValue<T>(bool isDeepClone = true)
{
object val = Value;

var t = typeof(T);

if (t == TypeHelper.BoolType || t == TypeHelper.StringType || t == TypeHelper.CharType || t == TypeHelper.DateTimeType || t.IsNumeric())
Expand All @@ -412,7 +421,7 @@ public T GetValue<T>(bool isDeepClone = true)
if (t == TypeHelper.NullableBoolType || t == TypeHelper.NullableCharType || t == TypeHelper.NullableDateTimeType || t.IsNullableNumeric())
return val == null ? default(T) : (T)Convert.ChangeType(val, Nullable.GetUnderlyingType(t));

return isDeepClone
return isDeepClone
? DeepClonerGenerator.CloneObject<T>((T)val)
: (T)val;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,43 @@ public void GetDatabase_Should_Succeed()
Assert.NotNull(db);
Assert.IsType<InMemoryCaching>(db);
}

[Fact]
public void Evicted_Event_Should_Trigger_When_StartScanForExpiredItems()
{
var key1 = "Evicted-111";
var key2 = "Evicted-112";

var db = (IInMemoryCaching)_provider.Database;

db.Evicted += (s,e) =>
{
Assert.Equal(key1, e.Key);
};

_provider.Set(key1, "111", TimeSpan.FromMilliseconds(500));
_provider.Set(key2, "112", TimeSpan.FromMilliseconds(6000));

System.Threading.Thread.Sleep(1000);
}

[Fact]
public void Evicted_Event_Should_Trigger_When_GetExpiredItems()
{
var key1 = "Evicted-211";

var db = (IInMemoryCaching)_provider.Database;

db.Evicted += (s, e) =>
{
Assert.Equal(key1, e.Key);
};

_provider.Set(key1, "211", TimeSpan.FromMilliseconds(500));
System.Threading.Thread.Sleep(1000);
_provider.Get<string>(key1);
System.Threading.Thread.Sleep(500);
}
}

public class MemoryCachingProviderWithFactoryTest : BaseCachingProviderWithFactoryTest
Expand Down