From 6607b46df92c5ef7b15645e1ecd3fa5b6934491a Mon Sep 17 00:00:00 2001 From: "e.nanvakenari" Date: Mon, 25 Nov 2024 12:48:38 +0330 Subject: [PATCH] Refactor: Change Manager to Generic methods --- CacheBuilder.cs | 27 ++++--- CacheManager.csproj.user | 9 +++ .../EasyCacheManagerTests.cs | 10 +-- .../EasyCacheManagerLoadTest.cs | 12 ++-- CacheManagerUnitTest/EasyCacheManagerTests.cs | 72 +++++++++---------- CacheSource/ApiCacheSourceWithGet.cs | 9 ++- CacheSource/DbCacheSourceWithGet.cs | 14 ++-- CacheSource/ICacheSourceWithGet.cs | 7 +- CacheSource/ICacheSourceWithGetWithClear.cs | 5 +- CacheSource/ICacheSourceWithGetWithSet.cs | 7 +- .../ICacheSourceWithGetWithSetAndClear.cs | 5 +- CacheSource/MemoryCacheSource.cs | 11 ++- CacheSource/RedisCacheSource.cs | 12 ++-- EasyCacheManager.cs | 28 ++++---- IEasyCacheManager.cs | 8 +-- README.md | 2 +- 16 files changed, 121 insertions(+), 117 deletions(-) create mode 100644 CacheManager.csproj.user diff --git a/CacheBuilder.cs b/CacheBuilder.cs index 49e8119..48bc501 100644 --- a/CacheBuilder.cs +++ b/CacheBuilder.cs @@ -1,4 +1,4 @@ -using CacheManager.CacheSource; +using CacheManager.CacheSource; using CacheManager.Config; namespace CacheManager; @@ -6,19 +6,18 @@ namespace CacheManager; /// /// Simple cache builder /// -/// EasyCacheManager -public class CacheBuilder +public class CacheBuilder { - private readonly List> _cacheSources = []; + private readonly List _cacheSources = []; /// /// Add Memory Cache /// /// Config /// CacheBuilder - public CacheBuilder AddMemory(MemoryConfig memoryConfig) + public CacheBuilder AddMemory(MemoryConfig memoryConfig) { - _cacheSources.Add(new MemoryCacheSource(memoryConfig, 1)); + _cacheSources.Add(new MemoryCacheSource(memoryConfig, 1)); return this; } @@ -27,9 +26,9 @@ public CacheBuilder AddMemory(MemoryConfig memoryConfig) /// /// Config /// CacheBuilder - public CacheBuilder AddRedis(RedisConfig redisConfig) + public CacheBuilder AddRedis(RedisConfig redisConfig) { - _cacheSources.Add(new RedisCacheSource(redisConfig, 2)); + _cacheSources.Add(new RedisCacheSource(redisConfig, 2)); return this; } @@ -38,9 +37,9 @@ public CacheBuilder AddRedis(RedisConfig redisConfig) /// /// Config /// CacheBuilder - public CacheBuilder AddDb(DbConfig dbConfig) + public CacheBuilder AddDb(DbConfig dbConfig) { - _cacheSources.Add(new DbCacheSourceWithGet(dbConfig, 3)); + _cacheSources.Add(new DbCacheSourceWithGet(dbConfig, 3)); return this; } @@ -49,9 +48,9 @@ public CacheBuilder AddDb(DbConfig dbConfig) /// /// Config /// CacheBuilder - public CacheBuilder AddApi(ApiConfig apiConfig) + public CacheBuilder AddApi(ApiConfig apiConfig) { - _cacheSources.Add(new ApiCacheSourceWithGet(apiConfig, 4)); + _cacheSources.Add(new ApiCacheSourceWithGet(apiConfig, 4)); return this; } @@ -60,7 +59,7 @@ public CacheBuilder AddApi(ApiConfig apiConfig) /// /// Your custom source /// CacheBuilder - public CacheBuilder AddCustom(ICacheSourceWithGet sourceWithGet) + public CacheBuilder AddCustom(ICacheSourceWithGet sourceWithGet) { _cacheSources.Add(sourceWithGet); return this; @@ -71,5 +70,5 @@ public CacheBuilder AddCustom(ICacheSourceWithGet sourceWithGet) /// /// Config /// EasyCacheManager - public EasyCacheManager Build(LockConfig lockConfig) => new(_cacheSources, lockConfig); + public EasyCacheManager Build(LockConfig lockConfig) => new(_cacheSources, lockConfig); } diff --git a/CacheManager.csproj.user b/CacheManager.csproj.user new file mode 100644 index 0000000..2b94d27 --- /dev/null +++ b/CacheManager.csproj.user @@ -0,0 +1,9 @@ + + + + + + Designer + + + \ No newline at end of file diff --git a/CacheManagerIntegrationTest/EasyCacheManagerTests.cs b/CacheManagerIntegrationTest/EasyCacheManagerTests.cs index 697daf7..87a9b87 100644 --- a/CacheManagerIntegrationTest/EasyCacheManagerTests.cs +++ b/CacheManagerIntegrationTest/EasyCacheManagerTests.cs @@ -16,7 +16,7 @@ public class EasyCacheManagerTests : IAsyncLifetime private RedisContainer _redisContainer = null!; private IConnectionMultiplexer _redisConnection = null!; private SqlConnection _sqlConnection = null!; - private EasyCacheManager _easyCacheManager = null!; + private EasyCacheManager _easyCacheManager = null!; public async Task InitializeAsync() { @@ -81,7 +81,7 @@ public async Task InitializeAsync() await _sqlConnection.ExecuteAsync(StaticData.QueryToCreateTable).ConfigureAwait(false); // Initialize Cache Manager with all sources - _easyCacheManager = new CacheBuilder() + _easyCacheManager = new CacheBuilder() .AddApi(new ApiConfig { Url = StaticData.Api }) .AddRedis(new RedisConfig { ConnectionString = redisConnectionString }) .AddDb(new DbConfig { ConnectionString = sqlConnectionString, Query = StaticData.QueryToSelect }) @@ -117,7 +117,7 @@ public async Task GetAsync_ShouldReturnData_FromDbAndSaveToMemoryAndRedis() _ = await _sqlConnection.ExecuteAsync(StaticData.QueryToInsert).ConfigureAwait(true); // Act - var result = await _easyCacheManager.GetAsync(StaticData.Key).ConfigureAwait(true); + var result = await _easyCacheManager.GetAsync(StaticData.Key).ConfigureAwait(true); // Assert Assert.NotNull(result); @@ -138,7 +138,7 @@ public async Task GetAsync_ShouldReturnData_FromApiAndSaveToMemoryAndRedis() .RespondWithJson(StaticData.Value); // Act - var result = await _easyCacheManager.GetAsync(StaticData.Key).ConfigureAwait(true); + var result = await _easyCacheManager.GetAsync(StaticData.Key).ConfigureAwait(true); // Assert Assert.NotNull(result); @@ -153,7 +153,7 @@ public async Task SetAsync_ShouldStoreData_InAllCacheSources() // Act await _easyCacheManager.SetAsync(StaticData.Key, StaticData.Value).ConfigureAwait(true); - var resultFromMemory = await _easyCacheManager.GetAsync(StaticData.Key).ConfigureAwait(true); + var resultFromMemory = await _easyCacheManager.GetAsync(StaticData.Key).ConfigureAwait(true); // Assert Assert.Equal(StaticData.Value, resultFromMemory); diff --git a/CacheManagerLoadTest/EasyCacheManagerLoadTest.cs b/CacheManagerLoadTest/EasyCacheManagerLoadTest.cs index d8a5fbc..aff5ad8 100644 --- a/CacheManagerLoadTest/EasyCacheManagerLoadTest.cs +++ b/CacheManagerLoadTest/EasyCacheManagerLoadTest.cs @@ -17,7 +17,7 @@ public class EasyCacheManagerLoadTest : IAsyncLifetime private RedisContainer _redisContainer = null!; private IConnectionMultiplexer _redisConnection = null!; private SqlConnection _sqlConnection = null!; - private EasyCacheManager _easyCacheManager = null!; + private EasyCacheManager _easyCacheManager = null!; public async Task InitializeAsync() { @@ -82,7 +82,7 @@ public async Task InitializeAsync() _ = await _sqlConnection.ExecuteAsync(StaticData.QueryToCreateTable).ConfigureAwait(false); // Initialize Cache Manager with all sources - _easyCacheManager = new CacheBuilder() + _easyCacheManager = new CacheBuilder() .AddApi(new ApiConfig { Url = StaticData.Api }) .AddRedis(new RedisConfig { ConnectionString = redisConnectionString }) .AddDb(new DbConfig { ConnectionString = sqlConnectionString, Query = StaticData.QueryToSelect }) @@ -124,7 +124,7 @@ public async Task LoadTest_GetAndSet_AllShouldBeValid() await _easyCacheManager.SetAsync(randomKey, randomKey).ConfigureAwait(true); - var response = await _easyCacheManager.GetAsync(randomKey).ConfigureAwait(true); + var response = await _easyCacheManager.GetAsync(randomKey).ConfigureAwait(true); if (response != randomKey) { @@ -157,7 +157,7 @@ public async Task LoadTest_GetFromApi_AllShouldBeValid() .WithVerb(HttpMethod.Get) .RespondWithJson(randomKey); - var response = await _easyCacheManager.GetAsync(randomKey).ConfigureAwait(true); + var response = await _easyCacheManager.GetAsync(randomKey).ConfigureAwait(true); if (response != randomKey) { @@ -191,7 +191,7 @@ public async Task LoadTest_GetFromApiJust50Percent_AllShouldBeValid() .WithVerb(HttpMethod.Get) .RespondWithJson(randomKey); - var response = await _easyCacheManager.GetAsync(randomKey).ConfigureAwait(true); + var response = await _easyCacheManager.GetAsync(randomKey).ConfigureAwait(true); if (response != randomKey) { @@ -216,7 +216,7 @@ public async Task LoadTest_GetFromApiJust50Percent_AllShouldBeValid() .WithVerb(HttpMethod.Get) .RespondWithJson(null); - var response = await _easyCacheManager.GetAsync(randomKey).ConfigureAwait(true); + var response = await _easyCacheManager.GetAsync(randomKey).ConfigureAwait(true); if (response != randomKey) { diff --git a/CacheManagerUnitTest/EasyCacheManagerTests.cs b/CacheManagerUnitTest/EasyCacheManagerTests.cs index 4013ba9..e8ecca6 100644 --- a/CacheManagerUnitTest/EasyCacheManagerTests.cs +++ b/CacheManagerUnitTest/EasyCacheManagerTests.cs @@ -25,19 +25,19 @@ public async Task SetAsync_ShouldClearAndSetCacheOnAllSources() const string Key = StaticData.Key; const string Value = StaticData.Key; - var cacheSourceWithSet1 = new Mock>(); + var cacheSourceWithSet1 = new Mock(); _ = cacheSourceWithSet1.Setup(x => x.Priority).Returns(1); - var cacheSourceWithSet2 = new Mock>(); + var cacheSourceWithSet2 = new Mock(); _ = cacheSourceWithSet2.Setup(x => x.Priority).Returns(2); - var cacheSourceWithClear1 = new Mock>(); + var cacheSourceWithClear1 = new Mock(); _ = cacheSourceWithClear1.Setup(x => x.Priority).Returns(3); - var cacheSourceWithClear2 = new Mock>(); + var cacheSourceWithClear2 = new Mock(); _ = cacheSourceWithClear2.Setup(x => x.Priority).Returns(4); - var cacheSources = new List> { cacheSourceWithSet1.Object, cacheSourceWithSet2.Object, cacheSourceWithClear1.Object, cacheSourceWithClear2.Object }; + var cacheSources = new List { cacheSourceWithSet1.Object, cacheSourceWithSet2.Object, cacheSourceWithClear1.Object, cacheSourceWithClear2.Object }; - var cacheManager = new EasyCacheManager(cacheSources, _lockConfig); + var cacheManager = new EasyCacheManager(cacheSources, _lockConfig); // Act await cacheManager.SetAsync(Key, Value).ConfigureAwait(true); @@ -54,19 +54,19 @@ public async Task GetAsync_ShouldRetrieveFromCacheAndSetInHigherPrioritySources( const string Key = StaticData.Key; const string Value = StaticData.Key; - var cacheSource1 = new Mock>(); + var cacheSource1 = new Mock(); _ = cacheSource1.Setup(x => x.Priority).Returns(2); - _ = cacheSource1.Setup(x => x.GetAsync(It.IsAny())).ReturnsAsync(Value); + _ = cacheSource1.Setup(x => x.GetAsync(It.IsAny())).ReturnsAsync(Value); - var cacheSource2 = new Mock>(); + var cacheSource2 = new Mock(); _ = cacheSource2.Setup(x => x.Priority).Returns(1); - _ = cacheSource2.Setup(x => x.GetAsync(It.IsAny())).ReturnsAsync((string)null!); + _ = cacheSource2.Setup(x => x.GetAsync(It.IsAny())).ReturnsAsync((string)null!); - var cacheSources = new List> { cacheSource1.Object, cacheSource2.Object }; - var cacheManager = new EasyCacheManager(cacheSources, _lockConfig); + var cacheSources = new List { cacheSource1.Object, cacheSource2.Object }; + var cacheManager = new EasyCacheManager(cacheSources, _lockConfig); // Act - var result = await cacheManager.GetAsync(Key).ConfigureAwait(true); + var result = await cacheManager.GetAsync(Key).ConfigureAwait(true); // Assert Assert.Equal(Value, result); @@ -77,33 +77,33 @@ public async Task GetAsync_ShouldRetrieveFromCacheAndSetInHigherPrioritySources( public void Constructor_ShouldThrowException_WhenCacheSourcesIsNull() { // Act & Assert - _ = Assert.Throws(() => new EasyCacheManager(null!, _lockConfig)); + _ = Assert.Throws(() => new EasyCacheManager(null!, _lockConfig)); } [Fact] public void Constructor_ShouldThrowException_WhenLockConfigIsNull() { // Arrange - var cacheSource = new Mock>().Object; - var cacheSources = new List> { cacheSource }; + var cacheSource = new Mock().Object; + var cacheSources = new List { cacheSource }; // Act & Assert - _ = Assert.Throws(() => new EasyCacheManager(cacheSources, null!)); + _ = Assert.Throws(() => new EasyCacheManager(cacheSources, null!)); } [Fact] public void Constructor_ShouldThrowException_WhenDuplicatePrioritiesExist() { // Arrange - var cacheSource1 = new Mock>(); + var cacheSource1 = new Mock(); _ = cacheSource1.Setup(x => x.Priority).Returns(1); - var cacheSource2 = new Mock>(); + var cacheSource2 = new Mock(); _ = cacheSource2.Setup(x => x.Priority).Returns(1); - var cacheSources = new List> { cacheSource1.Object, cacheSource2.Object }; + var cacheSources = new List { cacheSource1.Object, cacheSource2.Object }; // Act & Assert - var exception = Assert.Throws(() => new EasyCacheManager(cacheSources, _lockConfig)); + var exception = Assert.Throws(() => new EasyCacheManager(cacheSources, _lockConfig)); Assert.Contains("Duplicate priority values found", exception.Message, StringComparison.OrdinalIgnoreCase); } @@ -114,40 +114,40 @@ public async Task GetAsync_ShouldGetFromApiAndSetToOther_ValidData() const string Key = StaticData.Key; const string Value = StaticData.Key; - var memoryCacheSource = new Mock>(); - var redisCacheSource = new Mock>(); - var dbCacheSource = new Mock>(); - var apiCacheSource = new Mock>(); + var memoryCacheSource = new Mock(); + var redisCacheSource = new Mock(); + var dbCacheSource = new Mock(); + var apiCacheSource = new Mock(); - _ = memoryCacheSource.Setup(x => x.GetAsync(Key)).ReturnsAsync((string)null!); + _ = memoryCacheSource.Setup(x => x.GetAsync(Key)).ReturnsAsync((string)null!); _ = memoryCacheSource.Setup(x => x.SetAsync(Key, Value)); _ = memoryCacheSource.Setup(x => x.ClearAsync(Key)); _ = memoryCacheSource.Setup(x => x.Priority).Returns(1); - _ = redisCacheSource.Setup(x => x.GetAsync(Key)).ReturnsAsync((string)null!); + _ = redisCacheSource.Setup(x => x.GetAsync(Key)).ReturnsAsync((string)null!); _ = redisCacheSource.Setup(x => x.SetAsync(Key, Value)); _ = redisCacheSource.Setup(x => x.ClearAsync(Key)); _ = redisCacheSource.Setup(x => x.Priority).Returns(2); - _ = dbCacheSource.Setup(x => x.GetAsync(Key)).ReturnsAsync((string)null!); + _ = dbCacheSource.Setup(x => x.GetAsync(Key)).ReturnsAsync((string)null!); _ = dbCacheSource.Setup(x => x.Priority).Returns(3); - _ = apiCacheSource.Setup(x => x.GetAsync(Key)).ReturnsAsync(Value); + _ = apiCacheSource.Setup(x => x.GetAsync(Key)).ReturnsAsync(Value); _ = apiCacheSource.Setup(x => x.Priority).Returns(4); - var cacheSources = new List> { apiCacheSource.Object, dbCacheSource.Object, memoryCacheSource.Object, redisCacheSource.Object }; + var cacheSources = new List { apiCacheSource.Object, dbCacheSource.Object, memoryCacheSource.Object, redisCacheSource.Object }; // Act - var easyCacheManager = new EasyCacheManager(cacheSources, _lockConfig); - var result = await easyCacheManager.GetAsync(Key).ConfigureAwait(true); + var easyCacheManager = new EasyCacheManager(cacheSources, _lockConfig); + var result = await easyCacheManager.GetAsync(Key).ConfigureAwait(true); //Assert Assert.Equal(Value, result); - memoryCacheSource.Verify(x => x.GetAsync(Key), Times.Once, "Memory GetAsync should call only one"); - redisCacheSource.Verify(x => x.GetAsync(Key), Times.Once, "Redis GetAsync should call only one"); - dbCacheSource.Verify(x => x.GetAsync(Key), Times.Once, "Db GetAsync should call only one"); - apiCacheSource.Verify(x => x.GetAsync(Key), Times.Once, "API GetAsync should call only one"); + memoryCacheSource.Verify(x => x.GetAsync(Key), Times.Once, "Memory GetAsync should call only one"); + redisCacheSource.Verify(x => x.GetAsync(Key), Times.Once, "Redis GetAsync should call only one"); + dbCacheSource.Verify(x => x.GetAsync(Key), Times.Once, "Db GetAsync should call only one"); + apiCacheSource.Verify(x => x.GetAsync(Key), Times.Once, "API GetAsync should call only one"); memoryCacheSource.Verify(x => x.SetAsync(Key, Value), Times.Once, "Memory SetAsync should call only one"); redisCacheSource.Verify(x => x.SetAsync(Key, Value), Times.Once, "Redis SetAsync should call only one"); diff --git a/CacheSource/ApiCacheSourceWithGet.cs b/CacheSource/ApiCacheSourceWithGet.cs index 1e3f6a7..4e78c37 100644 --- a/CacheSource/ApiCacheSourceWithGet.cs +++ b/CacheSource/ApiCacheSourceWithGet.cs @@ -1,4 +1,4 @@ -using CacheManager.Config; +using CacheManager.Config; using Flurl.Http; namespace CacheManager.CacheSource; @@ -6,8 +6,7 @@ namespace CacheManager.CacheSource; /// /// Get from Api /// -/// Result -public class ApiCacheSourceWithGet : ICacheSourceWithGet +public class ApiCacheSourceWithGet : ICacheSourceWithGet { private readonly ApiConfig _config; @@ -28,7 +27,7 @@ public ApiCacheSourceWithGet(ApiConfig config, int priority) /// /// Key /// Result - public async Task GetAsync(string key) + public async Task GetAsync(string key) { var result = _config.Type switch { @@ -53,7 +52,7 @@ public ApiCacheSourceWithGet(ApiConfig config, int priority) /// Priority, Lowest priority - checked last /// #if NETSTANDARD2_0 || NET462 - public int Priority { get; set; } + public int Priority { get; set; } #else public int Priority { get; init; } #endif diff --git a/CacheSource/DbCacheSourceWithGet.cs b/CacheSource/DbCacheSourceWithGet.cs index b19b53e..295df08 100644 --- a/CacheSource/DbCacheSourceWithGet.cs +++ b/CacheSource/DbCacheSourceWithGet.cs @@ -1,4 +1,4 @@ -using System.Data; +using System.Data; using System.Diagnostics.CodeAnalysis; using CacheManager.Config; using Dapper; @@ -9,8 +9,7 @@ namespace CacheManager.CacheSource; /// /// Get from Db /// -/// Result -public class DbCacheSourceWithGet : ICacheSourceWithGet +public class DbCacheSourceWithGet : ICacheSourceWithGet { private readonly DbConfig _config; @@ -32,10 +31,10 @@ public DbCacheSourceWithGet(DbConfig config, int priority) /// Key /// Result [SuppressMessage("Reliability", "CA2007:Consider calling ConfigureAwait on the awaited task")] - public async Task GetAsync(string key) + public async Task GetAsync(string key) { #if NETSTANDARD2_0 || NET462 - using var connection = new SqlConnection(_config.ConnectionString); + using var connection = new SqlConnection(_config.ConnectionString); #else await using var connection = new SqlConnection(_config.ConnectionString); #endif @@ -43,7 +42,8 @@ public DbCacheSourceWithGet(DbConfig config, int priority) _config.Query, new { Key = key }, commandType: CommandType.Text, - commandTimeout: _config.TimeOutOnSecond).ConfigureAwait(false); + commandTimeout: _config.TimeOutOnSecond + ).ConfigureAwait(false); return result; } @@ -52,7 +52,7 @@ public DbCacheSourceWithGet(DbConfig config, int priority) /// Priority, Lowest priority - checked last /// #if NETSTANDARD2_0 || NET462 - public int Priority { get; set; } + public int Priority { get; set; } #else public int Priority { get; init; } #endif diff --git a/CacheSource/ICacheSourceWithGet.cs b/CacheSource/ICacheSourceWithGet.cs index d478ebb..601622d 100644 --- a/CacheSource/ICacheSourceWithGet.cs +++ b/CacheSource/ICacheSourceWithGet.cs @@ -1,15 +1,14 @@ -namespace CacheManager.CacheSource; +namespace CacheManager.CacheSource; /// /// Base interface of cache provider with Get ability /// -/// Item to cache -public interface ICacheSourceWithGet : ICacheSourceBase +public interface ICacheSourceWithGet : ICacheSourceBase { /// /// Get from cache /// /// Key /// Result - Task GetAsync(string key); + Task GetAsync(string key); } diff --git a/CacheSource/ICacheSourceWithGetWithClear.cs b/CacheSource/ICacheSourceWithGetWithClear.cs index 067aca2..7ee9f73 100644 --- a/CacheSource/ICacheSourceWithGetWithClear.cs +++ b/CacheSource/ICacheSourceWithGetWithClear.cs @@ -1,10 +1,9 @@ -namespace CacheManager.CacheSource; +namespace CacheManager.CacheSource; /// /// Base interface of cache provider with clear ability /// -/// Item to cache -public interface ICacheSourceWithGetWithClear : ICacheSourceWithGet +public interface ICacheSourceWithGetWithClear : ICacheSourceWithGet { /// /// Clear from cache with key diff --git a/CacheSource/ICacheSourceWithGetWithSet.cs b/CacheSource/ICacheSourceWithGetWithSet.cs index 6c8a20d..753cff3 100644 --- a/CacheSource/ICacheSourceWithGetWithSet.cs +++ b/CacheSource/ICacheSourceWithGetWithSet.cs @@ -1,15 +1,14 @@ -namespace CacheManager.CacheSource; +namespace CacheManager.CacheSource; /// /// Base interface of cache provider with set ability /// -/// Item to cache -public interface ICacheSourceWithGetWithSet : ICacheSourceWithGet +public interface ICacheSourceWithGetWithSet : ICacheSourceWithGet { /// /// Set data to cache /// /// Key /// Data to cache - Task SetAsync(string key, T data); + Task SetAsync(string key, T data); } diff --git a/CacheSource/ICacheSourceWithGetWithSetAndClear.cs b/CacheSource/ICacheSourceWithGetWithSetAndClear.cs index 333bc3a..a6c2d12 100644 --- a/CacheSource/ICacheSourceWithGetWithSetAndClear.cs +++ b/CacheSource/ICacheSourceWithGetWithSetAndClear.cs @@ -1,9 +1,8 @@ -namespace CacheManager.CacheSource; +namespace CacheManager.CacheSource; /// /// Base interface of cache provider with clear and set ability /// -/// Item to cache -public interface ICacheSourceWithGetWithSetAndClear : ICacheSourceWithGetWithSet, ICacheSourceWithGetWithClear +public interface ICacheSourceWithGetWithSetAndClear : ICacheSourceWithGetWithSet, ICacheSourceWithGetWithClear { } diff --git a/CacheSource/MemoryCacheSource.cs b/CacheSource/MemoryCacheSource.cs index 8f34880..2174bb7 100644 --- a/CacheSource/MemoryCacheSource.cs +++ b/CacheSource/MemoryCacheSource.cs @@ -1,4 +1,4 @@ -using CacheManager.Config; +using CacheManager.Config; using Microsoft.Extensions.Caching.Memory; namespace CacheManager.CacheSource; @@ -6,8 +6,7 @@ namespace CacheManager.CacheSource; /// /// Get from Memory /// -/// Result -public class MemoryCacheSource : ICacheSourceWithGetWithSetAndClear +public class MemoryCacheSource : ICacheSourceWithGetWithSetAndClear { private readonly MemoryCache _memoryCache; private readonly MemoryConfig _config; @@ -30,7 +29,7 @@ public MemoryCacheSource(MemoryConfig config, int priority) /// /// Key /// Result - public Task GetAsync(string key) + public Task GetAsync(string key) { _ = _memoryCache.TryGetValue(key, out T? value); return Task.FromResult(value); @@ -41,7 +40,7 @@ public MemoryCacheSource(MemoryConfig config, int priority) /// /// Key /// Data to cache - public Task SetAsync(string key, T data) + public Task SetAsync(string key, T data) { _ = _memoryCache.Set(key, data, _config.CacheTime); return Task.CompletedTask; @@ -61,7 +60,7 @@ public Task ClearAsync(string key) /// Priority, Lowest priority - checked last /// #if NETSTANDARD2_0 || NET462 - public int Priority { get; set; } + public int Priority { get; set; } #else public int Priority { get; init; } #endif diff --git a/CacheSource/RedisCacheSource.cs b/CacheSource/RedisCacheSource.cs index c142686..4078a2c 100644 --- a/CacheSource/RedisCacheSource.cs +++ b/CacheSource/RedisCacheSource.cs @@ -1,4 +1,4 @@ -using System.Text.Json; +using System.Text.Json; using CacheManager.Config; using StackExchange.Redis; @@ -7,8 +7,7 @@ namespace CacheManager.CacheSource; /// /// Get from Redis /// -/// Result -public class RedisCacheSource : ICacheSourceWithGetWithSetAndClear +public class RedisCacheSource : ICacheSourceWithGetWithSetAndClear { private readonly IDatabase _redisCache; private readonly RedisConfig _config; @@ -32,8 +31,9 @@ public RedisCacheSource(RedisConfig config, int priority) /// /// Key /// Result - public async Task GetAsync(string key) + public async Task GetAsync(string key) { + var value = await _redisCache.StringGetAsync(key).ConfigureAwait(false); return value.HasValue ? JsonSerializer.Deserialize(value!) : default; } @@ -43,7 +43,7 @@ public RedisCacheSource(RedisConfig config, int priority) /// /// Key /// Data to cache - public async Task SetAsync(string key, T data) + public async Task SetAsync(string key, T data) { _ = await _redisCache.StringSetAsync(key, JsonSerializer.Serialize(data), _config.CacheTime).ConfigureAwait(false); } @@ -61,7 +61,7 @@ public async Task ClearAsync(string key) /// Priority, Lowest priority - checked last /// #if NETSTANDARD2_0 || NET462 - public int Priority { get; set; } + public int Priority { get; set; } #else public int Priority { get; init; } #endif diff --git a/EasyCacheManager.cs b/EasyCacheManager.cs index a64c25f..6112360 100644 --- a/EasyCacheManager.cs +++ b/EasyCacheManager.cs @@ -1,4 +1,4 @@ -using System.Collections.Concurrent; +using System.Collections.Concurrent; using System.ComponentModel.DataAnnotations; using System.Globalization; using AsyncKeyedLock; @@ -10,12 +10,12 @@ namespace CacheManager; /// /// Manage Cache Easily /// -public class EasyCacheManager : IEasyCacheManager +public class EasyCacheManager : IEasyCacheManager { private readonly LockConfig _lockConfig; - private readonly IEnumerable> _cacheSources; - private readonly IEnumerable> _cacheSourcesWithSet; - private readonly IEnumerable> _cacheSourcesWithClear; + private readonly IEnumerable _cacheSources; + private readonly IEnumerable _cacheSourcesWithSet; + private readonly IEnumerable _cacheSourcesWithClear; private readonly AsyncKeyedLocker _asyncLock; private readonly ConcurrentDictionary _ongoingOperations; @@ -28,7 +28,7 @@ public class EasyCacheManager : IEasyCacheManager /// CacheSources is null /// Options is null /// Duplicate priority values found - public EasyCacheManager([Required] IEnumerable> cacheSources, LockConfig lockConfig) + public EasyCacheManager([Required] IEnumerable cacheSources, LockConfig lockConfig) { if (cacheSources is null) { @@ -52,12 +52,14 @@ public EasyCacheManager([Required] IEnumerable> cacheSour } _cacheSources = baseCacheSources.OrderBy(x => x.Priority); - _cacheSourcesWithSet = baseCacheSources.OfType>().OrderBy(x => x.Priority); - _cacheSourcesWithClear = baseCacheSources.OfType>().OrderBy(x => x.Priority); + _cacheSourcesWithSet = baseCacheSources.OfType().OrderBy(x => x.Priority); + _cacheSourcesWithClear = baseCacheSources.OfType().OrderBy(x => x.Priority); _asyncLock = new AsyncKeyedLocker(new AsyncKeyedLockOptions { - PoolSize = Environment.ProcessorCount * lockConfig.PoolSize, PoolInitialFill = lockConfig.PoolInitialFill, MaxCount = lockConfig.MaxCount + PoolSize = Environment.ProcessorCount * lockConfig.PoolSize, + PoolInitialFill = lockConfig.PoolInitialFill, + MaxCount = lockConfig.MaxCount }); _ongoingOperations = new ConcurrentDictionary(); @@ -68,13 +70,13 @@ public EasyCacheManager([Required] IEnumerable> cacheSour /// /// Key /// cached item - public async Task GetAsync(string key) + public async Task GetAsync(string key) { T? result = default; foreach (var source in _cacheSources) { - result = await source.GetAsync(key).ConfigureAwait(false); + result = await source.GetAsync(key).ConfigureAwait(false); if (result != null) { @@ -117,7 +119,7 @@ public EasyCacheManager([Required] IEnumerable> cacheSour /// Key /// Value /// cached item - public async Task SetAsync(string key, T value) + public async Task SetAsync(string key, T value) { using (await _asyncLock.LockAsync(key).ConfigureAwait(false)) { @@ -158,7 +160,7 @@ public ValueTask DisposeAsync() #endif } - private async Task SetToListAsync(string key, T result, int priority) + private async Task SetToListAsync(string key, T result, int priority) { foreach (var higherPrioritySource in _cacheSourcesWithSet.Where(x => x.Priority < priority)) { diff --git a/IEasyCacheManager.cs b/IEasyCacheManager.cs index 9582faa..4ecb8ee 100644 --- a/IEasyCacheManager.cs +++ b/IEasyCacheManager.cs @@ -1,16 +1,16 @@ -namespace CacheManager; +namespace CacheManager; /// /// Manage Cache Easily /// -public interface IEasyCacheManager : IAsyncDisposable +public interface IEasyCacheManager : IAsyncDisposable { /// /// Get Cached item from all. if not exist call api and returned it, also cached it /// /// Key /// cached item - Task GetAsync(string key); + Task GetAsync(string key); /// /// Manual set value to cache @@ -18,7 +18,7 @@ public interface IEasyCacheManager : IAsyncDisposable /// Key /// Value /// cached item - Task SetAsync(string key, T value); + Task SetAsync(string key, T value); /// /// Clear cached item from all diff --git a/README.md b/README.md index 978185e..bf24189 100644 --- a/README.md +++ b/README.md @@ -53,7 +53,7 @@ also if found on db or api it will set to redis and memory. This package use AsyncKeyedLock to handle lock on get, set and clear on specific key. so you use this package on multi thread program. ### Info -You can use all type like class, object, string to cache, for example EasyCacheManager, EasyCacheManager +You can use all type like class, object, string to cache, for example EasyCacheManager, EasyCacheManager Priority should be unique, you can't crate EasyCacheManager with list of providers with same Priority ### Clear cache