Skip to content

Commit

Permalink
Fix no check expires when get cache count in memory cache (#498)
Browse files Browse the repository at this point in the history
* fix: no check expires when get cache count in memory cache

* styles: format code #497

* feat: add test
  • Loading branch information
Memoyu committed Oct 13, 2023
1 parent 8f2c764 commit 151be2b
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 6 deletions.
12 changes: 6 additions & 6 deletions src/EasyCaching.InMemory/Internal/InMemoryCaching.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,8 @@ public void Clear(string prefix = "")
public int GetCount(string prefix = "")
{
return string.IsNullOrWhiteSpace(prefix)
? _memory.Count
: _memory.Count(x => x.Key.StartsWith(prefix, StringComparison.OrdinalIgnoreCase));
? _memory.Values.Where(x => x.ExpiresAt > SystemClock.UtcNow).Count()
: _memory.Values.Where(x => x.Key.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) && x.ExpiresAt > SystemClock.UtcNow).Count();
}

internal void RemoveExpiredKey(string key)
Expand Down Expand Up @@ -283,7 +283,7 @@ public int RemoveByPattern(string searchKey, SearchKeyPattern searchPattern)
public IEnumerable<string> GetAllKeys(string prefix)
{
return _memory.Values.Where(x => x.Key.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) && x.ExpiresAt > SystemClock.UtcNow)
.Select(x=> x.Key).ToList();
.Select(x => x.Key).ToList();
}

private static bool FilterByPattern(string key, string searchKey, SearchKeyPattern searchKeyPattern)
Expand Down Expand Up @@ -314,10 +314,10 @@ public IDictionary<string, CacheValue<T>> GetAll<T>(IEnumerable<string> keys)

public IDictionary<string, CacheValue<T>> GetAll<T>(string prefix = "")
{
var values = string.IsNullOrEmpty(prefix)
? _memory.Values.Where(x => x.ExpiresAt > SystemClock.UtcNow)
var values = string.IsNullOrEmpty(prefix)
? _memory.Values.Where(x => x.ExpiresAt > SystemClock.UtcNow)
: _memory.Values.Where(x => x.Key.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) && x.ExpiresAt > SystemClock.UtcNow);

return values.ToDictionary(k => k.Key, v => new CacheValue<T>(v.GetValue<T>(_options.EnableReadDeepClone), true));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,21 @@ public void Evicted_Event_Should_Trigger_When_GetExpiredItems()
_provider.Get<string>(key1);
System.Threading.Thread.Sleep(500);
}

[Fact]
public async void Issues497_GetCountAsync_Check_Expires_Test()
{
for (int i = 0; i < 9; i++)
{
await _provider.SetAsync(Guid.NewGuid().ToString(), $"value-{i}", TimeSpan.FromSeconds(5));
}

Assert.Equal(9, await _provider.GetCountAsync());

await Task.Delay(5000);

Assert.Equal(0, await _provider.GetCountAsync());
}
}

public class MemoryCachingProviderWithFactoryTest : BaseCachingProviderWithFactoryTest
Expand Down

0 comments on commit 151be2b

Please sign in to comment.