From 9e81143008f32acf801e557f8db665fdf6ae2067 Mon Sep 17 00:00:00 2001 From: catcherwong Date: Wed, 26 Sep 2018 22:48:31 +0800 Subject: [PATCH 01/22] :arrow_up: Update StackExchange.Redis --- src/EasyCaching.Redis/EasyCaching.Redis.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/EasyCaching.Redis/EasyCaching.Redis.csproj b/src/EasyCaching.Redis/EasyCaching.Redis.csproj index 5de2b38c..7a4a5e40 100644 --- a/src/EasyCaching.Redis/EasyCaching.Redis.csproj +++ b/src/EasyCaching.Redis/EasyCaching.Redis.csproj @@ -21,7 +21,7 @@ - + From 5a8df7ebbe32a9daee15b4d955411b32683e0925 Mon Sep 17 00:00:00 2001 From: catcherwong Date: Thu, 27 Sep 2018 22:34:50 +0800 Subject: [PATCH 02/22] :bug: IEasyCachingProvider TryAdd -> Add. --- .../InMemoryCacheServiceCollectionExtensions.cs | 4 ++-- .../MemcachedServiceCollectionExtensions.cs | 2 +- .../RedisCacheServiceCollectionExtensions.cs | 4 ++-- .../SQLiteCacheServiceCollectionExtensions.cs | 4 ++-- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/EasyCaching.InMemory/InMemoryCacheServiceCollectionExtensions.cs b/src/EasyCaching.InMemory/InMemoryCacheServiceCollectionExtensions.cs index fc4f557a..a78a552d 100644 --- a/src/EasyCaching.InMemory/InMemoryCacheServiceCollectionExtensions.cs +++ b/src/EasyCaching.InMemory/InMemoryCacheServiceCollectionExtensions.cs @@ -46,7 +46,7 @@ public static IServiceCollection AddDefaultInMemoryCache( services.Configure(providerAction); services.AddMemoryCache(); - services.TryAddSingleton(); + services.AddSingleton(); return services; } @@ -76,7 +76,7 @@ public static IServiceCollection AddDefaultInMemoryCache( services.Configure(dbConfig); services.AddMemoryCache(); - services.TryAddSingleton(); + services.AddSingleton(); return services; } diff --git a/src/EasyCaching.Memcached/MemcachedServiceCollectionExtensions.cs b/src/EasyCaching.Memcached/MemcachedServiceCollectionExtensions.cs index 0bcf1a52..462ba17e 100644 --- a/src/EasyCaching.Memcached/MemcachedServiceCollectionExtensions.cs +++ b/src/EasyCaching.Memcached/MemcachedServiceCollectionExtensions.cs @@ -39,7 +39,7 @@ public static IServiceCollection AddDefaultMemcached( services.TryAddSingleton(); services.TryAddSingleton(); - services.TryAddSingleton(); + services.AddSingleton(); return services; } diff --git a/src/EasyCaching.Redis/RedisCacheServiceCollectionExtensions.cs b/src/EasyCaching.Redis/RedisCacheServiceCollectionExtensions.cs index 70ead25c..4bb61ee7 100644 --- a/src/EasyCaching.Redis/RedisCacheServiceCollectionExtensions.cs +++ b/src/EasyCaching.Redis/RedisCacheServiceCollectionExtensions.cs @@ -29,7 +29,7 @@ public static IServiceCollection AddDefaultRedisCache( services.TryAddSingleton(); services.TryAddSingleton(); - services.TryAddSingleton(); + services.AddSingleton(); return services; } @@ -78,7 +78,7 @@ public static IServiceCollection AddDefaultRedisCache( services.TryAddSingleton(); services.TryAddSingleton(); - services.TryAddSingleton(); + services.AddSingleton(); return services; } diff --git a/src/EasyCaching.SQLite/SQLiteCacheServiceCollectionExtensions.cs b/src/EasyCaching.SQLite/SQLiteCacheServiceCollectionExtensions.cs index 7c743811..b3ceb33f 100644 --- a/src/EasyCaching.SQLite/SQLiteCacheServiceCollectionExtensions.cs +++ b/src/EasyCaching.SQLite/SQLiteCacheServiceCollectionExtensions.cs @@ -28,7 +28,7 @@ public static IServiceCollection AddSQLiteCache( services.Configure(providerAction); services.TryAddSingleton(); - services.TryAddSingleton(); + services.AddSingleton(); return services; } @@ -62,7 +62,7 @@ public static IServiceCollection AddSQLiteCache( services.Configure(dbConfig); services.TryAddSingleton(); - services.TryAddSingleton(); + services.AddSingleton(); return services; } From a08d530b48f175aa543ea47ff58a508263167504 Mon Sep 17 00:00:00 2001 From: catcherwong Date: Sat, 6 Oct 2018 22:40:47 +0800 Subject: [PATCH 03/22] :sparkles: Named Provider for InMemory Caching --- EasyCaching.sln | 96 +++++++++---------- .../Controllers/CusController.cs | 28 ++++++ sample/EasyCaching.Demo.Providers/Startup.cs | 13 ++- src/EasyCaching.Core/EasyCaching.Core.csproj | 3 + src/EasyCaching.Core/EasyCachingConstValue.cs | 4 +- src/EasyCaching.Core/IEasyCachingProvider.cs | 2 + .../IEasyCachingProviderFactory.cs | 29 ++++++ .../DefaultInMemoryCachingProvider.cs | 84 +++++++++++----- ...nMemoryCacheServiceCollectionExtensions.cs | 66 +++++++++++++ 9 files changed, 245 insertions(+), 80 deletions(-) create mode 100644 sample/EasyCaching.Demo.Providers/Controllers/CusController.cs create mode 100644 src/EasyCaching.Core/IEasyCachingProviderFactory.cs diff --git a/EasyCaching.sln b/EasyCaching.sln index a36156c3..7b9e10c7 100644 --- a/EasyCaching.sln +++ b/EasyCaching.sln @@ -11,14 +11,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EasyCaching.Core", "src\Eas EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EasyCaching.InMemory", "src\EasyCaching.InMemory\EasyCaching.InMemory.csproj", "{B9490432-737B-4518-B851-9D40FD29B392}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EasyCaching.SQLite", "src\EasyCaching.SQLite\EasyCaching.SQLite.csproj", "{09FCF125-522E-4C0F-9CF0-0377A3F2A1A0}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EasyCaching.Redis", "src\EasyCaching.Redis\EasyCaching.Redis.csproj", "{7F72FA56-C4E8-4EF5-963D-FC4174453574}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EasyCaching.Memcached", "src\EasyCaching.Memcached\EasyCaching.Memcached.csproj", "{D5626647-1E42-4584-BC42-354D8BD94FE7}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EasyCaching.UnitTests", "test\EasyCaching.UnitTests\EasyCaching.UnitTests.csproj", "{93E7EF96-D44A-4400-BA75-169C0F3FDAC5}" -EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EasyCaching.Serialization.MessagePack", "src\EasyCaching.Serialization.MessagePack\EasyCaching.Serialization.MessagePack.csproj", "{50D8C42C-1BC0-4133-8B70-63A6649DBD74}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EasyCaching.Interceptor.AspectCore", "src\EasyCaching.Interceptor.AspectCore\EasyCaching.Interceptor.AspectCore.csproj", "{BED4832E-A790-42A6-978D-E0C1A215E638}" @@ -29,21 +21,29 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EasyCaching.Bus.RabbitMQ", EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EasyCaching.Interceptor.Castle", "src\EasyCaching.Interceptor.Castle\EasyCaching.Interceptor.Castle.csproj", "{7B55B6D9-4221-4E82-AED6-BEC9A60C99D2}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EasyCaching.HybridCache", "src\EasyCaching.HybridCache\EasyCaching.HybridCache.csproj", "{013F6582-CF26-4F5A-BE0B-B383347CF656}" -EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EasyCaching.Serialization.Json", "src\EasyCaching.Serialization.Json\EasyCaching.Serialization.Json.csproj", "{F0302BE8-188A-4EAF-8391-514CA9352DB3}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EasyCaching.Serialization.Protobuf", "src\EasyCaching.Serialization.Protobuf\EasyCaching.Serialization.Protobuf.csproj", "{3AAEDDBA-5037-4061-84E5-667F89C11F8E}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EasyCaching.PerformanceTests", "test\EasyCaching.PerformanceTests\EasyCaching.PerformanceTests.csproj", "{0631F74C-8AFA-4B16-A50F-A5E437226265}" -EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EasyCaching.ResponseCaching", "src\EasyCaching.ResponseCaching\EasyCaching.ResponseCaching.csproj", "{261EE728-4965-4C0E-B99B-3B188442263A}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EasyCaching.Demo.Providers", "sample\EasyCaching.Demo.Providers\EasyCaching.Demo.Providers.csproj", "{4193DF5A-E034-4917-83F4-380E8D7DCF83}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EasyCaching.Demo.Interceptors", "sample\EasyCaching.Demo.Interceptors\EasyCaching.Demo.Interceptors.csproj", "{F7DD4826-1375-42B3-97BA-37685460282E}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EasyCaching.Demo.ResponseCaching", "sample\EasyCaching.Demo.ResponseCaching\EasyCaching.Demo.ResponseCaching.csproj", "{2AFDA79E-C034-4BC2-921D-5C7082924281}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EasyCaching.SQLite", "src\EasyCaching.SQLite\EasyCaching.SQLite.csproj", "{50089D69-50CF-49B7-8939-59C309A22336}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EasyCaching.Redis", "src\EasyCaching.Redis\EasyCaching.Redis.csproj", "{F58E5C6F-407F-4E80-9282-2028E9810F55}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EasyCaching.Memcached", "src\EasyCaching.Memcached\EasyCaching.Memcached.csproj", "{709D2333-42A7-45E6-B175-E630DCC1D807}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EasyCaching.HybridCache", "src\EasyCaching.HybridCache\EasyCaching.HybridCache.csproj", "{18DB08CD-B8CC-4409-9C7C-2906BCAA8827}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EasyCaching.Demo.ResponseCaching", "sample\EasyCaching.Demo.ResponseCaching\EasyCaching.Demo.ResponseCaching.csproj", "{76A5C2E3-6525-45A0-9CE7-649F3235A443}" +EndProject +Project("{9344BDBB-3E7F-41FC-A0DD-8665D75EE146}") = "EasyCaching.UnitTests", "test\EasyCaching.UnitTests\EasyCaching.UnitTests.csproj", "{2A8D7103-DF64-47B6-A406-8F8559AF7E7F}" +EndProject +Project("{9344BDBB-3E7F-41FC-A0DD-8665D75EE146}") = "EasyCaching.PerformanceTests", "test\EasyCaching.PerformanceTests\EasyCaching.PerformanceTests.csproj", "{6EBE36A2-F128-4C63-B90A-B700D8C2F2E8}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -59,22 +59,6 @@ Global {B9490432-737B-4518-B851-9D40FD29B392}.Debug|Any CPU.Build.0 = Debug|Any CPU {B9490432-737B-4518-B851-9D40FD29B392}.Release|Any CPU.ActiveCfg = Release|Any CPU {B9490432-737B-4518-B851-9D40FD29B392}.Release|Any CPU.Build.0 = Release|Any CPU - {09FCF125-522E-4C0F-9CF0-0377A3F2A1A0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {09FCF125-522E-4C0F-9CF0-0377A3F2A1A0}.Debug|Any CPU.Build.0 = Debug|Any CPU - {09FCF125-522E-4C0F-9CF0-0377A3F2A1A0}.Release|Any CPU.ActiveCfg = Release|Any CPU - {09FCF125-522E-4C0F-9CF0-0377A3F2A1A0}.Release|Any CPU.Build.0 = Release|Any CPU - {7F72FA56-C4E8-4EF5-963D-FC4174453574}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {7F72FA56-C4E8-4EF5-963D-FC4174453574}.Debug|Any CPU.Build.0 = Debug|Any CPU - {7F72FA56-C4E8-4EF5-963D-FC4174453574}.Release|Any CPU.ActiveCfg = Release|Any CPU - {7F72FA56-C4E8-4EF5-963D-FC4174453574}.Release|Any CPU.Build.0 = Release|Any CPU - {D5626647-1E42-4584-BC42-354D8BD94FE7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {D5626647-1E42-4584-BC42-354D8BD94FE7}.Debug|Any CPU.Build.0 = Debug|Any CPU - {D5626647-1E42-4584-BC42-354D8BD94FE7}.Release|Any CPU.ActiveCfg = Release|Any CPU - {D5626647-1E42-4584-BC42-354D8BD94FE7}.Release|Any CPU.Build.0 = Release|Any CPU - {93E7EF96-D44A-4400-BA75-169C0F3FDAC5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {93E7EF96-D44A-4400-BA75-169C0F3FDAC5}.Debug|Any CPU.Build.0 = Debug|Any CPU - {93E7EF96-D44A-4400-BA75-169C0F3FDAC5}.Release|Any CPU.ActiveCfg = Release|Any CPU - {93E7EF96-D44A-4400-BA75-169C0F3FDAC5}.Release|Any CPU.Build.0 = Release|Any CPU {50D8C42C-1BC0-4133-8B70-63A6649DBD74}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {50D8C42C-1BC0-4133-8B70-63A6649DBD74}.Debug|Any CPU.Build.0 = Debug|Any CPU {50D8C42C-1BC0-4133-8B70-63A6649DBD74}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -95,10 +79,6 @@ Global {7B55B6D9-4221-4E82-AED6-BEC9A60C99D2}.Debug|Any CPU.Build.0 = Debug|Any CPU {7B55B6D9-4221-4E82-AED6-BEC9A60C99D2}.Release|Any CPU.ActiveCfg = Release|Any CPU {7B55B6D9-4221-4E82-AED6-BEC9A60C99D2}.Release|Any CPU.Build.0 = Release|Any CPU - {013F6582-CF26-4F5A-BE0B-B383347CF656}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {013F6582-CF26-4F5A-BE0B-B383347CF656}.Debug|Any CPU.Build.0 = Debug|Any CPU - {013F6582-CF26-4F5A-BE0B-B383347CF656}.Release|Any CPU.ActiveCfg = Release|Any CPU - {013F6582-CF26-4F5A-BE0B-B383347CF656}.Release|Any CPU.Build.0 = Release|Any CPU {F0302BE8-188A-4EAF-8391-514CA9352DB3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {F0302BE8-188A-4EAF-8391-514CA9352DB3}.Debug|Any CPU.Build.0 = Debug|Any CPU {F0302BE8-188A-4EAF-8391-514CA9352DB3}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -107,10 +87,6 @@ Global {3AAEDDBA-5037-4061-84E5-667F89C11F8E}.Debug|Any CPU.Build.0 = Debug|Any CPU {3AAEDDBA-5037-4061-84E5-667F89C11F8E}.Release|Any CPU.ActiveCfg = Release|Any CPU {3AAEDDBA-5037-4061-84E5-667F89C11F8E}.Release|Any CPU.Build.0 = Release|Any CPU - {0631F74C-8AFA-4B16-A50F-A5E437226265}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {0631F74C-8AFA-4B16-A50F-A5E437226265}.Debug|Any CPU.Build.0 = Debug|Any CPU - {0631F74C-8AFA-4B16-A50F-A5E437226265}.Release|Any CPU.ActiveCfg = Release|Any CPU - {0631F74C-8AFA-4B16-A50F-A5E437226265}.Release|Any CPU.Build.0 = Release|Any CPU {261EE728-4965-4C0E-B99B-3B188442263A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {261EE728-4965-4C0E-B99B-3B188442263A}.Debug|Any CPU.Build.0 = Debug|Any CPU {261EE728-4965-4C0E-B99B-3B188442263A}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -123,30 +99,54 @@ Global {F7DD4826-1375-42B3-97BA-37685460282E}.Debug|Any CPU.Build.0 = Debug|Any CPU {F7DD4826-1375-42B3-97BA-37685460282E}.Release|Any CPU.ActiveCfg = Release|Any CPU {F7DD4826-1375-42B3-97BA-37685460282E}.Release|Any CPU.Build.0 = Release|Any CPU - {2AFDA79E-C034-4BC2-921D-5C7082924281}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {2AFDA79E-C034-4BC2-921D-5C7082924281}.Debug|Any CPU.Build.0 = Debug|Any CPU - {2AFDA79E-C034-4BC2-921D-5C7082924281}.Release|Any CPU.ActiveCfg = Release|Any CPU - {2AFDA79E-C034-4BC2-921D-5C7082924281}.Release|Any CPU.Build.0 = Release|Any CPU + {50089D69-50CF-49B7-8939-59C309A22336}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {50089D69-50CF-49B7-8939-59C309A22336}.Debug|Any CPU.Build.0 = Debug|Any CPU + {50089D69-50CF-49B7-8939-59C309A22336}.Release|Any CPU.ActiveCfg = Release|Any CPU + {50089D69-50CF-49B7-8939-59C309A22336}.Release|Any CPU.Build.0 = Release|Any CPU + {F58E5C6F-407F-4E80-9282-2028E9810F55}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F58E5C6F-407F-4E80-9282-2028E9810F55}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F58E5C6F-407F-4E80-9282-2028E9810F55}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F58E5C6F-407F-4E80-9282-2028E9810F55}.Release|Any CPU.Build.0 = Release|Any CPU + {709D2333-42A7-45E6-B175-E630DCC1D807}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {709D2333-42A7-45E6-B175-E630DCC1D807}.Debug|Any CPU.Build.0 = Debug|Any CPU + {709D2333-42A7-45E6-B175-E630DCC1D807}.Release|Any CPU.ActiveCfg = Release|Any CPU + {709D2333-42A7-45E6-B175-E630DCC1D807}.Release|Any CPU.Build.0 = Release|Any CPU + {18DB08CD-B8CC-4409-9C7C-2906BCAA8827}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {18DB08CD-B8CC-4409-9C7C-2906BCAA8827}.Debug|Any CPU.Build.0 = Debug|Any CPU + {18DB08CD-B8CC-4409-9C7C-2906BCAA8827}.Release|Any CPU.ActiveCfg = Release|Any CPU + {18DB08CD-B8CC-4409-9C7C-2906BCAA8827}.Release|Any CPU.Build.0 = Release|Any CPU + {76A5C2E3-6525-45A0-9CE7-649F3235A443}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {76A5C2E3-6525-45A0-9CE7-649F3235A443}.Debug|Any CPU.Build.0 = Debug|Any CPU + {76A5C2E3-6525-45A0-9CE7-649F3235A443}.Release|Any CPU.ActiveCfg = Release|Any CPU + {76A5C2E3-6525-45A0-9CE7-649F3235A443}.Release|Any CPU.Build.0 = Release|Any CPU + {2A8D7103-DF64-47B6-A406-8F8559AF7E7F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {2A8D7103-DF64-47B6-A406-8F8559AF7E7F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2A8D7103-DF64-47B6-A406-8F8559AF7E7F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {2A8D7103-DF64-47B6-A406-8F8559AF7E7F}.Release|Any CPU.Build.0 = Release|Any CPU + {6EBE36A2-F128-4C63-B90A-B700D8C2F2E8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6EBE36A2-F128-4C63-B90A-B700D8C2F2E8}.Debug|Any CPU.Build.0 = Debug|Any CPU + {6EBE36A2-F128-4C63-B90A-B700D8C2F2E8}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6EBE36A2-F128-4C63-B90A-B700D8C2F2E8}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(NestedProjects) = preSolution {CE61FAA2-0233-451C-991D-4222ED61C84B} = {A0F5CC7E-155F-4726-8DEB-E966950B3FE9} {B9490432-737B-4518-B851-9D40FD29B392} = {A0F5CC7E-155F-4726-8DEB-E966950B3FE9} - {09FCF125-522E-4C0F-9CF0-0377A3F2A1A0} = {A0F5CC7E-155F-4726-8DEB-E966950B3FE9} - {7F72FA56-C4E8-4EF5-963D-FC4174453574} = {A0F5CC7E-155F-4726-8DEB-E966950B3FE9} - {D5626647-1E42-4584-BC42-354D8BD94FE7} = {A0F5CC7E-155F-4726-8DEB-E966950B3FE9} - {93E7EF96-D44A-4400-BA75-169C0F3FDAC5} = {EBB55F65-7D07-4281-8D5E-7B0CA88E1AD0} {50D8C42C-1BC0-4133-8B70-63A6649DBD74} = {A0F5CC7E-155F-4726-8DEB-E966950B3FE9} {BED4832E-A790-42A6-978D-E0C1A215E638} = {A0F5CC7E-155F-4726-8DEB-E966950B3FE9} {07326A03-B144-469F-837B-31DD3E0EB1AC} = {A0F5CC7E-155F-4726-8DEB-E966950B3FE9} {265FB0C5-2C34-438D-B671-63836954EB5A} = {A0F5CC7E-155F-4726-8DEB-E966950B3FE9} {7B55B6D9-4221-4E82-AED6-BEC9A60C99D2} = {A0F5CC7E-155F-4726-8DEB-E966950B3FE9} - {013F6582-CF26-4F5A-BE0B-B383347CF656} = {A0F5CC7E-155F-4726-8DEB-E966950B3FE9} {F0302BE8-188A-4EAF-8391-514CA9352DB3} = {A0F5CC7E-155F-4726-8DEB-E966950B3FE9} {3AAEDDBA-5037-4061-84E5-667F89C11F8E} = {A0F5CC7E-155F-4726-8DEB-E966950B3FE9} - {0631F74C-8AFA-4B16-A50F-A5E437226265} = {EBB55F65-7D07-4281-8D5E-7B0CA88E1AD0} {261EE728-4965-4C0E-B99B-3B188442263A} = {A0F5CC7E-155F-4726-8DEB-E966950B3FE9} {4193DF5A-E034-4917-83F4-380E8D7DCF83} = {F88D727A-9F9C-43D9-90B1-D4A02BF8BC98} {F7DD4826-1375-42B3-97BA-37685460282E} = {F88D727A-9F9C-43D9-90B1-D4A02BF8BC98} - {2AFDA79E-C034-4BC2-921D-5C7082924281} = {F88D727A-9F9C-43D9-90B1-D4A02BF8BC98} + {50089D69-50CF-49B7-8939-59C309A22336} = {A0F5CC7E-155F-4726-8DEB-E966950B3FE9} + {F58E5C6F-407F-4E80-9282-2028E9810F55} = {A0F5CC7E-155F-4726-8DEB-E966950B3FE9} + {709D2333-42A7-45E6-B175-E630DCC1D807} = {A0F5CC7E-155F-4726-8DEB-E966950B3FE9} + {18DB08CD-B8CC-4409-9C7C-2906BCAA8827} = {A0F5CC7E-155F-4726-8DEB-E966950B3FE9} + {76A5C2E3-6525-45A0-9CE7-649F3235A443} = {F88D727A-9F9C-43D9-90B1-D4A02BF8BC98} + {2A8D7103-DF64-47B6-A406-8F8559AF7E7F} = {EBB55F65-7D07-4281-8D5E-7B0CA88E1AD0} + {6EBE36A2-F128-4C63-B90A-B700D8C2F2E8} = {EBB55F65-7D07-4281-8D5E-7B0CA88E1AD0} EndGlobalSection EndGlobal diff --git a/sample/EasyCaching.Demo.Providers/Controllers/CusController.cs b/sample/EasyCaching.Demo.Providers/Controllers/CusController.cs new file mode 100644 index 00000000..7f3357cd --- /dev/null +++ b/sample/EasyCaching.Demo.Providers/Controllers/CusController.cs @@ -0,0 +1,28 @@ +namespace EasyCaching.Demo.Providers.Controllers +{ + using EasyCaching.Core; + using Microsoft.AspNetCore.Mvc; + using System; + + [Route("api/[controller]")] + public class CusController : Controller + { + private readonly IEasyCachingProviderFactory _factory; + + public CusController(IEasyCachingProviderFactory factory) + { + this._factory = factory; + } + + // GET api/cus/get?name=Default + [HttpGet] + [Route("get")] + public string Get(string name = "Default") + { + var provider = _factory.GetCachingProvider(name); + var val = name.Equals("cus") ? "cus" : "default"; + var res = provider.Get("demo", () => val, TimeSpan.FromMinutes(1)); + return $"cached value : {res}"; + } + } +} diff --git a/sample/EasyCaching.Demo.Providers/Startup.cs b/sample/EasyCaching.Demo.Providers/Startup.cs index 5d0bd293..c389071a 100644 --- a/sample/EasyCaching.Demo.Providers/Startup.cs +++ b/sample/EasyCaching.Demo.Providers/Startup.cs @@ -3,10 +3,10 @@ using EasyCaching.Core; using EasyCaching.Core.Internal; using EasyCaching.InMemory; - using EasyCaching.HybridCache; - using EasyCaching.Memcached; - using EasyCaching.Redis; - using EasyCaching.SQLite; + //using EasyCaching.HybridCache; + //using EasyCaching.Memcached; + //using EasyCaching.Redis; + //using EasyCaching.SQLite; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; @@ -29,7 +29,10 @@ public void ConfigureServices(IServiceCollection services) services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); //1. Important step for using InMemory Cache - services.AddDefaultInMemoryCache(x => { x.EnableLogging = true; }); + //services.AddDefaultInMemoryCache(); + + services.AddDefaultInMemoryCacheWithFactory(); + services.AddDefaultInMemoryCacheWithFactory("cus"); //services.AddDefaultInMemoryCache(Configuration); diff --git a/src/EasyCaching.Core/EasyCaching.Core.csproj b/src/EasyCaching.Core/EasyCaching.Core.csproj index c0db955f..1a46560b 100644 --- a/src/EasyCaching.Core/EasyCaching.Core.csproj +++ b/src/EasyCaching.Core/EasyCaching.Core.csproj @@ -26,4 +26,7 @@ + + + diff --git a/src/EasyCaching.Core/EasyCachingConstValue.cs b/src/EasyCaching.Core/EasyCachingConstValue.cs index 750b6e22..d3a49c3d 100644 --- a/src/EasyCaching.Core/EasyCachingConstValue.cs +++ b/src/EasyCaching.Core/EasyCachingConstValue.cs @@ -28,6 +28,8 @@ public class EasyCachingConstValue /// /// The in-memory section. /// - public const string InMemorySection = "easycaching:inmemory"; + public const string InMemorySection = "easycaching:inmemory"; + + public const string DefaultName = "Default"; } } diff --git a/src/EasyCaching.Core/IEasyCachingProvider.cs b/src/EasyCaching.Core/IEasyCachingProvider.cs index bd50005d..1881e88d 100644 --- a/src/EasyCaching.Core/IEasyCachingProvider.cs +++ b/src/EasyCaching.Core/IEasyCachingProvider.cs @@ -9,6 +9,8 @@ /// public interface IEasyCachingProvider { + string Name { get; } + /// /// Set the specified cacheKey, cacheValue and expiration. /// diff --git a/src/EasyCaching.Core/IEasyCachingProviderFactory.cs b/src/EasyCaching.Core/IEasyCachingProviderFactory.cs new file mode 100644 index 00000000..e5bc443c --- /dev/null +++ b/src/EasyCaching.Core/IEasyCachingProviderFactory.cs @@ -0,0 +1,29 @@ +namespace EasyCaching.Core +{ + using System.Collections.Generic; + using System.Linq; + + public interface IEasyCachingProviderFactory + { + IEasyCachingProvider GetCachingProvider(string name); + } + + public class DefaultEasyCachingProviderFactory : IEasyCachingProviderFactory + { + private readonly IEnumerable _cachingProviders; + + public DefaultEasyCachingProviderFactory(IEnumerable cachingProviders) + { + this._cachingProviders = cachingProviders; + } + + public IEasyCachingProvider GetCachingProvider(string name) + { + Internal.ArgumentCheck.NotNullOrWhiteSpace(name, nameof(name)); + + var provider = _cachingProviders.FirstOrDefault(x => x.Name.Equals(name)); + + return provider; + } + } +} diff --git a/src/EasyCaching.InMemory/DefaultInMemoryCachingProvider.cs b/src/EasyCaching.InMemory/DefaultInMemoryCachingProvider.cs index 97073ee7..37c19efa 100644 --- a/src/EasyCaching.InMemory/DefaultInMemoryCachingProvider.cs +++ b/src/EasyCaching.InMemory/DefaultInMemoryCachingProvider.cs @@ -62,13 +62,18 @@ public class DefaultInMemoryCachingProvider : IEasyCachingProvider private readonly CacheStats _cacheStats; + private readonly string _name; + public CacheStats CacheStats => _cacheStats; + public string Name => _name; + /// /// Initializes a new instance of the class. /// /// Microsoft MemoryCache. public DefaultInMemoryCachingProvider( + string name, IMemoryCache cache, IOptionsMonitor options, ILoggerFactory loggerFactory = null) @@ -79,6 +84,7 @@ public DefaultInMemoryCachingProvider( this._cacheKeys = new ConcurrentCollections.ConcurrentHashSet(); this._cacheStats = new CacheStats(); + this._name = name; } /// @@ -94,10 +100,10 @@ public CacheValue Get(string cacheKey, Func dataRetriever, TimeSpan exp ArgumentCheck.NotNullOrWhiteSpace(cacheKey, nameof(cacheKey)); ArgumentCheck.NotNegativeOrZero(expiration, nameof(expiration)); - if (_cache.Get(cacheKey) is T result) + if (_cache.Get(BuildCacheKey(Name, cacheKey)) is T result) { if (_options.EnableLogging) - _logger?.LogInformation($"Cache Hit : cachekey = {cacheKey}"); + _logger?.LogInformation($"Cache Hit : cachekey = {BuildCacheKey(Name, cacheKey)}"); CacheStats.OnHit(); @@ -107,7 +113,7 @@ public CacheValue Get(string cacheKey, Func dataRetriever, TimeSpan exp CacheStats.OnMiss(); if (_options.EnableLogging) - _logger?.LogInformation($"Cache Missed : cachekey = {cacheKey}"); + _logger?.LogInformation($"Cache Missed : cachekey = {BuildCacheKey(Name, cacheKey)}"); result = dataRetriever?.Invoke(); @@ -135,10 +141,10 @@ public async Task> GetAsync(string cacheKey, Func> data ArgumentCheck.NotNullOrWhiteSpace(cacheKey, nameof(cacheKey)); ArgumentCheck.NotNegativeOrZero(expiration, nameof(expiration)); - if (_cache.Get(cacheKey) is T result) + if (_cache.Get(BuildCacheKey(Name, cacheKey)) is T result) { if (_options.EnableLogging) - _logger?.LogInformation($"Cache Hit : cachekey = {cacheKey}"); + _logger?.LogInformation($"Cache Hit : cachekey = {BuildCacheKey(Name, cacheKey)}"); CacheStats.OnHit(); @@ -148,7 +154,7 @@ public async Task> GetAsync(string cacheKey, Func> data CacheStats.OnMiss(); if (_options.EnableLogging) - _logger?.LogInformation($"Cache Missed : cachekey = {cacheKey}"); + _logger?.LogInformation($"Cache Missed : cachekey = {BuildCacheKey(Name, cacheKey)}"); result = await dataRetriever?.Invoke(); @@ -173,10 +179,10 @@ public CacheValue Get(string cacheKey)// where T : class { ArgumentCheck.NotNullOrWhiteSpace(cacheKey, nameof(cacheKey)); - if (_cache.Get(cacheKey) is T result) + if (_cache.Get(BuildCacheKey(Name, cacheKey)) is T result) { if (_options.EnableLogging) - _logger?.LogInformation($"Cache Hit : cachekey = {cacheKey}"); + _logger?.LogInformation($"Cache Hit : cachekey = {BuildCacheKey(Name, cacheKey)}"); CacheStats.OnHit(); @@ -185,7 +191,7 @@ public CacheValue Get(string cacheKey)// where T : class else { if (_options.EnableLogging) - _logger?.LogInformation($"Cache Missed : cachekey = {cacheKey}"); + _logger?.LogInformation($"Cache Missed : cachekey = {BuildCacheKey(Name, cacheKey)}"); CacheStats.OnMiss(); @@ -203,12 +209,12 @@ public async Task> GetAsync(string cacheKey)// where T : class { ArgumentCheck.NotNullOrWhiteSpace(cacheKey, nameof(cacheKey)); - var result = await Task.FromResult((T)_cache.Get(cacheKey)); + var result = await Task.FromResult((T)_cache.Get(BuildCacheKey(Name, cacheKey))); if (result != null) { if (_options.EnableLogging) - _logger?.LogInformation($"Cache Hit : cachekey = {cacheKey}"); + _logger?.LogInformation($"Cache Hit : cachekey = {BuildCacheKey(Name, cacheKey)}"); CacheStats.OnHit(); @@ -217,7 +223,7 @@ public async Task> GetAsync(string cacheKey)// where T : class else { if (_options.EnableLogging) - _logger?.LogInformation($"Cache Missed : cachekey = {cacheKey}"); + _logger?.LogInformation($"Cache Missed : cachekey = {BuildCacheKey(Name, cacheKey)}"); CacheStats.OnMiss(); @@ -234,9 +240,9 @@ public void Remove(string cacheKey) { ArgumentCheck.NotNullOrWhiteSpace(cacheKey, nameof(cacheKey)); - _cache.Remove(cacheKey); + _cache.Remove(BuildCacheKey(Name, cacheKey)); - _cacheKeys.TryRemove(cacheKey); + _cacheKeys.TryRemove(BuildCacheKey(Name, cacheKey)); } /// @@ -250,8 +256,8 @@ public async Task RemoveAsync(string cacheKey) await Task.Run(() => { - _cache.Remove(cacheKey); - _cacheKeys.TryRemove(cacheKey); + _cache.Remove(BuildCacheKey(Name, cacheKey)); + _cacheKeys.TryRemove(BuildCacheKey(Name, cacheKey)); }); } @@ -275,9 +281,9 @@ public void Set(string cacheKey, T cacheValue, TimeSpan expiration)// where T expiration.Add(new TimeSpan(0, 0, addSec)); } - _cache.Set(cacheKey, cacheValue, expiration); + _cache.Set(BuildCacheKey(Name, cacheKey), cacheValue, expiration); - _cacheKeys.Add(cacheKey); + _cacheKeys.Add(BuildCacheKey(Name, cacheKey)); } @@ -303,8 +309,8 @@ public async Task SetAsync(string cacheKey, T cacheValue, TimeSpan expiration await Task.Run(() => { - _cache.Set(cacheKey, cacheValue, expiration); - _cacheKeys.Add(cacheKey); + _cache.Set(BuildCacheKey(Name, cacheKey), cacheValue, expiration); + _cacheKeys.Add(BuildCacheKey(Name, cacheKey)); }); } @@ -317,7 +323,7 @@ public bool Exists(string cacheKey) { ArgumentCheck.NotNullOrWhiteSpace(cacheKey, nameof(cacheKey)); - return _cache.TryGetValue(cacheKey, out object value); + return _cache.TryGetValue(BuildCacheKey(Name, cacheKey), out object value); } /// @@ -329,7 +335,7 @@ public async Task ExistsAsync(string cacheKey) { ArgumentCheck.NotNullOrWhiteSpace(cacheKey, nameof(cacheKey)); - return await Task.FromResult(_cache.TryGetValue(cacheKey, out object value)); + return await Task.FromResult(_cache.TryGetValue(BuildCacheKey(Name, cacheKey), out object value)); } /// @@ -375,6 +381,8 @@ public void RemoveByPrefix(string prefix) { ArgumentCheck.NotNullOrWhiteSpace(prefix, nameof(prefix)); + prefix = BuildCacheKey(Name, prefix); + var keys = _cacheKeys.Where(x => x.StartsWith(prefix.Trim(), StringComparison.OrdinalIgnoreCase)); if (_options.EnableLogging) @@ -398,6 +406,8 @@ public async Task RemoveByPrefixAsync(string prefix) { ArgumentCheck.NotNullOrWhiteSpace(prefix, nameof(prefix)); + prefix = BuildCacheKey(Name, prefix); + var keys = _cacheKeys.Where(x => x.StartsWith(prefix.Trim(), StringComparison.OrdinalIgnoreCase)); if (_options.EnableLogging) @@ -504,6 +514,8 @@ public IDictionary> GetByPrefix(string prefix)// where var map = new Dictionary>(); + prefix = BuildCacheKey(Name, prefix); + if (_options.EnableLogging) _logger?.LogInformation($"GetByPrefix : prefix = {prefix}"); @@ -529,6 +541,8 @@ public Task>> GetByPrefixAsync(string prefi { ArgumentCheck.NotNullOrWhiteSpace(prefix, nameof(prefix)); + prefix = BuildCacheKey(Name, prefix); + if (_options.EnableLogging) _logger?.LogInformation($"GetByPrefixAsync : prefix = {prefix}"); @@ -555,6 +569,8 @@ public void RemoveAll(IEnumerable cacheKeys) { ArgumentCheck.NotNullAndCountGTZero(cacheKeys, nameof(cacheKeys)); + cacheKeys = cacheKeys.Select(x => BuildCacheKey(Name, x)); + if (_options.EnableLogging) _logger?.LogInformation($"RemoveAll : cacheKeys = {string.Join(",", cacheKeys)}"); @@ -573,6 +589,8 @@ public async Task RemoveAllAsync(IEnumerable cacheKeys) { ArgumentCheck.NotNullAndCountGTZero(cacheKeys, nameof(cacheKeys)); + cacheKeys = cacheKeys.Select(x => BuildCacheKey(Name, x)); + if (_options.EnableLogging) _logger?.LogInformation($"RemoveAllAsync : cacheKeys = {string.Join(",", cacheKeys)}"); @@ -594,7 +612,7 @@ public int GetCount(string prefix = "") { return string.IsNullOrWhiteSpace(prefix) ? _cacheKeys.Count - : _cacheKeys.Count(x => x.StartsWith(prefix.Trim(), StringComparison.OrdinalIgnoreCase)); + : _cacheKeys.Count(x => x.StartsWith(BuildCacheKey(Name, prefix.Trim()), StringComparison.OrdinalIgnoreCase)); } /// @@ -605,10 +623,13 @@ public void Flush() if (_options.EnableLogging) _logger?.LogInformation("Flush"); - foreach (var item in _cacheKeys) - _cache.Remove(item); + var cacheKeys = _cacheKeys.Where(x => x.StartsWith(Name, StringComparison.OrdinalIgnoreCase)); - _cacheKeys.Clear(); + foreach (var item in cacheKeys) + { + _cache.Remove(item); + _cacheKeys.TryRemove(item); + } } /// @@ -623,5 +644,16 @@ public async Task FlushAsync() Flush(); await Task.CompletedTask; } + + /// + /// Builds the cache key. + /// + /// The cache key. + /// Privider name. + /// Cache key. + private string BuildCacheKey(string prividerName, string cacheKey) + { + return $"{prividerName}-{cacheKey}"; + } } } diff --git a/src/EasyCaching.InMemory/InMemoryCacheServiceCollectionExtensions.cs b/src/EasyCaching.InMemory/InMemoryCacheServiceCollectionExtensions.cs index a78a552d..e9352dbc 100644 --- a/src/EasyCaching.InMemory/InMemoryCacheServiceCollectionExtensions.cs +++ b/src/EasyCaching.InMemory/InMemoryCacheServiceCollectionExtensions.cs @@ -47,6 +47,13 @@ public static IServiceCollection AddDefaultInMemoryCache( services.AddMemoryCache(); services.AddSingleton(); + //services.AddSingleton(x=> + //{ + // var mCache = x.GetRequiredService(); + // var mOptions = x.GetRequiredService>(); + // var mLog = x.GetRequiredService(); + // return new DefaultInMemoryCachingProvider(name, mCache, mOptions,mLog); + //}); return services; } @@ -77,6 +84,65 @@ public static IServiceCollection AddDefaultInMemoryCache( services.AddMemoryCache(); services.AddSingleton(); + //services.AddSingleton(x => + //{ + // var mCache = x.GetRequiredService(); + // var mOptions = x.GetRequiredService>(); + // var mLog = x.GetRequiredService(); + // return new DefaultInMemoryCachingProvider(name, mCache, mOptions, mLog); + //}); + + return services; + } + + + + + /// + /// Adds the default in-memory cache. + /// + /// The default in-memory cache. + /// Services. + public static IServiceCollection AddDefaultInMemoryCacheWithFactory(this IServiceCollection services,string providerName = EasyCachingConstValue.DefaultName) + { + var option = new InMemoryOptions(); + + return services.AddDefaultInMemoryCacheWithFactory(providerName, x => + { + x.CachingProviderType = option.CachingProviderType; + x.MaxRdSecond = option.MaxRdSecond; + x.Order = option.Order; + }); + } + + /// + /// Adds the default in-memory cache. + /// + /// The default in-memory cache. + /// Services. + /// Option. + public static IServiceCollection AddDefaultInMemoryCacheWithFactory( + this IServiceCollection services, + string providerName, + Action providerAction) + { + ArgumentCheck.NotNull(services, nameof(services)); + ArgumentCheck.NotNull(providerAction, nameof(providerAction)); + + services.AddOptions(); + services.Configure(providerAction); + + services.AddMemoryCache(); + + services.AddSingleton(); + //services.AddSingleton(); + services.AddSingleton(x=> + { + var mCache = x.GetRequiredService(); + var mOptions = x.GetRequiredService>(); + var mLog = x.GetRequiredService(); + return new DefaultInMemoryCachingProvider(providerName, mCache, mOptions,mLog); + }); return services; } From 5c1c83c04f4c4d6cd3c006820355881f97dca4af Mon Sep 17 00:00:00 2001 From: catcherwong Date: Mon, 8 Oct 2018 22:29:39 +0800 Subject: [PATCH 04/22] :sparkles: Named Provider --- EasyCaching.sln | 4 +- .../Controllers/CusController.cs | 33 +++++- sample/EasyCaching.Demo.Providers/Startup.cs | 22 +++- src/EasyCaching.Core/EasyCachingConstValue.cs | 8 +- .../IEasyCachingProviderFactory.cs | 2 + .../HybridCachingProvider.cs | 2 + .../DefaultInMemoryCachingProvider.cs | 18 ++- ...nMemoryCacheServiceCollectionExtensions.cs | 9 +- .../DefaultMemcachedCachingProvider.cs | 2 + .../DefaultRedisCachingProvider.cs | 26 +++++ .../IRedisDatabaseProvider.cs | 2 + .../RedisCacheServiceCollectionExtensions.cs | 109 +++++++++++++++++- .../RedisDatabaseProvider.cs | 11 ++ .../DefaultSQLiteCachingProvider.cs | 2 + .../CachingTests/HybridCachingTest.cs | 4 +- .../CachingTests/MemoryCachingProviderTest.cs | 87 ++++++++++++++ 16 files changed, 316 insertions(+), 25 deletions(-) diff --git a/EasyCaching.sln b/EasyCaching.sln index 7b9e10c7..d6112bb9 100644 --- a/EasyCaching.sln +++ b/EasyCaching.sln @@ -41,9 +41,9 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EasyCaching.HybridCache", " EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EasyCaching.Demo.ResponseCaching", "sample\EasyCaching.Demo.ResponseCaching\EasyCaching.Demo.ResponseCaching.csproj", "{76A5C2E3-6525-45A0-9CE7-649F3235A443}" EndProject -Project("{9344BDBB-3E7F-41FC-A0DD-8665D75EE146}") = "EasyCaching.UnitTests", "test\EasyCaching.UnitTests\EasyCaching.UnitTests.csproj", "{2A8D7103-DF64-47B6-A406-8F8559AF7E7F}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EasyCaching.UnitTests", "test\EasyCaching.UnitTests\EasyCaching.UnitTests.csproj", "{2A8D7103-DF64-47B6-A406-8F8559AF7E7F}" EndProject -Project("{9344BDBB-3E7F-41FC-A0DD-8665D75EE146}") = "EasyCaching.PerformanceTests", "test\EasyCaching.PerformanceTests\EasyCaching.PerformanceTests.csproj", "{6EBE36A2-F128-4C63-B90A-B700D8C2F2E8}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EasyCaching.PerformanceTests", "test\EasyCaching.PerformanceTests\EasyCaching.PerformanceTests.csproj", "{6EBE36A2-F128-4C63-B90A-B700D8C2F2E8}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution diff --git a/sample/EasyCaching.Demo.Providers/Controllers/CusController.cs b/sample/EasyCaching.Demo.Providers/Controllers/CusController.cs index 7f3357cd..fd8429a2 100644 --- a/sample/EasyCaching.Demo.Providers/Controllers/CusController.cs +++ b/sample/EasyCaching.Demo.Providers/Controllers/CusController.cs @@ -12,17 +12,40 @@ public class CusController : Controller public CusController(IEasyCachingProviderFactory factory) { this._factory = factory; - } - - // GET api/cus/get?name=Default + } + + // GET api/cus/inmem?name=Default [HttpGet] - [Route("get")] - public string Get(string name = "Default") + [Route("inmem")] + public string Get(string name = EasyCachingConstValue.DefaultInMemoryName) { var provider = _factory.GetCachingProvider(name); var val = name.Equals("cus") ? "cus" : "default"; var res = provider.Get("demo", () => val, TimeSpan.FromMinutes(1)); return $"cached value : {res}"; } + + // GET api/cus/redis?name=Default + [HttpGet] + [Route("redis")] + public string GetRedis(string name = EasyCachingConstValue.DefaultRedisName) + { + var provider = _factory.GetCachingProvider(name); + var val = name.Equals("redis1") ? $"redis1-{Guid.NewGuid()}" : $"redis2-{Guid.NewGuid()}"; + var res = provider.Get("named-provider", () => val, TimeSpan.FromMinutes(1)); + return $"cached value : {res}"; + } + + + // GET api/cus/com?name=Default + [HttpGet] + [Route("com")] + public string GetCom(string name = "cus") + { + var provider = _factory.GetCachingProvider(name); + var val = $"{name}-{Guid.NewGuid()}"; + var res = provider.Get("named-provider2", () => val, TimeSpan.FromMinutes(1)); + return $"cached value : {res}"; + } } } diff --git a/sample/EasyCaching.Demo.Providers/Startup.cs b/sample/EasyCaching.Demo.Providers/Startup.cs index c389071a..e4a6562b 100644 --- a/sample/EasyCaching.Demo.Providers/Startup.cs +++ b/sample/EasyCaching.Demo.Providers/Startup.cs @@ -3,10 +3,10 @@ using EasyCaching.Core; using EasyCaching.Core.Internal; using EasyCaching.InMemory; - //using EasyCaching.HybridCache; - //using EasyCaching.Memcached; - //using EasyCaching.Redis; - //using EasyCaching.SQLite; + using EasyCaching.HybridCache; + using EasyCaching.Memcached; + using EasyCaching.Redis; + using EasyCaching.SQLite; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; @@ -31,7 +31,7 @@ public void ConfigureServices(IServiceCollection services) //1. Important step for using InMemory Cache //services.AddDefaultInMemoryCache(); - services.AddDefaultInMemoryCacheWithFactory(); + //services.AddDefaultInMemoryCacheWithFactory(); services.AddDefaultInMemoryCacheWithFactory("cus"); //services.AddDefaultInMemoryCache(Configuration); @@ -51,6 +51,18 @@ public void ConfigureServices(IServiceCollection services) // option.DBConfig.Password = ""; //}); + services.AddDefaultRedisCacheWithFactory("redis1",option => + { + option.DBConfig.Endpoints.Add(new ServerEndPoint("127.0.0.1", 6379)); + option.DBConfig.Password = ""; + }); + + services.AddDefaultRedisCacheWithFactory("redis2", option => + { + option.DBConfig.Endpoints.Add(new ServerEndPoint("127.0.0.1", 6380)); + option.DBConfig.Password = ""; + }); + //services.AddDefaultRedisCache(Configuration); ////4. Important step for using SQLite Cache diff --git a/src/EasyCaching.Core/EasyCachingConstValue.cs b/src/EasyCaching.Core/EasyCachingConstValue.cs index d3a49c3d..b8b72656 100644 --- a/src/EasyCaching.Core/EasyCachingConstValue.cs +++ b/src/EasyCaching.Core/EasyCachingConstValue.cs @@ -30,6 +30,12 @@ public class EasyCachingConstValue /// public const string InMemorySection = "easycaching:inmemory"; - public const string DefaultName = "Default"; + public const string DefaultInMemoryName = "DefaultInMemory"; + + public const string DefaultRedisName = "DefaultRedis"; + + public const string DefaultMemcachedName = "DefaultMemcached"; + + public const string DefaultSQLiteName = "DefaultSQLite"; } } diff --git a/src/EasyCaching.Core/IEasyCachingProviderFactory.cs b/src/EasyCaching.Core/IEasyCachingProviderFactory.cs index e5bc443c..dd5094a9 100644 --- a/src/EasyCaching.Core/IEasyCachingProviderFactory.cs +++ b/src/EasyCaching.Core/IEasyCachingProviderFactory.cs @@ -23,6 +23,8 @@ public IEasyCachingProvider GetCachingProvider(string name) var provider = _cachingProviders.FirstOrDefault(x => x.Name.Equals(name)); + if (provider == null) throw new System.ArgumentException("can not find a match caching provider!"); + return provider; } } diff --git a/src/EasyCaching.HybridCache/HybridCachingProvider.cs b/src/EasyCaching.HybridCache/HybridCachingProvider.cs index b78f6551..b5eef08f 100644 --- a/src/EasyCaching.HybridCache/HybridCachingProvider.cs +++ b/src/EasyCaching.HybridCache/HybridCachingProvider.cs @@ -44,6 +44,8 @@ public class HybridCachingProvider : IHybridCachingProvider public CacheStats CacheStats => throw new NotImplementedException(); + public string Name => throw new NotImplementedException(); + /// /// Initializes a new instance of the class. /// diff --git a/src/EasyCaching.InMemory/DefaultInMemoryCachingProvider.cs b/src/EasyCaching.InMemory/DefaultInMemoryCachingProvider.cs index 37c19efa..20222b19 100644 --- a/src/EasyCaching.InMemory/DefaultInMemoryCachingProvider.cs +++ b/src/EasyCaching.InMemory/DefaultInMemoryCachingProvider.cs @@ -392,7 +392,8 @@ public void RemoveByPrefix(string prefix) { foreach (var item in keys) { - this.Remove(item); + _cache.Remove(item); + _cacheKeys.TryRemove(item); } } } @@ -417,7 +418,14 @@ public async Task RemoveByPrefixAsync(string prefix) { var tasks = new List(); foreach (var item in keys) - tasks.Add(RemoveAsync(item)); + { + tasks.Add(Task.Run(() => + { + _cache.Remove(item); + _cacheKeys.TryRemove(item); + })); + } + //tasks.Add(RemoveAsync(item)); await Task.WhenAll(tasks); } @@ -525,7 +533,7 @@ public IDictionary> GetByPrefix(string prefix)// where { foreach (var item in keys) { - map[item] = this.Get(item); + map[item] = this.Get(item.Substring(Name.Length + 1, item.Length - Name.Length - 1)); } } return map; @@ -553,7 +561,7 @@ public Task>> GetByPrefixAsync(string prefi if (keys.Any()) { foreach (string key in keys) - map[key] = GetAsync(key); + map[key] = GetAsync(key.Substring(Name.Length + 1, key.Length - Name.Length - 1)); } return Task.WhenAll(map.Values) @@ -597,7 +605,7 @@ public async Task RemoveAllAsync(IEnumerable cacheKeys) var tasks = new List(); foreach (var item in cacheKeys.Distinct()) { - tasks.Add(RemoveAsync(item)); + tasks.Add(RemoveAsync(item.Substring(Name.Length + 1, item.Length - Name.Length - 1 ))); } await Task.WhenAll(tasks); diff --git a/src/EasyCaching.InMemory/InMemoryCacheServiceCollectionExtensions.cs b/src/EasyCaching.InMemory/InMemoryCacheServiceCollectionExtensions.cs index e9352dbc..c0f0dcb9 100644 --- a/src/EasyCaching.InMemory/InMemoryCacheServiceCollectionExtensions.cs +++ b/src/EasyCaching.InMemory/InMemoryCacheServiceCollectionExtensions.cs @@ -103,7 +103,7 @@ public static IServiceCollection AddDefaultInMemoryCache( /// /// The default in-memory cache. /// Services. - public static IServiceCollection AddDefaultInMemoryCacheWithFactory(this IServiceCollection services,string providerName = EasyCachingConstValue.DefaultName) + public static IServiceCollection AddDefaultInMemoryCacheWithFactory(this IServiceCollection services,string providerName = EasyCachingConstValue.DefaultInMemoryName) { var option = new InMemoryOptions(); @@ -139,9 +139,10 @@ public static IServiceCollection AddDefaultInMemoryCacheWithFactory( services.AddSingleton(x=> { var mCache = x.GetRequiredService(); - var mOptions = x.GetRequiredService>(); - var mLog = x.GetRequiredService(); - return new DefaultInMemoryCachingProvider(providerName, mCache, mOptions,mLog); + var options = x.GetRequiredService>(); + //ILoggerFactory can be null + var factory = x.GetService(); + return new DefaultInMemoryCachingProvider(providerName, mCache, options,factory); }); return services; diff --git a/src/EasyCaching.Memcached/DefaultMemcachedCachingProvider.cs b/src/EasyCaching.Memcached/DefaultMemcachedCachingProvider.cs index 11e1a951..ee5bf408 100644 --- a/src/EasyCaching.Memcached/DefaultMemcachedCachingProvider.cs +++ b/src/EasyCaching.Memcached/DefaultMemcachedCachingProvider.cs @@ -60,6 +60,8 @@ public class DefaultMemcachedCachingProvider : IEasyCachingProvider public CacheStats CacheStats => _cacheStats; + public string Name => throw new NotImplementedException(); + /// /// Initializes a new instance of the class. /// diff --git a/src/EasyCaching.Redis/DefaultRedisCachingProvider.cs b/src/EasyCaching.Redis/DefaultRedisCachingProvider.cs index f08b9e36..a04a63ef 100644 --- a/src/EasyCaching.Redis/DefaultRedisCachingProvider.cs +++ b/src/EasyCaching.Redis/DefaultRedisCachingProvider.cs @@ -73,12 +73,17 @@ public class DefaultRedisCachingProvider : IEasyCachingProvider public CacheStats CacheStats => _cacheStats; + private readonly string _name; + + public string Name => this._name; + /// /// Initializes a new instance of the class. /// /// DB Provider. /// Serializer. public DefaultRedisCachingProvider( + string name, IRedisDatabaseProvider dbProvider, IEasyCachingSerializer serializer, IOptionsMonitor options, @@ -94,6 +99,27 @@ public DefaultRedisCachingProvider( this._cache = _dbProvider.GetDatabase(); this._servers = _dbProvider.GetServerList(); this._cacheStats = new CacheStats(); + this._name = name; + } + + public DefaultRedisCachingProvider( + string name, + IEnumerable dbProviders, + IEasyCachingSerializer serializer, + IOptionsMonitor options, + ILoggerFactory loggerFactory = null) + { + ArgumentCheck.NotNullAndCountGTZero(dbProviders, nameof(dbProviders)); + ArgumentCheck.NotNull(serializer, nameof(serializer)); + + this._dbProvider = dbProviders.FirstOrDefault(x=>x.DBProviderName.Equals(name)); + this._serializer = serializer; + this._options = options.CurrentValue; + this._logger = loggerFactory?.CreateLogger(); + this._cache = _dbProvider.GetDatabase(); + this._servers = _dbProvider.GetServerList(); + this._cacheStats = new CacheStats(); + this._name = name; } /// diff --git a/src/EasyCaching.Redis/IRedisDatabaseProvider.cs b/src/EasyCaching.Redis/IRedisDatabaseProvider.cs index bbb9af27..2d51cf46 100644 --- a/src/EasyCaching.Redis/IRedisDatabaseProvider.cs +++ b/src/EasyCaching.Redis/IRedisDatabaseProvider.cs @@ -19,5 +19,7 @@ public interface IRedisDatabaseProvider /// /// The server list. IEnumerable GetServerList(); + + string DBProviderName { get; } } } diff --git a/src/EasyCaching.Redis/RedisCacheServiceCollectionExtensions.cs b/src/EasyCaching.Redis/RedisCacheServiceCollectionExtensions.cs index 4bb61ee7..ece61b79 100644 --- a/src/EasyCaching.Redis/RedisCacheServiceCollectionExtensions.cs +++ b/src/EasyCaching.Redis/RedisCacheServiceCollectionExtensions.cs @@ -5,6 +5,8 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; + using Microsoft.Extensions.Logging; + using Microsoft.Extensions.Options; using System; /// @@ -32,7 +34,7 @@ public static IServiceCollection AddDefaultRedisCache( services.AddSingleton(); return services; - } + } /// /// Adds the default redis cache. @@ -83,5 +85,110 @@ public static IServiceCollection AddDefaultRedisCache( return services; } + + + /// + /// Adds the default redis cache. + /// + /// The default redis cache. + /// Services. + /// Options Action. + public static IServiceCollection AddDefaultRedisCacheWithFactory( + this IServiceCollection services, + string name, + Action providerAction) + { + ArgumentCheck.NotNull(services, nameof(services)); + + services.AddOptions(); + //services.Configure(providerAction); + + services.Configure(name, providerAction); + + services.AddSingleton(); + services.TryAddSingleton(); + services.AddSingleton(x => + { + var optionsMon = x.GetRequiredService>(); + var options = optionsMon.Get(name); + return new RedisDatabaseProvider(name, options); + }); + //services.AddSingleton(); + services.AddSingleton(x => + { + var dbProviders = x.GetServices(); + var serializer = x.GetRequiredService(); + var options = x.GetRequiredService>(); + var factory = x.GetRequiredService(); + return new DefaultRedisCachingProvider(name, dbProviders, serializer, options, factory); + }); + + return services; + } + + /// + /// Adds the default redis cache. + /// + /// + /// + /// + /// The default redis cache. + /// Services. + /// Configuration. + public static IServiceCollection AddDefaultRedisCacheWithFactory( + this IServiceCollection services, + string name, + IConfiguration configuration) + { + var cacheConfig = configuration.GetSection(EasyCachingConstValue.RedisSection); + services.Configure(name,cacheConfig); + + //var redisConfig = configuration.GetSection(EasyCachingConstValue.ConfigChildSection); + //services.Configure(redisConfig); + + services.AddSingleton(); + services.TryAddSingleton(); + services.AddSingleton(x => + { + var optionsMon = x.GetRequiredService>(); + var options = optionsMon.Get(name); + return new RedisDatabaseProvider(name, options); + }); + //services.AddSingleton(); + services.AddSingleton(x => + { + var dbProviders = x.GetServices(); + var serializer = x.GetRequiredService(); + var options = x.GetRequiredService>(); + var factory = x.GetRequiredService(); + return new DefaultRedisCachingProvider(name, dbProviders, serializer, options, factory); + }); + + return services; + } + } } diff --git a/src/EasyCaching.Redis/RedisDatabaseProvider.cs b/src/EasyCaching.Redis/RedisDatabaseProvider.cs index d34b2d0b..af490aa4 100644 --- a/src/EasyCaching.Redis/RedisDatabaseProvider.cs +++ b/src/EasyCaching.Redis/RedisDatabaseProvider.cs @@ -32,6 +32,17 @@ public RedisDatabaseProvider(IOptionsMonitor options) _connectionMultiplexer = new Lazy(CreateConnectionMultiplexer); } + public RedisDatabaseProvider(string name,RedisOptions options) + { + _options = options.DBConfig; + _connectionMultiplexer = new Lazy(CreateConnectionMultiplexer); + _name = name; + } + + private readonly string _name; + + public string DBProviderName => this._name; + /// /// Gets the database connection. /// diff --git a/src/EasyCaching.SQLite/DefaultSQLiteCachingProvider.cs b/src/EasyCaching.SQLite/DefaultSQLiteCachingProvider.cs index ddd4c2df..526f70c7 100644 --- a/src/EasyCaching.SQLite/DefaultSQLiteCachingProvider.cs +++ b/src/EasyCaching.SQLite/DefaultSQLiteCachingProvider.cs @@ -80,6 +80,8 @@ public DefaultSQLiteCachingProvider( public CacheStats CacheStats => _cacheStats; + public string Name => throw new NotImplementedException(); + /// /// Exists the specified cacheKey. /// diff --git a/test/EasyCaching.UnitTests/CachingTests/HybridCachingTest.cs b/test/EasyCaching.UnitTests/CachingTests/HybridCachingTest.cs index 6432f1db..0941ad6e 100644 --- a/test/EasyCaching.UnitTests/CachingTests/HybridCachingTest.cs +++ b/test/EasyCaching.UnitTests/CachingTests/HybridCachingTest.cs @@ -30,8 +30,8 @@ public HybridCachingTest() var providers = new List { - new DefaultInMemoryCachingProvider(new MemoryCache(new MemoryCacheOptions()), new TestOptionMonitorWrapper(new InMemoryOptions())), - new DefaultRedisCachingProvider(fakeDbProvider, serializer, new TestOptionMonitorWrapper(new RedisOptions())) + new DefaultInMemoryCachingProvider("de",new MemoryCache(new MemoryCacheOptions()), new TestOptionMonitorWrapper(new InMemoryOptions())), + new DefaultRedisCachingProvider("re",fakeDbProvider, serializer, new TestOptionMonitorWrapper(new RedisOptions())) }; _provider = new HybridCachingProvider(providers); diff --git a/test/EasyCaching.UnitTests/CachingTests/MemoryCachingProviderTest.cs b/test/EasyCaching.UnitTests/CachingTests/MemoryCachingProviderTest.cs index 61f9fbb1..3f9bf301 100644 --- a/test/EasyCaching.UnitTests/CachingTests/MemoryCachingProviderTest.cs +++ b/test/EasyCaching.UnitTests/CachingTests/MemoryCachingProviderTest.cs @@ -4,6 +4,9 @@ namespace EasyCaching.UnitTests using EasyCaching.InMemory; using Microsoft.Extensions.DependencyInjection; using System; + using System.Collections.Generic; + using System.Linq; + using System.Threading.Tasks; using Xunit; public class MemoryCachingProviderTest : BaseCachingProviderTest @@ -23,4 +26,88 @@ public void Deault_MaxRdSecond_Should_Be_120() Assert.Equal(120, _provider.MaxRdSecond); } } + + public class MemoryCachingProviderWithFactoryTest : BaseCachingProviderTest + { + private readonly IEasyCachingProvider _secondProvider; + + private const string SECOND_PROVIDER_NAME = "second"; + + public MemoryCachingProviderWithFactoryTest() + { + IServiceCollection services = new ServiceCollection(); + services.AddDefaultInMemoryCacheWithFactory(); + services.AddDefaultInMemoryCacheWithFactory(SECOND_PROVIDER_NAME); + IServiceProvider serviceProvider = services.BuildServiceProvider(); + var factory = serviceProvider.GetService(); + _provider = factory.GetCachingProvider(EasyCachingConstValue.DefaultInMemoryName); + _secondProvider = factory.GetCachingProvider(SECOND_PROVIDER_NAME); + _defaultTs = TimeSpan.FromSeconds(30); + } + + + [Fact] + public void Multi_Instance_Set_And_Get_Should_Succeed() + { + var cacheKey1 = "named-provider-1"; + var cacheKey2 = "named-provider-2"; + + var value1 = Guid.NewGuid().ToString(); + var value2 = Guid.NewGuid().ToString("N"); + + _provider.Set(cacheKey1, value1, _defaultTs); + _secondProvider.Set(cacheKey2, value2, _defaultTs); + + var p1 = _provider.Get(cacheKey1); + var p2 = _provider.Get(cacheKey2); + + var s1 = _secondProvider.Get(cacheKey1); + var s2 = _secondProvider.Get(cacheKey2); + + Assert.Equal(value1, p1.Value); + Assert.False(p2.HasValue); + + Assert.False(s1.HasValue); + Assert.Equal(value2, s2.Value); + } + + + [Fact] + protected override void GetByPrefix_Should_Succeed() + { + _provider.RemoveAll(new List { "getbyprefix:key:1", "getbyprefix:key:2" }); + var dict = GetMultiDict("getbyprefix:"); + + _provider.SetAll(dict, _defaultTs); + + string prefix = "getbyprefix:key:"; + + var res = _provider.GetByPrefix(prefix); + + Assert.Equal(2, res.Count); + Assert.Contains($"{EasyCachingConstValue.DefaultInMemoryName}-getbyprefix:key:1", res.Select(x => x.Key)); + Assert.Contains($"{EasyCachingConstValue.DefaultInMemoryName}-getbyprefix:key:2", res.Select(x => x.Key)); + Assert.Equal("value1", res.Where(x => x.Key == $"{EasyCachingConstValue.DefaultInMemoryName}-getbyprefix:key:1").Select(x => x.Value).FirstOrDefault().Value); + Assert.Equal("value2", res.Where(x => x.Key == $"{EasyCachingConstValue.DefaultInMemoryName}-getbyprefix:key:2").Select(x => x.Value).FirstOrDefault().Value); + } + + [Fact] + protected override async Task GetByPrefixAsync_Should_Succeed() + { + _provider.RemoveAll(new List { "getbyprefixasync:key:1", "getbyprefixasync:key:2" }); + var dict = GetMultiDict("getbyprefixasync:"); + + _provider.SetAll(dict, _defaultTs); + + string prefix = "getbyprefixasync:key:"; + + var res = await _provider.GetByPrefixAsync(prefix); + + Assert.Equal(2, res.Count); + Assert.Contains($"{EasyCachingConstValue.DefaultInMemoryName}-getbyprefixasync:key:1", res.Select(x => x.Key)); + Assert.Contains($"{EasyCachingConstValue.DefaultInMemoryName}-getbyprefixasync:key:2", res.Select(x => x.Key)); + Assert.Equal("value1", res.Where(x => x.Key == $"{EasyCachingConstValue.DefaultInMemoryName}-getbyprefixasync:key:1").Select(x => x.Value).FirstOrDefault().Value); + Assert.Equal("value2", res.Where(x => x.Key == $"{EasyCachingConstValue.DefaultInMemoryName}-getbyprefixasync:key:2").Select(x => x.Value).FirstOrDefault().Value); + } + } } From fcf6073ba48c00333f2cdf0d77d1514e42f53494 Mon Sep 17 00:00:00 2001 From: catcherwong Date: Mon, 8 Oct 2018 22:43:39 +0800 Subject: [PATCH 05/22] :construction: Named Provider Tests. --- src/EasyCaching.Redis/DefaultRedisCachingProvider.cs | 4 ++-- test/EasyCaching.UnitTests/CachingTests/HybridCachingTest.cs | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/EasyCaching.Redis/DefaultRedisCachingProvider.cs b/src/EasyCaching.Redis/DefaultRedisCachingProvider.cs index a04a63ef..3b498ffb 100644 --- a/src/EasyCaching.Redis/DefaultRedisCachingProvider.cs +++ b/src/EasyCaching.Redis/DefaultRedisCachingProvider.cs @@ -83,7 +83,7 @@ public class DefaultRedisCachingProvider : IEasyCachingProvider /// DB Provider. /// Serializer. public DefaultRedisCachingProvider( - string name, + //string name, IRedisDatabaseProvider dbProvider, IEasyCachingSerializer serializer, IOptionsMonitor options, @@ -99,7 +99,7 @@ public DefaultRedisCachingProvider( this._cache = _dbProvider.GetDatabase(); this._servers = _dbProvider.GetServerList(); this._cacheStats = new CacheStats(); - this._name = name; + //this._name = name; } public DefaultRedisCachingProvider( diff --git a/test/EasyCaching.UnitTests/CachingTests/HybridCachingTest.cs b/test/EasyCaching.UnitTests/CachingTests/HybridCachingTest.cs index 0941ad6e..b28458ad 100644 --- a/test/EasyCaching.UnitTests/CachingTests/HybridCachingTest.cs +++ b/test/EasyCaching.UnitTests/CachingTests/HybridCachingTest.cs @@ -31,7 +31,7 @@ public HybridCachingTest() var providers = new List { new DefaultInMemoryCachingProvider("de",new MemoryCache(new MemoryCacheOptions()), new TestOptionMonitorWrapper(new InMemoryOptions())), - new DefaultRedisCachingProvider("re",fakeDbProvider, serializer, new TestOptionMonitorWrapper(new RedisOptions())) + new DefaultRedisCachingProvider(fakeDbProvider, serializer, new TestOptionMonitorWrapper(new RedisOptions())) }; _provider = new HybridCachingProvider(providers); From 2deae20efc52588b33af5bd4a8b132c27a744a7a Mon Sep 17 00:00:00 2001 From: catcherwong Date: Tue, 9 Oct 2018 22:41:32 +0800 Subject: [PATCH 06/22] :construction: Redis Named Provider Tests. --- .../DefaultInMemoryCachingProvider.cs | 28 ++++++++- .../DefaultRedisCachingProvider.cs | 30 +++++---- .../CachingTests/HybridCachingTest.cs | 3 +- .../CachingTests/RedisCachingProviderTest.cs | 62 +++++++++++++++++++ 4 files changed, 108 insertions(+), 15 deletions(-) diff --git a/src/EasyCaching.InMemory/DefaultInMemoryCachingProvider.cs b/src/EasyCaching.InMemory/DefaultInMemoryCachingProvider.cs index 20222b19..045d375c 100644 --- a/src/EasyCaching.InMemory/DefaultInMemoryCachingProvider.cs +++ b/src/EasyCaching.InMemory/DefaultInMemoryCachingProvider.cs @@ -69,11 +69,12 @@ public class DefaultInMemoryCachingProvider : IEasyCachingProvider public string Name => _name; /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// - /// Microsoft MemoryCache. + /// Cache. + /// Options. + /// Logger factory. public DefaultInMemoryCachingProvider( - string name, IMemoryCache cache, IOptionsMonitor options, ILoggerFactory loggerFactory = null) @@ -83,6 +84,27 @@ public DefaultInMemoryCachingProvider( this._logger = loggerFactory?.CreateLogger(); this._cacheKeys = new ConcurrentCollections.ConcurrentHashSet(); + this._cacheStats = new CacheStats(); + } + + /// + /// Initializes a new instance of the class. + /// + /// Name. + /// Cache. + /// Options. + /// Logger factory. + public DefaultInMemoryCachingProvider( + string name, + IMemoryCache cache, + IOptionsMonitor options, + ILoggerFactory loggerFactory = null) + { + this._cache = cache; + this._options = options.CurrentValue; + this._logger = loggerFactory?.CreateLogger(); + this._cacheKeys = new ConcurrentCollections.ConcurrentHashSet(); + this._cacheStats = new CacheStats(); this._name = name; } diff --git a/src/EasyCaching.Redis/DefaultRedisCachingProvider.cs b/src/EasyCaching.Redis/DefaultRedisCachingProvider.cs index 3b498ffb..3470085d 100644 --- a/src/EasyCaching.Redis/DefaultRedisCachingProvider.cs +++ b/src/EasyCaching.Redis/DefaultRedisCachingProvider.cs @@ -80,10 +80,11 @@ public class DefaultRedisCachingProvider : IEasyCachingProvider /// /// Initializes a new instance of the class. /// - /// DB Provider. + /// Db provider. /// Serializer. + /// Options. + /// Logger factory. public DefaultRedisCachingProvider( - //string name, IRedisDatabaseProvider dbProvider, IEasyCachingSerializer serializer, IOptionsMonitor options, @@ -99,9 +100,16 @@ public DefaultRedisCachingProvider( this._cache = _dbProvider.GetDatabase(); this._servers = _dbProvider.GetServerList(); this._cacheStats = new CacheStats(); - //this._name = name; } + /// + /// Initializes a new instance of the class. + /// + /// Name. + /// Db providers. + /// Serializer. + /// Options. + /// Logger factory. public DefaultRedisCachingProvider( string name, IEnumerable dbProviders, @@ -112,7 +120,7 @@ public DefaultRedisCachingProvider( ArgumentCheck.NotNullAndCountGTZero(dbProviders, nameof(dbProviders)); ArgumentCheck.NotNull(serializer, nameof(serializer)); - this._dbProvider = dbProviders.FirstOrDefault(x=>x.DBProviderName.Equals(name)); + this._dbProvider = dbProviders.FirstOrDefault(x => x.DBProviderName.Equals(name)); this._serializer = serializer; this._options = options.CurrentValue; this._logger = loggerFactory?.CreateLogger(); @@ -159,7 +167,7 @@ public CacheValue Get(string cacheKey, Func dataRetriever, TimeSpan exp return new CacheValue(item, true); } else - { + { return CacheValue.NoValue; } } @@ -457,7 +465,7 @@ private RedisKey[] SearchRedisKeys(string pattern) var keys = new List(); foreach (var server in _servers) - keys.AddRange(server.Keys(pattern: pattern)); + keys.AddRange(server.Keys(pattern: pattern, database: _cache.Database)); return keys.Distinct().ToArray(); @@ -511,7 +519,7 @@ public void SetAll(IDictionary values, TimeSpan expiration)// wher { ArgumentCheck.NotNegativeOrZero(expiration, nameof(expiration)); ArgumentCheck.NotNullAndCountGTZero(values, nameof(values)); - + var batch = _cache.CreateBatch(); foreach (var item in values) @@ -531,7 +539,7 @@ public async Task SetAllAsync(IDictionary values, TimeSpan expirat { ArgumentCheck.NotNegativeOrZero(expiration, nameof(expiration)); ArgumentCheck.NotNullAndCountGTZero(values, nameof(values)); - + var tasks = new List(); foreach (var item in values) @@ -684,7 +692,7 @@ public async Task RemoveAllAsync(IEnumerable cacheKeys) /// Prefix. public int GetCount(string prefix = "") { - if(string.IsNullOrWhiteSpace(prefix)) + if (string.IsNullOrWhiteSpace(prefix)) { var allCount = 0; @@ -692,9 +700,9 @@ public int GetCount(string prefix = "") allCount += (int)server.DatabaseSize(_cache.Database); return allCount; - } + } - return this.SearchRedisKeys(this.HandlePrefix(prefix)).Length; + return this.SearchRedisKeys(this.HandlePrefix(prefix)).Length; } /// diff --git a/test/EasyCaching.UnitTests/CachingTests/HybridCachingTest.cs b/test/EasyCaching.UnitTests/CachingTests/HybridCachingTest.cs index b28458ad..6e5f9998 100644 --- a/test/EasyCaching.UnitTests/CachingTests/HybridCachingTest.cs +++ b/test/EasyCaching.UnitTests/CachingTests/HybridCachingTest.cs @@ -19,6 +19,7 @@ public HybridCachingTest() RedisOptions options = new RedisOptions(); options.DBConfig.AllowAdmin = true; options.DBConfig.Endpoints.Add(new ServerEndPoint("127.0.0.1", 6379)); + options.DBConfig.Database = 6; var fakeOption = A.Fake>(); @@ -30,7 +31,7 @@ public HybridCachingTest() var providers = new List { - new DefaultInMemoryCachingProvider("de",new MemoryCache(new MemoryCacheOptions()), new TestOptionMonitorWrapper(new InMemoryOptions())), + new DefaultInMemoryCachingProvider(new MemoryCache(new MemoryCacheOptions()), new TestOptionMonitorWrapper(new InMemoryOptions())), new DefaultRedisCachingProvider(fakeDbProvider, serializer, new TestOptionMonitorWrapper(new RedisOptions())) }; diff --git a/test/EasyCaching.UnitTests/CachingTests/RedisCachingProviderTest.cs b/test/EasyCaching.UnitTests/CachingTests/RedisCachingProviderTest.cs index a6d4c501..901596b7 100644 --- a/test/EasyCaching.UnitTests/CachingTests/RedisCachingProviderTest.cs +++ b/test/EasyCaching.UnitTests/CachingTests/RedisCachingProviderTest.cs @@ -19,6 +19,7 @@ public RedisCachingProviderTest() AllowAdmin = true }; options.DBConfig.Endpoints.Add(new ServerEndPoint("127.0.0.1", 6379)); + options.DBConfig.Database = 5; }); IServiceProvider serviceProvider = services.BuildServiceProvider(); _provider = serviceProvider.GetService(); @@ -83,4 +84,65 @@ public void Use_Configuration_String_Should_Succeed() } } + + + public class RedisCachingProviderWithFactoryTest : BaseCachingProviderTest + { + private readonly IEasyCachingProvider _secondProvider; + + private const string SECOND_PROVIDER_NAME = "second"; + + public RedisCachingProviderWithFactoryTest() + { + IServiceCollection services = new ServiceCollection(); + services.AddDefaultRedisCacheWithFactory(EasyCachingConstValue.DefaultRedisName,options => + { + options.DBConfig = new RedisDBOptions + { + AllowAdmin = true + }; + options.DBConfig.Endpoints.Add(new ServerEndPoint("127.0.0.1", 6379)); + options.DBConfig.Database = 3; + }); + services.AddDefaultRedisCacheWithFactory(SECOND_PROVIDER_NAME, options => + { + options.DBConfig = new RedisDBOptions + { + AllowAdmin = true + }; + options.DBConfig.Endpoints.Add(new ServerEndPoint("127.0.0.1", 6379)); + options.DBConfig.Database = 4; + }); + IServiceProvider serviceProvider = services.BuildServiceProvider(); + var factory = serviceProvider.GetService(); + _provider = factory.GetCachingProvider(EasyCachingConstValue.DefaultRedisName); + _secondProvider = factory.GetCachingProvider(SECOND_PROVIDER_NAME); + _defaultTs = TimeSpan.FromSeconds(30); + } + + [Fact] + public void Multi_Instance_Set_And_Get_Should_Succeed() + { + var cacheKey1 = "named-provider-1"; + var cacheKey2 = "named-provider-2"; + + var value1 = Guid.NewGuid().ToString(); + var value2 = Guid.NewGuid().ToString("N"); + + _provider.Set(cacheKey1, value1, _defaultTs); + _secondProvider.Set(cacheKey2, value2, _defaultTs); + + var p1 = _provider.Get(cacheKey1); + var p2 = _provider.Get(cacheKey2); + + var s1 = _secondProvider.Get(cacheKey1); + var s2 = _secondProvider.Get(cacheKey2); + + Assert.Equal(value1, p1.Value); + Assert.False(p2.HasValue); + + Assert.False(s1.HasValue); + Assert.Equal(value2, s2.Value); + } + } } From 46f80794d7cedbc7adafe1148b22ec06a47ad853 Mon Sep 17 00:00:00 2001 From: catcherwong Date: Tue, 9 Oct 2018 22:48:33 +0800 Subject: [PATCH 07/22] :construction: Redis ILoggerFactory GetRequiredService -> GetService. --- src/EasyCaching.Redis/RedisCacheServiceCollectionExtensions.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/EasyCaching.Redis/RedisCacheServiceCollectionExtensions.cs b/src/EasyCaching.Redis/RedisCacheServiceCollectionExtensions.cs index ece61b79..e803e2ee 100644 --- a/src/EasyCaching.Redis/RedisCacheServiceCollectionExtensions.cs +++ b/src/EasyCaching.Redis/RedisCacheServiceCollectionExtensions.cs @@ -183,7 +183,7 @@ public static IServiceCollection AddDefaultRedisCacheWithFactory( var dbProviders = x.GetServices(); var serializer = x.GetRequiredService(); var options = x.GetRequiredService>(); - var factory = x.GetRequiredService(); + var factory = x.GetService(); return new DefaultRedisCachingProvider(name, dbProviders, serializer, options, factory); }); From 72ed9aa96efb24f37c08bae317c632fbe3e8a076 Mon Sep 17 00:00:00 2001 From: catcherwong Date: Tue, 9 Oct 2018 22:56:47 +0800 Subject: [PATCH 08/22] :construction: Redis ILoggerFactory GetRequiredService -> GetService. --- src/EasyCaching.Redis/RedisCacheServiceCollectionExtensions.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/EasyCaching.Redis/RedisCacheServiceCollectionExtensions.cs b/src/EasyCaching.Redis/RedisCacheServiceCollectionExtensions.cs index e803e2ee..2ef08cf0 100644 --- a/src/EasyCaching.Redis/RedisCacheServiceCollectionExtensions.cs +++ b/src/EasyCaching.Redis/RedisCacheServiceCollectionExtensions.cs @@ -119,7 +119,7 @@ public static IServiceCollection AddDefaultRedisCacheWithFactory( var dbProviders = x.GetServices(); var serializer = x.GetRequiredService(); var options = x.GetRequiredService>(); - var factory = x.GetRequiredService(); + var factory = x.GetService(); return new DefaultRedisCachingProvider(name, dbProviders, serializer, options, factory); }); From e36d1109c40d6ef1eae393905680f740f9000eff Mon Sep 17 00:00:00 2001 From: catcherwong Date: Wed, 10 Oct 2018 21:23:42 +0800 Subject: [PATCH 09/22] :construction: Fix UnitTests. --- .../DefaultInMemoryCachingProvider.cs | 34 ++++++++++++------- 1 file changed, 22 insertions(+), 12 deletions(-) diff --git a/src/EasyCaching.InMemory/DefaultInMemoryCachingProvider.cs b/src/EasyCaching.InMemory/DefaultInMemoryCachingProvider.cs index 045d375c..f0a98fd8 100644 --- a/src/EasyCaching.InMemory/DefaultInMemoryCachingProvider.cs +++ b/src/EasyCaching.InMemory/DefaultInMemoryCachingProvider.cs @@ -145,7 +145,7 @@ public CacheValue Get(string cacheKey, Func dataRetriever, TimeSpan exp return new CacheValue(result, true); } else - { + { return CacheValue.NoValue; } } @@ -186,7 +186,7 @@ public async Task> GetAsync(string cacheKey, Func> data return new CacheValue(result, true); } else - { + { return CacheValue.NoValue; } } @@ -553,9 +553,10 @@ public IDictionary> GetByPrefix(string prefix)// where if (keys.Any()) { - foreach (var item in keys) + foreach (var key in keys) { - map[item] = this.Get(item.Substring(Name.Length + 1, item.Length - Name.Length - 1)); + var cacheKey = string.IsNullOrWhiteSpace(_name) ? key : key.Substring(Name.Length + 1, key.Length - Name.Length - 1); + map[key] = this.Get(cacheKey); } } return map; @@ -583,7 +584,10 @@ public Task>> GetByPrefixAsync(string prefi if (keys.Any()) { foreach (string key in keys) - map[key] = GetAsync(key.Substring(Name.Length + 1, key.Length - Name.Length - 1)); + { + var cacheKey = string.IsNullOrWhiteSpace(_name) ? key : key.Substring(Name.Length + 1, key.Length - Name.Length - 1); + map[key] = GetAsync(cacheKey); + } } return Task.WhenAll(map.Values) @@ -599,14 +603,15 @@ public void RemoveAll(IEnumerable cacheKeys) { ArgumentCheck.NotNullAndCountGTZero(cacheKeys, nameof(cacheKeys)); - cacheKeys = cacheKeys.Select(x => BuildCacheKey(Name, x)); + cacheKeys = cacheKeys.Select(x => BuildCacheKey(this._name, x)); if (_options.EnableLogging) _logger?.LogInformation($"RemoveAll : cacheKeys = {string.Join(",", cacheKeys)}"); - foreach (var item in cacheKeys.Distinct()) + foreach (var key in cacheKeys.Distinct()) { - _cache.Remove(item); + var cacheKey = string.IsNullOrWhiteSpace(_name) ? key : key.Substring(Name.Length + 1, key.Length - Name.Length - 1); + Remove(cacheKey); } } @@ -625,9 +630,10 @@ public async Task RemoveAllAsync(IEnumerable cacheKeys) _logger?.LogInformation($"RemoveAllAsync : cacheKeys = {string.Join(",", cacheKeys)}"); var tasks = new List(); - foreach (var item in cacheKeys.Distinct()) + foreach (var key in cacheKeys.Distinct()) { - tasks.Add(RemoveAsync(item.Substring(Name.Length + 1, item.Length - Name.Length - 1 ))); + var cacheKey = string.IsNullOrWhiteSpace(_name) ? key : key.Substring(Name.Length + 1, key.Length - Name.Length - 1); + tasks.Add(RemoveAsync(cacheKey)); } await Task.WhenAll(tasks); @@ -653,7 +659,9 @@ public void Flush() if (_options.EnableLogging) _logger?.LogInformation("Flush"); - var cacheKeys = _cacheKeys.Where(x => x.StartsWith(Name, StringComparison.OrdinalIgnoreCase)); + var cacheKeys = string.IsNullOrWhiteSpace(_name) + ? _cacheKeys + : _cacheKeys.Where(x => x.StartsWith(_name, StringComparison.OrdinalIgnoreCase)); foreach (var item in cacheKeys) { @@ -683,7 +691,9 @@ public async Task FlushAsync() /// Cache key. private string BuildCacheKey(string prividerName, string cacheKey) { - return $"{prividerName}-{cacheKey}"; + return string.IsNullOrWhiteSpace(prividerName) + ? cacheKey + : $"{prividerName}-{cacheKey}"; } } } From 921bd61fd60b45e71e9808cbf629c1c5936e2534 Mon Sep 17 00:00:00 2001 From: catcherwong Date: Wed, 31 Oct 2018 20:58:55 +0800 Subject: [PATCH 10/22] :art: pattern matching --- .../EasyCachingInterceptor.cs | 27 +++---------------- .../EasyCachingInterceptor.cs | 18 +++++-------- 2 files changed, 10 insertions(+), 35 deletions(-) diff --git a/src/EasyCaching.Interceptor.AspectCore/EasyCachingInterceptor.cs b/src/EasyCaching.Interceptor.AspectCore/EasyCachingInterceptor.cs index 940887d7..cf65a58e 100644 --- a/src/EasyCaching.Interceptor.AspectCore/EasyCachingInterceptor.cs +++ b/src/EasyCaching.Interceptor.AspectCore/EasyCachingInterceptor.cs @@ -58,10 +58,8 @@ public async override Task Invoke(AspectContext context, AspectDelegate next) /// Next. private async Task ProceedAbleAsync(AspectContext context, AspectDelegate next) { - var attribute = context.ServiceMethod.GetCustomAttributes(true).FirstOrDefault(x => x.GetType() == typeof(EasyCachingAbleAttribute)) as EasyCachingAbleAttribute; - - if (attribute != null) - { + if (context.ServiceMethod.GetCustomAttributes(true).FirstOrDefault(x => x.GetType() == typeof(EasyCachingAbleAttribute)) is EasyCachingAbleAttribute attribute) + { var cacheKey = KeyGenerator.GetCacheKey(context.ServiceMethod, context.Parameters, attribute.CacheKeyPrefix); var cacheValue = await CacheProvider.GetAsync(cacheKey); @@ -114,9 +112,7 @@ private async Task ProceedAbleAsync(AspectContext context, AspectDelegate next) /// Context. private async Task ProcessPutAsync(AspectContext context) { - var attribute = context.ServiceMethod.GetCustomAttributes(true).FirstOrDefault(x => x.GetType() == typeof(EasyCachingPutAttribute)) as EasyCachingPutAttribute; - - if (attribute != null && context.ReturnValue != null) + if (context.ServiceMethod.GetCustomAttributes(true).FirstOrDefault(x => x.GetType() == typeof(EasyCachingPutAttribute)) is EasyCachingPutAttribute attribute && context.ReturnValue != null) { var cacheKey = KeyGenerator.GetCacheKey(context.ServiceMethod, context.Parameters, attribute.CacheKeyPrefix); @@ -142,9 +138,7 @@ private async Task ProcessPutAsync(AspectContext context) /// If set to true is before. private async Task ProcessEvictAsync(AspectContext context, bool isBefore) { - var attribute = context.ServiceMethod.GetCustomAttributes(true).FirstOrDefault(x => x.GetType() == typeof(EasyCachingEvictAttribute)) as EasyCachingEvictAttribute; - - if (attribute != null && attribute.IsBefore == isBefore) + if (context.ServiceMethod.GetCustomAttributes(true).FirstOrDefault(x => x.GetType() == typeof(EasyCachingEvictAttribute)) is EasyCachingEvictAttribute attribute && attribute.IsBefore == isBefore) { if (attribute.IsAll) { @@ -162,18 +156,5 @@ private async Task ProcessEvictAsync(AspectContext context, bool isBefore) } } } - - private static async Task InterceptAsync(Task task) - { - await task.ConfigureAwait(false); - // do the continuation work for Task... - } - - private static async Task InterceptAsync(Task task) - { - T result = await task.ConfigureAwait(false); - // do the continuation work for Task... - return result; - } } } diff --git a/src/EasyCaching.Interceptor.Castle/EasyCachingInterceptor.cs b/src/EasyCaching.Interceptor.Castle/EasyCachingInterceptor.cs index 9ff3fb9a..66bef73a 100644 --- a/src/EasyCaching.Interceptor.Castle/EasyCachingInterceptor.cs +++ b/src/EasyCaching.Interceptor.Castle/EasyCachingInterceptor.cs @@ -60,9 +60,7 @@ private void ProceedAble(IInvocation invocation) { var serviceMethod = invocation.MethodInvocationTarget ?? invocation.Method; - var attribute = serviceMethod.GetCustomAttributes(true).FirstOrDefault(x => x.GetType() == typeof(EasyCachingAbleAttribute)) as EasyCachingAbleAttribute; - - if (attribute != null) + if (serviceMethod.GetCustomAttributes(true).FirstOrDefault(x => x.GetType() == typeof(EasyCachingAbleAttribute)) is EasyCachingAbleAttribute attribute) { var cacheKey = _keyGenerator.GetCacheKey(serviceMethod, invocation.Arguments, attribute.CacheKeyPrefix); @@ -96,9 +94,7 @@ private void ProcessPut(IInvocation invocation) { var serviceMethod = invocation.MethodInvocationTarget ?? invocation.Method; - var attribute = serviceMethod.GetCustomAttributes(true).FirstOrDefault(x => x.GetType() == typeof(EasyCachingPutAttribute)) as EasyCachingPutAttribute; - - if (attribute != null && invocation.ReturnValue != null) + if (serviceMethod.GetCustomAttributes(true).FirstOrDefault(x => x.GetType() == typeof(EasyCachingPutAttribute)) is EasyCachingPutAttribute attribute && invocation.ReturnValue != null) { var cacheKey = _keyGenerator.GetCacheKey(serviceMethod, invocation.Arguments, attribute.CacheKeyPrefix); @@ -115,11 +111,9 @@ private void ProcessEvict(IInvocation invocation, bool isBefore) { var serviceMethod = invocation.MethodInvocationTarget ?? invocation.Method; - var attribute = serviceMethod.GetCustomAttributes(true).FirstOrDefault(x => x.GetType() == typeof(EasyCachingEvictAttribute)) as EasyCachingEvictAttribute; - - if (attribute != null && attribute.IsBefore == isBefore) - { - if(attribute.IsAll) + if (serviceMethod.GetCustomAttributes(true).FirstOrDefault(x => x.GetType() == typeof(EasyCachingEvictAttribute)) is EasyCachingEvictAttribute attribute && attribute.IsBefore == isBefore) + { + if (attribute.IsAll) { //If is all , clear all cached items which cachekey start with the prefix. var cacheKeyPrefix = _keyGenerator.GetCacheKeyPrefix(serviceMethod, attribute.CacheKeyPrefix); @@ -131,7 +125,7 @@ private void ProcessEvict(IInvocation invocation, bool isBefore) //If not all , just remove the cached item by its cachekey. var cacheKey = _keyGenerator.GetCacheKey(serviceMethod, invocation.Arguments, attribute.CacheKeyPrefix); - _cacheProvider.Remove(cacheKey); + _cacheProvider.Remove(cacheKey); } } } From 6ec5a5c873c88b3cebd40769aa39be071c38d4d3 Mon Sep 17 00:00:00 2001 From: catcherwong Date: Thu, 1 Nov 2018 22:23:56 +0800 Subject: [PATCH 11/22] :sparkles: SQLite Cache Named provider --- src/EasyCaching.SQLite/ConstSQL.cs | 27 +++--- .../DefaultSQLiteCachingProvider.cs | 71 +++++++++----- .../ISQLiteDatabaseProvider.cs | 2 + .../SQLiteCacheServiceCollectionExtensions.cs | 92 +++++++++++++++++++ .../SQLiteDatabaseProvider.cs | 11 +++ .../CachingTests/SQLiteCachingTest.cs | 76 +++++++++++++++ 6 files changed, 246 insertions(+), 33 deletions(-) diff --git a/src/EasyCaching.SQLite/ConstSQL.cs b/src/EasyCaching.SQLite/ConstSQL.cs index 035ee888..e58b9013 100644 --- a/src/EasyCaching.SQLite/ConstSQL.cs +++ b/src/EasyCaching.SQLite/ConstSQL.cs @@ -9,13 +9,15 @@ public static class ConstSQL /// The setsql. /// public const string SETSQL = @" - DELETE FROM [easycaching] WHERE [cachekey] = @cachekey; + DELETE FROM [easycaching] WHERE [cachekey] = @cachekey AND [name]=@name; INSERT INTO [easycaching] - ([cachekey] + ([name] + ,[cachekey] ,[cachevalue] ,[expiration]) VALUES - (@cachekey + (@name + ,@cachekey ,@cachevalue ,(select strftime('%s','now')) + @expiration);"; @@ -24,63 +26,64 @@ INSERT INTO [easycaching] /// public const string GETSQL = @"SELECT [cachevalue] FROM [easycaching] - WHERE [cachekey] = @cachekey AND [expiration] > strftime('%s','now')"; + WHERE [cachekey] = @cachekey AND [name]=@name AND [expiration] > strftime('%s','now')"; /// /// The getallsql. /// public const string GETALLSQL = @"SELECT [cachekey],[cachevalue] FROM [easycaching] - WHERE [cachekey] IN @cachekey AND [expiration] > strftime('%s','now')"; + WHERE [cachekey] IN @cachekey AND [name]=@name AND [expiration] > strftime('%s','now')"; /// /// The getbyprefixsql. /// public const string GETBYPREFIXSQL = @"SELECT [cachekey],[cachevalue] FROM [easycaching] - WHERE [cachekey] LIKE @cachekey AND [expiration] > strftime('%s','now')"; + WHERE [cachekey] LIKE @cachekey AND [name]=@name AND [expiration] > strftime('%s','now')"; /// /// The removesql. /// - public const string REMOVESQL = @"DELETE FROM [easycaching] WHERE [cachekey] = @cachekey "; + public const string REMOVESQL = @"DELETE FROM [easycaching] WHERE [cachekey] = @cachekey AND [name] = @name "; /// /// The removebyprefixsql. /// - public const string REMOVEBYPREFIXSQL = @"DELETE FROM [easycaching] WHERE [cachekey] like @cachekey "; + public const string REMOVEBYPREFIXSQL = @"DELETE FROM [easycaching] WHERE [cachekey] like @cachekey AND [name]=@name"; /// /// The existssql. /// public const string EXISTSSQL = @"SELECT COUNT(1) FROM [easycaching] - WHERE [cachekey] = @cachekey AND [expiration] > strftime('%s','now')"; + WHERE [cachekey] = @cachekey AND [name]=@name AND [expiration] > strftime('%s','now')"; /// /// The countallsql. /// public const string COUNTALLSQL = @"SELECT COUNT(1) FROM [easycaching] - WHERE [expiration] > strftime('%s','now')"; + WHERE [expiration] > strftime('%s','now') AND [name]=@name"; /// /// The countprefixsql. /// public const string COUNTPREFIXSQL = @"SELECT COUNT(1) FROM [easycaching] - WHERE [cachekey] like @cachekey AND [expiration] > strftime('%s','now')"; + WHERE [cachekey] like @cachekey AND [name]=@name AND [expiration] > strftime('%s','now')"; /// /// The flushsql. /// - public const string FLUSHSQL = @"DELETE FROM [easycaching]"; + public const string FLUSHSQL = @"DELETE FROM [easycaching] WHERE [name]=@name"; /// /// The createsql. /// public const string CREATESQL = @"CREATE TABLE IF NOT EXISTS [easycaching] ( [ID] INTEGER PRIMARY KEY + , [name] TEXT , [cachekey] TEXT , [cachevalue] TEXT , [expiration] INTEGER)"; diff --git a/src/EasyCaching.SQLite/DefaultSQLiteCachingProvider.cs b/src/EasyCaching.SQLite/DefaultSQLiteCachingProvider.cs index 526f70c7..31eae35e 100644 --- a/src/EasyCaching.SQLite/DefaultSQLiteCachingProvider.cs +++ b/src/EasyCaching.SQLite/DefaultSQLiteCachingProvider.cs @@ -36,6 +36,8 @@ public class DefaultSQLiteCachingProvider : IEasyCachingProvider /// private readonly SqliteConnection _cache; + private readonly string _name= EasyCachingConstValue.DefaultSQLiteName; + /// /// Initializes a new instance of the class. /// @@ -52,6 +54,20 @@ public DefaultSQLiteCachingProvider( this._cacheStats = new CacheStats(); } + public DefaultSQLiteCachingProvider( + string name, + IEnumerable< ISQLiteDatabaseProvider> dbProviders, + IOptionsMonitor options, + ILoggerFactory loggerFactory = null) + { + this._dbProvider = dbProviders.FirstOrDefault(x => x.DBProviderName.Equals(name)); + this._options = options.CurrentValue; + this._logger = loggerFactory?.CreateLogger(); + this._cache = _dbProvider.GetConnection(); + this._cacheStats = new CacheStats(); + this._name = name; + } + /// /// is not distributed cache. /// @@ -80,7 +96,7 @@ public DefaultSQLiteCachingProvider( public CacheStats CacheStats => _cacheStats; - public string Name => throw new NotImplementedException(); + public string Name => this._name; /// /// Exists the specified cacheKey. @@ -93,7 +109,7 @@ public bool Exists(string cacheKey) var dbResult = _cache.ExecuteScalar(ConstSQL.EXISTSSQL, new { - cachekey = cacheKey + cachekey = cacheKey, name = _name }); return dbResult == 1; @@ -110,7 +126,8 @@ public async Task ExistsAsync(string cacheKey) var dbResult = await _cache.ExecuteScalarAsync(ConstSQL.EXISTSSQL, new { - cachekey = cacheKey + cachekey = cacheKey, + name = _name }); return dbResult == 1; @@ -131,7 +148,8 @@ public CacheValue Get(string cacheKey, Func dataRetriever, TimeSpan exp var dbResult = _cache.Query(ConstSQL.GETSQL, new { - cachekey = cacheKey + cachekey = cacheKey, + name = _name }).FirstOrDefault(); if (!string.IsNullOrWhiteSpace(dbResult)) @@ -177,7 +195,8 @@ public async Task> GetAsync(string cacheKey, Func> data var list = await _cache.QueryAsync(ConstSQL.GETSQL, new { - cachekey = cacheKey + cachekey = cacheKey, + name = _name }); var dbResult = list.FirstOrDefault(); @@ -222,7 +241,8 @@ public CacheValue Get(string cacheKey)// where T : class var dbResult = _cache.Query(ConstSQL.GETSQL, new { - cachekey = cacheKey + cachekey = cacheKey, + name = _name }).FirstOrDefault(); if (!string.IsNullOrWhiteSpace(dbResult)) @@ -257,7 +277,8 @@ public async Task> GetAsync(string cacheKey)// where T : class var list = await _cache.QueryAsync(ConstSQL.GETSQL, new { - cachekey = cacheKey + cachekey = cacheKey, + name = _name }); var dbResult = list.FirstOrDefault(); @@ -291,7 +312,7 @@ public void Remove(string cacheKey) { ArgumentCheck.NotNullOrWhiteSpace(cacheKey, nameof(cacheKey)); - _cache.Execute(ConstSQL.REMOVESQL, new { cachekey = cacheKey }); + _cache.Execute(ConstSQL.REMOVESQL, new { cachekey = cacheKey, name = _name }); } /// @@ -303,7 +324,7 @@ public async Task RemoveAsync(string cacheKey) { ArgumentCheck.NotNullOrWhiteSpace(cacheKey, nameof(cacheKey)); - await _cache.ExecuteAsync(ConstSQL.REMOVESQL, new { cachekey = cacheKey }); + await _cache.ExecuteAsync(ConstSQL.REMOVESQL, new { cachekey = cacheKey, name = _name }); } /// @@ -329,6 +350,7 @@ public void Set(string cacheKey, T cacheValue, TimeSpan expiration)// where T _cache.Execute(ConstSQL.SETSQL, new { cachekey = cacheKey, + name = _name, cachevalue = Newtonsoft.Json.JsonConvert.SerializeObject(cacheValue), expiration = expiration.Ticks / 10000000 }); @@ -358,6 +380,7 @@ public async Task SetAsync(string cacheKey, T cacheValue, TimeSpan expiration await _cache.ExecuteAsync(ConstSQL.SETSQL, new { cachekey = cacheKey, + name = _name, cachevalue = Newtonsoft.Json.JsonConvert.SerializeObject(cacheValue), expiration = expiration.Ticks / 10000000 }); @@ -409,7 +432,7 @@ public void RemoveByPrefix(string prefix) if (_options.EnableLogging) _logger?.LogInformation($"RemoveByPrefix : prefix = {prefix}"); - _cache.Execute(ConstSQL.REMOVEBYPREFIXSQL, new { cachekey = string.Concat(prefix, "%") }); + _cache.Execute(ConstSQL.REMOVEBYPREFIXSQL, new { cachekey = string.Concat(prefix, "%"), name = _name }); } /// @@ -423,7 +446,7 @@ public async Task RemoveByPrefixAsync(string prefix) if (_options.EnableLogging) _logger?.LogInformation($"RemoveByPrefixAsync : prefix = {prefix}"); - await _cache.ExecuteAsync(ConstSQL.REMOVEBYPREFIXSQL, new { cachekey = string.Concat(prefix, "%") }); + await _cache.ExecuteAsync(ConstSQL.REMOVEBYPREFIXSQL, new { cachekey = string.Concat(prefix, "%"), name = _name }); } /// @@ -444,6 +467,7 @@ public void SetAll(IDictionary values, TimeSpan expiration)// wher _cache.Execute(ConstSQL.SETSQL, new { cachekey = item.Key, + name = _name, cachevalue = Newtonsoft.Json.JsonConvert.SerializeObject(item.Value), expiration = expiration.Ticks / 10000000 }, tran); @@ -472,6 +496,7 @@ public async Task SetAllAsync(IDictionary values, TimeSpan expirat tasks.Add(_cache.ExecuteAsync(ConstSQL.SETSQL, new { cachekey = item.Key, + name = _name, cachevalue = Newtonsoft.Json.JsonConvert.SerializeObject(item.Value), expiration = expiration.Ticks / 10000000 }, tran)); @@ -493,7 +518,8 @@ public IDictionary> GetAll(IEnumerable cacheKey var list = _cache.Query(ConstSQL.GETALLSQL, new { - cachekey = cacheKeys.ToArray() + cachekey = cacheKeys.ToArray(), + name = _name }).ToList(); return GetDict(list); @@ -511,7 +537,8 @@ public async Task>> GetAllAsync(IEnumerable var list = (await _cache.QueryAsync(ConstSQL.GETALLSQL, new { - cachekey = cacheKeys.ToArray() + cachekey = cacheKeys.ToArray(), + name = _name })).ToList(); return GetDict(list); @@ -548,7 +575,8 @@ public IDictionary> GetByPrefix(string prefix)// where var list = _cache.Query(ConstSQL.GETBYPREFIXSQL, new { - cachekey = string.Concat(prefix, "%") + cachekey = string.Concat(prefix, "%"), + name = _name }).ToList(); return GetDict(list); @@ -566,7 +594,8 @@ public async Task>> GetByPrefixAsync(string var list = (await _cache.QueryAsync(ConstSQL.GETBYPREFIXSQL, new { - cachekey = string.Concat(prefix, "%") + cachekey = string.Concat(prefix, "%"), + name = _name })).ToList(); return GetDict(list); @@ -583,7 +612,7 @@ public void RemoveAll(IEnumerable cacheKeys) var tran = _cache.BeginTransaction(); foreach (var item in cacheKeys) - _cache.Execute(ConstSQL.REMOVESQL, new { cachekey = item }, tran); + _cache.Execute(ConstSQL.REMOVESQL, new { cachekey = item, name = _name }, tran); tran.Commit(); } @@ -601,7 +630,7 @@ public async Task RemoveAllAsync(IEnumerable cacheKeys) var tasks = new List>(); foreach (var item in cacheKeys) - tasks.Add(_cache.ExecuteAsync(ConstSQL.REMOVESQL, new { cachekey = item }, tran)); + tasks.Add(_cache.ExecuteAsync(ConstSQL.REMOVESQL, new { cachekey = item, name = _name }, tran)); await Task.WhenAll(tasks); tran.Commit(); @@ -616,23 +645,23 @@ public int GetCount(string prefix = "") { if (string.IsNullOrWhiteSpace(prefix)) { - return _cache.ExecuteScalar(ConstSQL.COUNTALLSQL); + return _cache.ExecuteScalar(ConstSQL.COUNTALLSQL,new{ name = _name }); } else { - return _cache.ExecuteScalar(ConstSQL.COUNTPREFIXSQL, new { cachekey = string.Concat(prefix, "%") }); + return _cache.ExecuteScalar(ConstSQL.COUNTPREFIXSQL, new { cachekey = string.Concat(prefix, "%"), name = _name }); } } /// /// Flush All Cached Item. /// - public void Flush() => _cache.Execute(ConstSQL.FLUSHSQL); + public void Flush() => _cache.Execute(ConstSQL.FLUSHSQL,new{ name = _name }); /// /// Flush All Cached Item async. /// /// The async. - public async Task FlushAsync() => await _cache.ExecuteAsync(ConstSQL.FLUSHSQL); + public async Task FlushAsync() => await _cache.ExecuteAsync(ConstSQL.FLUSHSQL,new { name = _name }); } } diff --git a/src/EasyCaching.SQLite/ISQLiteDatabaseProvider.cs b/src/EasyCaching.SQLite/ISQLiteDatabaseProvider.cs index e854259a..077c5608 100644 --- a/src/EasyCaching.SQLite/ISQLiteDatabaseProvider.cs +++ b/src/EasyCaching.SQLite/ISQLiteDatabaseProvider.cs @@ -12,5 +12,7 @@ public interface ISQLiteDatabaseProvider /// /// The connection. SqliteConnection GetConnection(); + + string DBProviderName { get; } } } diff --git a/src/EasyCaching.SQLite/SQLiteCacheServiceCollectionExtensions.cs b/src/EasyCaching.SQLite/SQLiteCacheServiceCollectionExtensions.cs index b3ceb33f..33d072c8 100644 --- a/src/EasyCaching.SQLite/SQLiteCacheServiceCollectionExtensions.cs +++ b/src/EasyCaching.SQLite/SQLiteCacheServiceCollectionExtensions.cs @@ -6,6 +6,8 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; + using Microsoft.Extensions.Logging; + using Microsoft.Extensions.Options; /// /// SQLite cache service collection extensions. @@ -66,5 +68,95 @@ public static IServiceCollection AddSQLiteCache( return services; } + + + public static IServiceCollection AddSQLiteCacheWithFactory( + this IServiceCollection services, + string name, + Action providerAction) + { + ArgumentCheck.NotNull(services, nameof(services)); + + services.AddOptions(); + services.Configure(providerAction); + services.AddSingleton(); + services.AddSingleton(x => + { + var optionsMon = x.GetRequiredService>(); + var options = optionsMon.Get(name); + return new SQLiteDatabaseProvider(name, options); + }); + + services.AddSingleton(x => + { + var dbProviders = x.GetServices(); + var options = x.GetRequiredService>(); + var factory = x.GetService(); + return new DefaultSQLiteCachingProvider(name, dbProviders, options, factory); + }); + + return services; + } + + /// + /// Adds the default redis cache. + /// + /// + /// + /// + /// The default redis cache. + /// Services. + /// Configuration. + public static IServiceCollection AddSQLiteCacheWithFactory( + this IServiceCollection services, + string name, + IConfiguration configuration) + { + var cacheConfig = configuration.GetSection(EasyCachingConstValue.SQLiteSection); + services.Configure(name, cacheConfig); + + //var redisConfig = configuration.GetSection(EasyCachingConstValue.ConfigChildSection); + //services.Configure(redisConfig); + services.AddSingleton(); + services.AddSingleton(x => + { + var optionsMon = x.GetRequiredService>(); + var options = optionsMon.Get(name); + return new SQLiteDatabaseProvider(name, options); + }); + + services.AddSingleton(x => + { + var dbProviders = x.GetServices(); + var options = x.GetRequiredService>(); + var factory = x.GetService(); + return new DefaultSQLiteCachingProvider(name, dbProviders, options, factory); + }); + + return services; + } } } diff --git a/src/EasyCaching.SQLite/SQLiteDatabaseProvider.cs b/src/EasyCaching.SQLite/SQLiteDatabaseProvider.cs index 4dbd46b1..e63883e1 100644 --- a/src/EasyCaching.SQLite/SQLiteDatabaseProvider.cs +++ b/src/EasyCaching.SQLite/SQLiteDatabaseProvider.cs @@ -1,5 +1,6 @@ namespace EasyCaching.SQLite { + using EasyCaching.Core; using Microsoft.Data.Sqlite; using Microsoft.Extensions.Options; @@ -22,11 +23,21 @@ public SQLiteDatabaseProvider(IOptionsMonitor optionAction) this._options = optionAction.CurrentValue.DBConfig; } + + public SQLiteDatabaseProvider(string name , SQLiteOptions options) + { + this._name = name; + this._options = options.DBConfig; + } + /// /// The conn. /// private static SqliteConnection _conn; + private readonly string _name = EasyCachingConstValue.DefaultSQLiteName; + public string DBProviderName => _name; + /// /// Gets the connection. /// diff --git a/test/EasyCaching.UnitTests/CachingTests/SQLiteCachingTest.cs b/test/EasyCaching.UnitTests/CachingTests/SQLiteCachingTest.cs index f9107636..30955bbb 100644 --- a/test/EasyCaching.UnitTests/CachingTests/SQLiteCachingTest.cs +++ b/test/EasyCaching.UnitTests/CachingTests/SQLiteCachingTest.cs @@ -1,9 +1,11 @@ namespace EasyCaching.UnitTests { using Dapper; + using EasyCaching.Core; using EasyCaching.SQLite; using Microsoft.Extensions.DependencyInjection; using System; + using Xunit; public class SQLiteCachingTest : BaseCachingProviderTest { @@ -37,4 +39,78 @@ public SQLiteCachingTest() _defaultTs = TimeSpan.FromSeconds(30); } } + + + + public class SQLiteCachingProviderWithFactoryTest : BaseCachingProviderTest + { + private readonly IEasyCachingProvider _secondProvider; + + private const string SECOND_PROVIDER_NAME = "second"; + + public SQLiteCachingProviderWithFactoryTest() + { + IServiceCollection services = new ServiceCollection(); + services.AddSQLiteCacheWithFactory(EasyCachingConstValue.DefaultSQLiteName, options => + { + options.DBConfig = new SQLiteDBOptions + { + FileName = "", + FilePath = "", + CacheMode = Microsoft.Data.Sqlite.SqliteCacheMode.Default, + OpenMode = Microsoft.Data.Sqlite.SqliteOpenMode.Memory, + }; + + }); + services.AddSQLiteCacheWithFactory(SECOND_PROVIDER_NAME, options => + { + options.DBConfig = new SQLiteDBOptions + { + FileName = "", + FilePath = "", + CacheMode = Microsoft.Data.Sqlite.SqliteCacheMode.Default, + OpenMode = Microsoft.Data.Sqlite.SqliteOpenMode.Memory, + }; + }); + IServiceProvider serviceProvider = services.BuildServiceProvider(); + var factory = serviceProvider.GetService(); + _provider = factory.GetCachingProvider(EasyCachingConstValue.DefaultSQLiteName); + _secondProvider = factory.GetCachingProvider(SECOND_PROVIDER_NAME); + + var _dbProvider = serviceProvider.GetService(); + var conn = _dbProvider.GetConnection(); + if (conn.State == System.Data.ConnectionState.Closed) + { + conn.Open(); + } + conn.Execute(ConstSQL.CREATESQL); + + _defaultTs = TimeSpan.FromSeconds(30); + } + + [Fact] + public void Multi_Instance_Set_And_Get_Should_Succeed() + { + var cacheKey1 = "named-provider-1"; + var cacheKey2 = "named-provider-2"; + + var value1 = Guid.NewGuid().ToString(); + var value2 = Guid.NewGuid().ToString("N"); + + _provider.Set(cacheKey1, value1, _defaultTs); + _secondProvider.Set(cacheKey2, value2, _defaultTs); + + var p1 = _provider.Get(cacheKey1); + var p2 = _provider.Get(cacheKey2); + + var s1 = _secondProvider.Get(cacheKey1); + var s2 = _secondProvider.Get(cacheKey2); + + Assert.Equal(value1, p1.Value); + Assert.False(p2.HasValue); + + Assert.False(s1.HasValue); + Assert.Equal(value2, s2.Value); + } + } } From 92e7f95a74e6f2c407b9d3c4a987de0512ec4d50 Mon Sep 17 00:00:00 2001 From: catcherwong Date: Mon, 10 Dec 2018 22:22:32 +0800 Subject: [PATCH 12/22] :arrow_up: Upgrading dependencies. --- .../EasyCaching.Interceptor.AspectCore.csproj | 4 ++-- .../EasyCaching.Interceptor.Castle.csproj | 4 ++-- src/EasyCaching.Redis/EasyCaching.Redis.csproj | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/EasyCaching.Interceptor.AspectCore/EasyCaching.Interceptor.AspectCore.csproj b/src/EasyCaching.Interceptor.AspectCore/EasyCaching.Interceptor.AspectCore.csproj index 26b84b05..e27e6853 100644 --- a/src/EasyCaching.Interceptor.AspectCore/EasyCaching.Interceptor.AspectCore.csproj +++ b/src/EasyCaching.Interceptor.AspectCore/EasyCaching.Interceptor.AspectCore.csproj @@ -24,7 +24,7 @@ - - + + diff --git a/src/EasyCaching.Interceptor.Castle/EasyCaching.Interceptor.Castle.csproj b/src/EasyCaching.Interceptor.Castle/EasyCaching.Interceptor.Castle.csproj index 28104d61..e1f068e2 100644 --- a/src/EasyCaching.Interceptor.Castle/EasyCaching.Interceptor.Castle.csproj +++ b/src/EasyCaching.Interceptor.Castle/EasyCaching.Interceptor.Castle.csproj @@ -25,8 +25,8 @@ - + - + diff --git a/src/EasyCaching.Redis/EasyCaching.Redis.csproj b/src/EasyCaching.Redis/EasyCaching.Redis.csproj index 7a4a5e40..26d7c3c0 100644 --- a/src/EasyCaching.Redis/EasyCaching.Redis.csproj +++ b/src/EasyCaching.Redis/EasyCaching.Redis.csproj @@ -21,7 +21,7 @@ - + From 80c58fd945f416b9a528b379b55402dfebbbb663 Mon Sep 17 00:00:00 2001 From: catcherwong Date: Tue, 11 Dec 2018 20:50:37 +0800 Subject: [PATCH 13/22] :sparkles: Memcached Named Provider. --- .../DefaultInMemoryCachingProvider.cs | 1 + .../DefaultMemcachedCachingProvider.cs | 34 +++++- .../EasyCachingMemcachedClient.cs | 19 ++++ ...EasyCachingMemcachedClientConfiguration.cs | 107 ++++++++++++++++++ .../MemcachedServiceCollectionExtensions.cs | 15 +-- .../DefaultRedisCachingProvider.cs | 1 + .../DefaultSQLiteCachingProvider.cs | 3 +- 7 files changed, 168 insertions(+), 12 deletions(-) create mode 100644 src/EasyCaching.Memcached/EasyCachingMemcachedClient.cs diff --git a/src/EasyCaching.InMemory/DefaultInMemoryCachingProvider.cs b/src/EasyCaching.InMemory/DefaultInMemoryCachingProvider.cs index f0a98fd8..b0fb623b 100644 --- a/src/EasyCaching.InMemory/DefaultInMemoryCachingProvider.cs +++ b/src/EasyCaching.InMemory/DefaultInMemoryCachingProvider.cs @@ -85,6 +85,7 @@ public DefaultInMemoryCachingProvider( this._cacheKeys = new ConcurrentCollections.ConcurrentHashSet(); this._cacheStats = new CacheStats(); + this._name = EasyCachingConstValue.DefaultInMemoryName; } /// diff --git a/src/EasyCaching.Memcached/DefaultMemcachedCachingProvider.cs b/src/EasyCaching.Memcached/DefaultMemcachedCachingProvider.cs index ee5bf408..cc910ad7 100644 --- a/src/EasyCaching.Memcached/DefaultMemcachedCachingProvider.cs +++ b/src/EasyCaching.Memcached/DefaultMemcachedCachingProvider.cs @@ -60,18 +60,44 @@ public class DefaultMemcachedCachingProvider : IEasyCachingProvider public CacheStats CacheStats => _cacheStats; - public string Name => throw new NotImplementedException(); + private readonly string _name; + + public string Name => this._name; + + /// + /// Initializes a new instance of the class. + /// + /// Memcached client. + /// Options. + /// Logger factory. + public DefaultMemcachedCachingProvider( + IEnumerable memcachedClients, + IOptionsMonitor options, + ILoggerFactory loggerFactory = null) + { + this._name = EasyCachingConstValue.DefaultMemcachedName; + this._memcachedClient = memcachedClients.FirstOrDefault(x=>x.Name.Equals(this._name)); + this._options = options.CurrentValue; + this._logger = loggerFactory?.CreateLogger(); + + this._cacheStats = new CacheStats(); + } /// /// Initializes a new instance of the class. /// - /// Memcached client. + /// Name. + /// Memcached client. + /// Options. + /// Logger factory. public DefaultMemcachedCachingProvider( - IMemcachedClient memcachedClient, + string name, + IEnumerable memcachedClients, IOptionsMonitor options, ILoggerFactory loggerFactory = null) { - this._memcachedClient = memcachedClient; + this._name = name; + this._memcachedClient = memcachedClients.FirstOrDefault(x => x.Name.Equals(this._name)); this._options = options.CurrentValue; this._logger = loggerFactory?.CreateLogger(); diff --git a/src/EasyCaching.Memcached/EasyCachingMemcachedClient.cs b/src/EasyCaching.Memcached/EasyCachingMemcachedClient.cs new file mode 100644 index 00000000..37f2fcaa --- /dev/null +++ b/src/EasyCaching.Memcached/EasyCachingMemcachedClient.cs @@ -0,0 +1,19 @@ +namespace EasyCaching.Memcached +{ + using Enyim.Caching; + using Enyim.Caching.Configuration; + using Microsoft.Extensions.Logging; + + public class EasyCachingMemcachedClient : MemcachedClient + { + private readonly string _name; + + public string Name { get { return this._name; } } + + public EasyCachingMemcachedClient(string name, ILoggerFactory loggerFactor, IMemcachedClientConfiguration configuration) + : base(loggerFactor, configuration) + { + this._name = name; + } + } +} diff --git a/src/EasyCaching.Memcached/EasyCachingMemcachedClientConfiguration.cs b/src/EasyCaching.Memcached/EasyCachingMemcachedClientConfiguration.cs index 6fc4ee43..d1809df8 100644 --- a/src/EasyCaching.Memcached/EasyCachingMemcachedClientConfiguration.cs +++ b/src/EasyCaching.Memcached/EasyCachingMemcachedClientConfiguration.cs @@ -17,6 +17,7 @@ public class EasyCachingMemcachedClientConfiguration : IMemcachedClientConfigura private ITranscoder _transcoder; private IMemcachedKeyTransformer _keyTransformer; private ILogger _logger; + private string _name; /// /// Initializes a new instance of the class. @@ -119,6 +120,106 @@ public EasyCachingMemcachedClientConfiguration( } } + public EasyCachingMemcachedClientConfiguration( + string name, + ILoggerFactory loggerFactory, + IOptionsMonitor optionsAccessor, + ITranscoder transcoder = null, + IMemcachedKeyTransformer keyTransformer = null) + { + this._name = name; + if (optionsAccessor == null) + { + throw new ArgumentNullException(nameof(optionsAccessor)); + } + + _logger = loggerFactory.CreateLogger(); + + var options = optionsAccessor.CurrentValue.DBConfig; + Servers = new List(); + foreach (var server in options.Servers) + { + Servers.Add(new DnsEndPoint(server.Address, server.Port)); + } + + SocketPool = new SocketPoolConfiguration(); + if (options.SocketPool != null) + { + options.SocketPool.CheckPoolSize(); + options.SocketPool.CheckTimeout(); + + SocketPool.MinPoolSize = options.SocketPool.MinPoolSize; + _logger.LogInformation($"{nameof(SocketPool.MinPoolSize)}: {SocketPool.MinPoolSize}"); + + SocketPool.MaxPoolSize = options.SocketPool.MaxPoolSize; + _logger.LogInformation($"{nameof(SocketPool.MaxPoolSize)}: {SocketPool.MaxPoolSize}"); + + SocketPool.ConnectionTimeout = options.SocketPool.ConnectionTimeout; + _logger.LogInformation($"{nameof(SocketPool.ConnectionTimeout)}: {SocketPool.ConnectionTimeout}"); + + SocketPool.ReceiveTimeout = options.SocketPool.ReceiveTimeout; + _logger.LogInformation($"{nameof(SocketPool.ReceiveTimeout)}: {SocketPool.ReceiveTimeout}"); + + SocketPool.DeadTimeout = options.SocketPool.DeadTimeout; + _logger.LogInformation($"{nameof(SocketPool.DeadTimeout)}: {SocketPool.DeadTimeout}"); + + SocketPool.QueueTimeout = options.SocketPool.QueueTimeout; + _logger.LogInformation($"{nameof(SocketPool.QueueTimeout)}: {SocketPool.QueueTimeout}"); + } + + Protocol = options.Protocol; + + if (options.Authentication != null && !string.IsNullOrEmpty(options.Authentication.Type)) + { + try + { + var authenticationType = Type.GetType(options.Authentication.Type); + if (authenticationType != null) + { + _logger.LogDebug($"Authentication type is {authenticationType}."); + + Authentication = new AuthenticationConfiguration(); + Authentication.Type = authenticationType; + foreach (var parameter in options.Authentication.Parameters) + { + Authentication.Parameters[parameter.Key] = parameter.Value; + _logger.LogDebug($"Authentication {parameter.Key} is '{parameter.Value}'."); + } + } + else + { + _logger.LogError($"Unable to load authentication type {options.Authentication.Type}."); + } + } + catch (Exception ex) + { + _logger.LogError(new EventId(), ex, $"Unable to load authentication type {options.Authentication.Type}."); + } + } + + if (keyTransformer != null) + { + this.KeyTransformer = keyTransformer; + _logger.LogDebug($"Use KeyTransformer Type : '{keyTransformer.ToString()}'"); + } + + if (NodeLocator == null) + { + NodeLocator = options.Servers.Count > 1 ? typeof(DefaultNodeLocator) : typeof(SingleNodeLocator); + } + + if (transcoder != null) + { + this._transcoder = transcoder; + _logger.LogDebug($"Use Transcoder Type : '{transcoder.ToString()}'"); + } + + if (options.NodeLocatorFactory != null) + { + NodeLocatorFactory = options.NodeLocatorFactory; + } + } + /// /// Adds a new server to the pool. /// @@ -138,6 +239,12 @@ public void AddServer(string host, int port) this.Servers.Add(new DnsEndPoint(host, port)); } + /// + /// Gets the name. + /// + /// The name. + public string Name => this._name; + /// /// Gets a list of each representing a Memcached server in the pool. /// diff --git a/src/EasyCaching.Memcached/MemcachedServiceCollectionExtensions.cs b/src/EasyCaching.Memcached/MemcachedServiceCollectionExtensions.cs index 462ba17e..bf77e511 100644 --- a/src/EasyCaching.Memcached/MemcachedServiceCollectionExtensions.cs +++ b/src/EasyCaching.Memcached/MemcachedServiceCollectionExtensions.cs @@ -8,6 +8,7 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; + using Microsoft.Extensions.Options; using System; /// @@ -31,13 +32,13 @@ public static IServiceCollection AddDefaultMemcached( services.AddOptions(); services.Configure(providerAction); - services.TryAddTransient(); - services.TryAddSingleton(); - services.TryAddSingleton(factory => factory.GetService()); - services.TryAddSingleton(); - services.TryAddSingleton(); services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddSingleton(); + + services.TryAddSingleton(); + services.TryAddSingleton(factory => factory.GetService()); services.AddSingleton(); @@ -88,8 +89,8 @@ public static IServiceCollection AddDefaultMemcached( //services.Configure(memcachedConfig); services.TryAddTransient(); - services.TryAddSingleton(); - services.TryAddSingleton(factory => factory.GetService()); + services.TryAddSingleton(); + services.TryAddSingleton(factory => factory.GetService()); services.TryAddSingleton(); services.TryAddSingleton(); diff --git a/src/EasyCaching.Redis/DefaultRedisCachingProvider.cs b/src/EasyCaching.Redis/DefaultRedisCachingProvider.cs index 3470085d..502a55c6 100644 --- a/src/EasyCaching.Redis/DefaultRedisCachingProvider.cs +++ b/src/EasyCaching.Redis/DefaultRedisCachingProvider.cs @@ -100,6 +100,7 @@ public DefaultRedisCachingProvider( this._cache = _dbProvider.GetDatabase(); this._servers = _dbProvider.GetServerList(); this._cacheStats = new CacheStats(); + this._name = EasyCachingConstValue.DefaultRedisName; } /// diff --git a/src/EasyCaching.SQLite/DefaultSQLiteCachingProvider.cs b/src/EasyCaching.SQLite/DefaultSQLiteCachingProvider.cs index 31eae35e..942c8d82 100644 --- a/src/EasyCaching.SQLite/DefaultSQLiteCachingProvider.cs +++ b/src/EasyCaching.SQLite/DefaultSQLiteCachingProvider.cs @@ -36,7 +36,7 @@ public class DefaultSQLiteCachingProvider : IEasyCachingProvider /// private readonly SqliteConnection _cache; - private readonly string _name= EasyCachingConstValue.DefaultSQLiteName; + private readonly string _name; /// /// Initializes a new instance of the class. @@ -52,6 +52,7 @@ public DefaultSQLiteCachingProvider( this._logger = loggerFactory?.CreateLogger(); this._cache = _dbProvider.GetConnection(); this._cacheStats = new CacheStats(); + this._name = EasyCachingConstValue.DefaultRedisName; } public DefaultSQLiteCachingProvider( From 829cba6763d2f5efb0a934283cc6ea52ab003605 Mon Sep 17 00:00:00 2001 From: catcherwong Date: Tue, 11 Dec 2018 21:04:28 +0800 Subject: [PATCH 14/22] :bug: Fixed bugs --- .../MemcachedServiceCollectionExtensions.cs | 45 ++++++++++++++++--- 1 file changed, 38 insertions(+), 7 deletions(-) diff --git a/src/EasyCaching.Memcached/MemcachedServiceCollectionExtensions.cs b/src/EasyCaching.Memcached/MemcachedServiceCollectionExtensions.cs index bf77e511..191c9570 100644 --- a/src/EasyCaching.Memcached/MemcachedServiceCollectionExtensions.cs +++ b/src/EasyCaching.Memcached/MemcachedServiceCollectionExtensions.cs @@ -8,6 +8,7 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; + using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using System; @@ -32,14 +33,29 @@ public static IServiceCollection AddDefaultMemcached( services.AddOptions(); services.Configure(providerAction); + services.AddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); - services.TryAddSingleton(); + services.AddSingleton(x => + { + var options = x.GetRequiredService>(); + var loggerFactory = x.GetRequiredService(); + var transcoder = x.GetRequiredService(); + var transformer = x.GetRequiredService(); + return new EasyCachingMemcachedClientConfiguration(loggerFactory, options, transcoder, transformer); + }); + + services.TryAddSingleton(x=> + { + var loggerFactory = x.GetRequiredService(); + var config = x.GetRequiredService(); + return new EasyCachingMemcachedClient(EasyCachingConstValue.DefaultMemcachedName, loggerFactory, config); + }); - services.TryAddSingleton(); services.TryAddSingleton(factory => factory.GetService()); + services.AddSingleton(); return services; @@ -88,13 +104,28 @@ public static IServiceCollection AddDefaultMemcached( //var memcachedConfig = configuration.GetSection(EasyCachingConstValue.ConfigChildSection); //services.Configure(memcachedConfig); - services.TryAddTransient(); - services.TryAddSingleton(); - services.TryAddSingleton(factory => factory.GetService()); - + services.AddSingleton(); services.TryAddSingleton(); - services.TryAddSingleton(); services.TryAddSingleton(); + services.TryAddSingleton(); + services.AddSingleton(x => + { + var options = x.GetRequiredService>(); + var loggerFactory = x.GetRequiredService(); + var transcoder = x.GetRequiredService(); + var transformer = x.GetRequiredService(); + return new EasyCachingMemcachedClientConfiguration(loggerFactory, options, transcoder, transformer); + }); + + services.TryAddSingleton(x => + { + var loggerFactory = x.GetRequiredService(); + var config = x.GetRequiredService(); + return new EasyCachingMemcachedClient(EasyCachingConstValue.DefaultMemcachedName, loggerFactory, config); + }); + + services.TryAddSingleton(factory => factory.GetService()); + services.TryAddSingleton(); From 0ca338157d124f0a7050fd01ae425d3627374de7 Mon Sep 17 00:00:00 2001 From: catcherwong Date: Tue, 11 Dec 2018 22:26:54 +0800 Subject: [PATCH 15/22] :construction: [WIP] Memcached Named Provider. --- .../DefaultInMemoryCachingProvider.cs | 2 +- ...EasyCachingMemcachedClientConfiguration.cs | 4 +- .../MemcachedServiceCollectionExtensions.cs | 93 ++++++++++- .../CachingTests/MemcachedProviderTest.cs | 155 ++++++++++++++++++ 4 files changed, 244 insertions(+), 10 deletions(-) diff --git a/src/EasyCaching.InMemory/DefaultInMemoryCachingProvider.cs b/src/EasyCaching.InMemory/DefaultInMemoryCachingProvider.cs index b0fb623b..7e47033d 100644 --- a/src/EasyCaching.InMemory/DefaultInMemoryCachingProvider.cs +++ b/src/EasyCaching.InMemory/DefaultInMemoryCachingProvider.cs @@ -85,7 +85,7 @@ public DefaultInMemoryCachingProvider( this._cacheKeys = new ConcurrentCollections.ConcurrentHashSet(); this._cacheStats = new CacheStats(); - this._name = EasyCachingConstValue.DefaultInMemoryName; + //this._name = EasyCachingConstValue.DefaultInMemoryName; } /// diff --git a/src/EasyCaching.Memcached/EasyCachingMemcachedClientConfiguration.cs b/src/EasyCaching.Memcached/EasyCachingMemcachedClientConfiguration.cs index d1809df8..a2c605a1 100644 --- a/src/EasyCaching.Memcached/EasyCachingMemcachedClientConfiguration.cs +++ b/src/EasyCaching.Memcached/EasyCachingMemcachedClientConfiguration.cs @@ -123,7 +123,7 @@ public EasyCachingMemcachedClientConfiguration( public EasyCachingMemcachedClientConfiguration( string name, ILoggerFactory loggerFactory, - IOptionsMonitor optionsAccessor, + MemcachedOptions optionsAccessor, ITranscoder transcoder = null, IMemcachedKeyTransformer keyTransformer = null) { @@ -135,7 +135,7 @@ public EasyCachingMemcachedClientConfiguration( _logger = loggerFactory.CreateLogger(); - var options = optionsAccessor.CurrentValue.DBConfig; + var options = optionsAccessor.DBConfig; Servers = new List(); foreach (var server in options.Servers) { diff --git a/src/EasyCaching.Memcached/MemcachedServiceCollectionExtensions.cs b/src/EasyCaching.Memcached/MemcachedServiceCollectionExtensions.cs index 191c9570..eb48a82a 100644 --- a/src/EasyCaching.Memcached/MemcachedServiceCollectionExtensions.cs +++ b/src/EasyCaching.Memcached/MemcachedServiceCollectionExtensions.cs @@ -2,7 +2,6 @@ { using EasyCaching.Core; using EasyCaching.Core.Internal; - using Enyim.Caching; using Enyim.Caching.Configuration; using Enyim.Caching.Memcached; using Microsoft.Extensions.Configuration; @@ -11,6 +10,7 @@ using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using System; + using System.Linq; /// /// Memcached service collection extensions. @@ -53,9 +53,6 @@ public static IServiceCollection AddDefaultMemcached( return new EasyCachingMemcachedClient(EasyCachingConstValue.DefaultMemcachedName, loggerFactory, config); }); - services.TryAddSingleton(factory => factory.GetService()); - - services.AddSingleton(); return services; @@ -124,13 +121,95 @@ public static IServiceCollection AddDefaultMemcached( return new EasyCachingMemcachedClient(EasyCachingConstValue.DefaultMemcachedName, loggerFactory, config); }); - services.TryAddSingleton(factory => factory.GetService()); + services.TryAddSingleton(); + return services; + } + /// + /// Adds the default memcached. + /// + /// The default memcached. + /// Services. + /// Name. + /// Provider action. + public static IServiceCollection AddDefaultMemcached( + this IServiceCollection services, + string name, + Action providerAction) + { + ArgumentCheck.NotNull(services, nameof(services)); + ArgumentCheck.NotNullOrWhiteSpace(name, nameof(name)); + ArgumentCheck.NotNull(providerAction, nameof(providerAction)); - services.TryAddSingleton(); + services.AddOptions(); + services.Configure(name, providerAction); + + services.AddSingleton(); + services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddSingleton(); + services.AddSingleton(x => + { + var optionsMon = x.GetRequiredService>(); + var options = optionsMon.Get(name); + var loggerFactory = x.GetRequiredService(); + var transcoder = x.GetRequiredService(); + var transformer = x.GetRequiredService(); + return new EasyCachingMemcachedClientConfiguration(name, loggerFactory, options, transcoder, transformer); + }); + services.TryAddSingleton(x => + { + var loggerFactory = x.GetRequiredService(); + var configs = x.GetServices(); + var config = configs.FirstOrDefault(y => y.Name.Equals(name)); + return new EasyCachingMemcachedClient(name, loggerFactory, config); + }); + + services.AddSingleton(); return services; - } + } + + /// + /// Adds the default memcached. + /// + /// The default memcached. + /// Services. + /// Name. + /// Configuration. + public static IServiceCollection AddDefaultMemcached( + this IServiceCollection services, + string name, + IConfiguration configuration) + { + var cacheConfig = configuration.GetSection(EasyCachingConstValue.MemcachedSection); + services.Configure(name,cacheConfig); + + services.AddSingleton(); + services.TryAddSingleton(); + services.TryAddSingleton(); + services.TryAddSingleton(); + services.AddSingleton(x => + { + var optionsMon = x.GetRequiredService>(); + var options = optionsMon.Get(name); + var loggerFactory = x.GetRequiredService(); + var transcoder = x.GetRequiredService(); + var transformer = x.GetRequiredService(); + return new EasyCachingMemcachedClientConfiguration(name, loggerFactory, options, transcoder, transformer); + }); + + services.TryAddSingleton(x => + { + var loggerFactory = x.GetRequiredService(); + var configs = x.GetServices(); + var config = configs.FirstOrDefault(y => y.Name.Equals(name)); + return new EasyCachingMemcachedClient(name, loggerFactory, config); + }); + + services.TryAddSingleton(); + return services; + } } } diff --git a/test/EasyCaching.UnitTests/CachingTests/MemcachedProviderTest.cs b/test/EasyCaching.UnitTests/CachingTests/MemcachedProviderTest.cs index 7a71fbfe..df09ffe0 100644 --- a/test/EasyCaching.UnitTests/CachingTests/MemcachedProviderTest.cs +++ b/test/EasyCaching.UnitTests/CachingTests/MemcachedProviderTest.cs @@ -159,4 +159,159 @@ private void GetCacheItem(string cacheKey, string prefix) Assert.False(val.HasValue); } } + + + public class MemcachedProviderWithFactoryTest : BaseCachingProviderTest + { + public MemcachedProviderWithFactoryTest() + { + IServiceCollection services = new ServiceCollection(); + services.AddDefaultMemcached("MyTest",options => + { + options.DBConfig.AddServer("127.0.0.1", 11211); + }); + services.AddLogging(); + IServiceProvider serviceProvider = services.BuildServiceProvider(); + _provider = serviceProvider.GetService(); + _defaultTs = TimeSpan.FromSeconds(50); + } + + [Fact] + protected override void RemoveByPrefix_Should_Succeed() + { + string prefixKey = "demowithfactory"; + string prefixValue = "abcwithfactory"; + + _provider.Set(prefixKey, prefixValue, TimeSpan.FromSeconds(120)); + + SetCacheItem("1", "1", prefixKey); + SetCacheItem("2", "2", prefixKey); + SetCacheItem("3", "3", prefixKey); + SetCacheItem("4", "4", prefixKey); + SetCacheItem("4", "4", "xxx"); + + _provider.RemoveByPrefix(prefixKey); + + GetCacheItem("1", prefixKey); + GetCacheItem("2", prefixKey); + GetCacheItem("3", prefixKey); + GetCacheItem("4", prefixKey); + + var pre = _provider.Get("xxx"); + var cacheKey = string.Concat(pre, "4"); + var val = _provider.Get(cacheKey); + Assert.True(val.HasValue); + + var afterPrefixValue = _provider.Get(prefixKey); + Assert.NotEqual(prefixValue, afterPrefixValue.Value); + } + + [Fact] + protected override async Task RemoveByPrefixAsync_Should_Succeed() + { + string prefixKey = "demowithfactoryasync"; + string prefixValue = "abcwithfactoryasync"; + + _provider.Set("demowithfactoryasync", prefixValue, TimeSpan.FromSeconds(120)); + + SetCacheItem("1", "1", prefixKey); + SetCacheItem("2", "2", prefixKey); + SetCacheItem("3", "3", prefixKey); + SetCacheItem("4", "4", prefixKey); + SetCacheItem("4", "4", "xxx"); + + await _provider.RemoveByPrefixAsync(prefixKey); + + GetCacheItem("1", prefixKey); + GetCacheItem("2", prefixKey); + GetCacheItem("3", prefixKey); + GetCacheItem("4", prefixKey); + + var pre = _provider.Get("xxx"); + var cacheKey = string.Concat(pre, "4"); + var val = _provider.Get(cacheKey); + Assert.True(val.HasValue); + + + var afterPrefixValue = _provider.Get(prefixKey); + Assert.NotEqual(prefixValue, afterPrefixValue.Value); + } + + [Fact] + public void CacheKey_Length_GT_250_Should_Call_SHA1() + { + var cacheKey = ""; + var part = "1000000000"; + + for (int i = 0; i < 26; i++) + cacheKey += part; + + var cacheValue = "value"; + + _provider.Set(cacheKey, cacheValue, _defaultTs); + + var val = _provider.Get(cacheKey); + Assert.True(val.HasValue); + } + + [Fact] + protected override void GetByPrefix_Should_Succeed() + { + + } + + [Fact] + protected override async Task GetByPrefixAsync_Should_Succeed() + { + await Task.FromResult(1); + } + + [Fact] + protected override void GetByPrefix_With_Not_Existed_Prefix_Should_Return_Empty_Dict() + { + + } + + [Fact] + protected override async Task GetByPrefixAsync_With_Not_Existed_Prefix_Should_Return_Empty_Dict() + { + await Task.FromResult(1); + } + + + [Fact] + protected override void Get_Count_Without_Prefix_Should_Succeed() + { + + } + + [Fact] + protected override void Get_Count_With_Prefix_Should_Succeed() + { + + } + + private void SetCacheItem(string cacheKey, string cacheValue, string prefix) + { + var pre = _provider.Get(prefix); + + cacheKey = string.Concat(pre, cacheKey); + + _provider.Set(cacheKey, cacheValue, _defaultTs); + + var val = _provider.Get(cacheKey); + Assert.Equal(cacheValue, val.Value); + } + + private void GetCacheItem(string cacheKey, string prefix) + { + var pre = _provider.Get(prefix); + + cacheKey = string.Concat(pre, cacheKey); + + var val = _provider.Get(cacheKey); + Assert.False(val.HasValue); + } + } + } From 51263151e7193d1cfd1acac9b05a487cef20c678 Mon Sep 17 00:00:00 2001 From: catcherwong Date: Tue, 11 Dec 2018 22:46:06 +0800 Subject: [PATCH 16/22] :construction: [WIP] Memcached Named Provider. --- .../MemcachedServiceCollectionExtensions.cs | 2 -- .../CachingTests/MemcachedProviderTest.cs | 4 +++- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/EasyCaching.Memcached/MemcachedServiceCollectionExtensions.cs b/src/EasyCaching.Memcached/MemcachedServiceCollectionExtensions.cs index eb48a82a..683dd4a8 100644 --- a/src/EasyCaching.Memcached/MemcachedServiceCollectionExtensions.cs +++ b/src/EasyCaching.Memcached/MemcachedServiceCollectionExtensions.cs @@ -33,7 +33,6 @@ public static IServiceCollection AddDefaultMemcached( services.AddOptions(); services.Configure(providerAction); - services.AddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); @@ -101,7 +100,6 @@ public static IServiceCollection AddDefaultMemcached( //var memcachedConfig = configuration.GetSection(EasyCachingConstValue.ConfigChildSection); //services.Configure(memcachedConfig); - services.AddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); diff --git a/test/EasyCaching.UnitTests/CachingTests/MemcachedProviderTest.cs b/test/EasyCaching.UnitTests/CachingTests/MemcachedProviderTest.cs index df09ffe0..e531b131 100644 --- a/test/EasyCaching.UnitTests/CachingTests/MemcachedProviderTest.cs +++ b/test/EasyCaching.UnitTests/CachingTests/MemcachedProviderTest.cs @@ -172,7 +172,9 @@ public MemcachedProviderWithFactoryTest() }); services.AddLogging(); IServiceProvider serviceProvider = services.BuildServiceProvider(); - _provider = serviceProvider.GetService(); + + var factory = serviceProvider.GetService(); + _provider = factory.GetCachingProvider("MyTest"); _defaultTs = TimeSpan.FromSeconds(50); } From 5a5c67310f51c8f399a57ad7c8d0967d5ee96806 Mon Sep 17 00:00:00 2001 From: catcherwong Date: Tue, 11 Dec 2018 22:56:42 +0800 Subject: [PATCH 17/22] :bug: [WIP] Fixed Memcached Reg bug . --- .../MemcachedServiceCollectionExtensions.cs | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/src/EasyCaching.Memcached/MemcachedServiceCollectionExtensions.cs b/src/EasyCaching.Memcached/MemcachedServiceCollectionExtensions.cs index 683dd4a8..6ca5926a 100644 --- a/src/EasyCaching.Memcached/MemcachedServiceCollectionExtensions.cs +++ b/src/EasyCaching.Memcached/MemcachedServiceCollectionExtensions.cs @@ -164,7 +164,13 @@ public static IServiceCollection AddDefaultMemcached( return new EasyCachingMemcachedClient(name, loggerFactory, config); }); - services.AddSingleton(); + services.AddSingleton(x => + { + var clients = x.GetServices(); + var options = x.GetRequiredService>(); + var factory = x.GetService(); + return new DefaultMemcachedCachingProvider(name, clients, options, factory); + }); return services; } @@ -206,7 +212,14 @@ public static IServiceCollection AddDefaultMemcached( return new EasyCachingMemcachedClient(name, loggerFactory, config); }); - services.TryAddSingleton(); + services.AddSingleton(x => + { + var clients = x.GetServices(); + var options = x.GetRequiredService>(); + var factory = x.GetService(); + return new DefaultMemcachedCachingProvider(name, clients, options, factory); + }); + return services; } } From d655218c671652f51b55a0b155a48df37f1db843 Mon Sep 17 00:00:00 2001 From: catcherwong Date: Wed, 12 Dec 2018 22:24:44 +0800 Subject: [PATCH 18/22] :art: Improving format of the code. --- ...nMemoryCacheServiceCollectionExtensions.cs | 22 +----- .../MemcachedServiceCollectionExtensions.cs | 64 +++++++-------- .../RedisCacheServiceCollectionExtensions.cs | 78 ++++++------------- .../SQLiteCacheServiceCollectionExtensions.cs | 65 ++++++---------- .../CachingTests/MemcachedProviderTest.cs | 2 +- 5 files changed, 85 insertions(+), 146 deletions(-) diff --git a/src/EasyCaching.InMemory/InMemoryCacheServiceCollectionExtensions.cs b/src/EasyCaching.InMemory/InMemoryCacheServiceCollectionExtensions.cs index c0f0dcb9..2e663641 100644 --- a/src/EasyCaching.InMemory/InMemoryCacheServiceCollectionExtensions.cs +++ b/src/EasyCaching.InMemory/InMemoryCacheServiceCollectionExtensions.cs @@ -4,7 +4,6 @@ using EasyCaching.Core.Internal; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; - using Microsoft.Extensions.DependencyInjection.Extensions; using System; /// @@ -47,13 +46,6 @@ public static IServiceCollection AddDefaultInMemoryCache( services.AddMemoryCache(); services.AddSingleton(); - //services.AddSingleton(x=> - //{ - // var mCache = x.GetRequiredService(); - // var mOptions = x.GetRequiredService>(); - // var mLog = x.GetRequiredService(); - // return new DefaultInMemoryCachingProvider(name, mCache, mOptions,mLog); - //}); return services; } @@ -84,20 +76,10 @@ public static IServiceCollection AddDefaultInMemoryCache( services.AddMemoryCache(); services.AddSingleton(); - //services.AddSingleton(x => - //{ - // var mCache = x.GetRequiredService(); - // var mOptions = x.GetRequiredService>(); - // var mLog = x.GetRequiredService(); - // return new DefaultInMemoryCachingProvider(name, mCache, mOptions, mLog); - //}); return services; } - - - /// /// Adds the default in-memory cache. /// @@ -105,6 +87,8 @@ public static IServiceCollection AddDefaultInMemoryCache( /// Services. public static IServiceCollection AddDefaultInMemoryCacheWithFactory(this IServiceCollection services,string providerName = EasyCachingConstValue.DefaultInMemoryName) { + ArgumentCheck.NotNullOrWhiteSpace(providerName, nameof(providerName)); + var option = new InMemoryOptions(); return services.AddDefaultInMemoryCacheWithFactory(providerName, x => @@ -127,6 +111,7 @@ public static IServiceCollection AddDefaultInMemoryCacheWithFactory( Action providerAction) { ArgumentCheck.NotNull(services, nameof(services)); + ArgumentCheck.NotNullOrWhiteSpace(providerName, nameof(providerName)); ArgumentCheck.NotNull(providerAction, nameof(providerAction)); services.AddOptions(); @@ -135,7 +120,6 @@ public static IServiceCollection AddDefaultInMemoryCacheWithFactory( services.AddMemoryCache(); services.AddSingleton(); - //services.AddSingleton(); services.AddSingleton(x=> { var mCache = x.GetRequiredService(); diff --git a/src/EasyCaching.Memcached/MemcachedServiceCollectionExtensions.cs b/src/EasyCaching.Memcached/MemcachedServiceCollectionExtensions.cs index 6ca5926a..0b5dc583 100644 --- a/src/EasyCaching.Memcached/MemcachedServiceCollectionExtensions.cs +++ b/src/EasyCaching.Memcached/MemcachedServiceCollectionExtensions.cs @@ -45,7 +45,7 @@ public static IServiceCollection AddDefaultMemcached( return new EasyCachingMemcachedClientConfiguration(loggerFactory, options, transcoder, transformer); }); - services.TryAddSingleton(x=> + services.AddSingleton(x=> { var loggerFactory = x.GetRequiredService(); var config = x.GetRequiredService(); @@ -94,12 +94,11 @@ public static IServiceCollection AddDefaultMemcached( this IServiceCollection services, IConfiguration configuration) { + ArgumentCheck.NotNull(services, nameof(services)); + var cacheConfig = configuration.GetSection(EasyCachingConstValue.MemcachedSection); services.Configure(cacheConfig); - //var memcachedConfig = configuration.GetSection(EasyCachingConstValue.ConfigChildSection); - //services.Configure(memcachedConfig); - services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddSingleton(); @@ -112,35 +111,35 @@ public static IServiceCollection AddDefaultMemcached( return new EasyCachingMemcachedClientConfiguration(loggerFactory, options, transcoder, transformer); }); - services.TryAddSingleton(x => + services.AddSingleton(x => { var loggerFactory = x.GetRequiredService(); var config = x.GetRequiredService(); return new EasyCachingMemcachedClient(EasyCachingConstValue.DefaultMemcachedName, loggerFactory, config); }); - services.TryAddSingleton(); + services.AddSingleton(); return services; } /// - /// Adds the default memcached. + /// Adds the default memcached with factory. /// - /// The default memcached. + /// The default memcached with factory. /// Services. - /// Name. + /// Provider name. /// Provider action. - public static IServiceCollection AddDefaultMemcached( + public static IServiceCollection AddDefaultMemcachedWithFactory( this IServiceCollection services, - string name, + string providerName, Action providerAction) { ArgumentCheck.NotNull(services, nameof(services)); - ArgumentCheck.NotNullOrWhiteSpace(name, nameof(name)); + ArgumentCheck.NotNullOrWhiteSpace(providerName, nameof(providerName)); ArgumentCheck.NotNull(providerAction, nameof(providerAction)); services.AddOptions(); - services.Configure(name, providerAction); + services.Configure(providerName, providerAction); services.AddSingleton(); services.TryAddSingleton(); @@ -149,19 +148,19 @@ public static IServiceCollection AddDefaultMemcached( services.AddSingleton(x => { var optionsMon = x.GetRequiredService>(); - var options = optionsMon.Get(name); + var options = optionsMon.Get(providerName); var loggerFactory = x.GetRequiredService(); var transcoder = x.GetRequiredService(); var transformer = x.GetRequiredService(); - return new EasyCachingMemcachedClientConfiguration(name, loggerFactory, options, transcoder, transformer); + return new EasyCachingMemcachedClientConfiguration(providerName, loggerFactory, options, transcoder, transformer); }); - services.TryAddSingleton(x => + services.AddSingleton(x => { var loggerFactory = x.GetRequiredService(); var configs = x.GetServices(); - var config = configs.FirstOrDefault(y => y.Name.Equals(name)); - return new EasyCachingMemcachedClient(name, loggerFactory, config); + var config = configs.FirstOrDefault(y => y.Name.Equals(providerName)); + return new EasyCachingMemcachedClient(providerName, loggerFactory, config); }); services.AddSingleton(x => @@ -169,26 +168,29 @@ public static IServiceCollection AddDefaultMemcached( var clients = x.GetServices(); var options = x.GetRequiredService>(); var factory = x.GetService(); - return new DefaultMemcachedCachingProvider(name, clients, options, factory); + return new DefaultMemcachedCachingProvider(providerName, clients, options, factory); }); return services; } /// - /// Adds the default memcached. + /// Adds the default memcached with factory. /// - /// The default memcached. + /// The default memcached with factory. /// Services. - /// Name. + /// Provider name. /// Configuration. - public static IServiceCollection AddDefaultMemcached( + public static IServiceCollection AddDefaultMemcachedWithFactory( this IServiceCollection services, - string name, + string providerName, IConfiguration configuration) { + ArgumentCheck.NotNull(services, nameof(services)); + ArgumentCheck.NotNullOrWhiteSpace(providerName, nameof(providerName)); + var cacheConfig = configuration.GetSection(EasyCachingConstValue.MemcachedSection); - services.Configure(name,cacheConfig); + services.Configure(providerName,cacheConfig); services.AddSingleton(); services.TryAddSingleton(); @@ -197,19 +199,19 @@ public static IServiceCollection AddDefaultMemcached( services.AddSingleton(x => { var optionsMon = x.GetRequiredService>(); - var options = optionsMon.Get(name); + var options = optionsMon.Get(providerName); var loggerFactory = x.GetRequiredService(); var transcoder = x.GetRequiredService(); var transformer = x.GetRequiredService(); - return new EasyCachingMemcachedClientConfiguration(name, loggerFactory, options, transcoder, transformer); + return new EasyCachingMemcachedClientConfiguration(providerName, loggerFactory, options, transcoder, transformer); }); - services.TryAddSingleton(x => + services.AddSingleton(x => { var loggerFactory = x.GetRequiredService(); var configs = x.GetServices(); - var config = configs.FirstOrDefault(y => y.Name.Equals(name)); - return new EasyCachingMemcachedClient(name, loggerFactory, config); + var config = configs.FirstOrDefault(y => y.Name.Equals(providerName)); + return new EasyCachingMemcachedClient(providerName, loggerFactory, config); }); services.AddSingleton(x => @@ -217,7 +219,7 @@ public static IServiceCollection AddDefaultMemcached( var clients = x.GetServices(); var options = x.GetRequiredService>(); var factory = x.GetService(); - return new DefaultMemcachedCachingProvider(name, clients, options, factory); + return new DefaultMemcachedCachingProvider(providerName, clients, options, factory); }); return services; diff --git a/src/EasyCaching.Redis/RedisCacheServiceCollectionExtensions.cs b/src/EasyCaching.Redis/RedisCacheServiceCollectionExtensions.cs index 2ef08cf0..8c266ae9 100644 --- a/src/EasyCaching.Redis/RedisCacheServiceCollectionExtensions.cs +++ b/src/EasyCaching.Redis/RedisCacheServiceCollectionExtensions.cs @@ -72,12 +72,11 @@ public static IServiceCollection AddDefaultRedisCache( this IServiceCollection services, IConfiguration configuration) { + ArgumentCheck.NotNull(services, nameof(services)); + var cacheConfig = configuration.GetSection(EasyCachingConstValue.RedisSection); services.Configure(cacheConfig); - //var redisConfig = configuration.GetSection(EasyCachingConstValue.ConfigChildSection); - //services.Configure(redisConfig); - services.TryAddSingleton(); services.TryAddSingleton(); services.AddSingleton(); @@ -85,106 +84,79 @@ public static IServiceCollection AddDefaultRedisCache( return services; } - - /// - /// Adds the default redis cache. + /// Adds the default redis cache with factory. /// - /// The default redis cache. + /// The default redis cache with factory. /// Services. - /// Options Action. + /// Provider name. + /// Provider action. public static IServiceCollection AddDefaultRedisCacheWithFactory( this IServiceCollection services, - string name, + string providerName, Action providerAction) { ArgumentCheck.NotNull(services, nameof(services)); + ArgumentCheck.NotNullOrWhiteSpace(providerName, nameof(providerName)); services.AddOptions(); - //services.Configure(providerAction); - - services.Configure(name, providerAction); + services.Configure(providerName, providerAction); services.AddSingleton(); services.TryAddSingleton(); services.AddSingleton(x => { var optionsMon = x.GetRequiredService>(); - var options = optionsMon.Get(name); - return new RedisDatabaseProvider(name, options); + var options = optionsMon.Get(providerName); + return new RedisDatabaseProvider(providerName, options); }); - //services.AddSingleton(); + services.AddSingleton(x => { var dbProviders = x.GetServices(); var serializer = x.GetRequiredService(); var options = x.GetRequiredService>(); var factory = x.GetService(); - return new DefaultRedisCachingProvider(name, dbProviders, serializer, options, factory); + return new DefaultRedisCachingProvider(providerName, dbProviders, serializer, options, factory); }); return services; } /// - /// Adds the default redis cache. + /// Adds the default redis cache with factory. /// - /// - /// - /// - /// The default redis cache. + /// The default redis cache with factory. /// Services. + /// Provider name. /// Configuration. public static IServiceCollection AddDefaultRedisCacheWithFactory( this IServiceCollection services, - string name, + string providerName, IConfiguration configuration) { - var cacheConfig = configuration.GetSection(EasyCachingConstValue.RedisSection); - services.Configure(name,cacheConfig); + ArgumentCheck.NotNull(services, nameof(services)); + ArgumentCheck.NotNullOrWhiteSpace(providerName, nameof(providerName)); - //var redisConfig = configuration.GetSection(EasyCachingConstValue.ConfigChildSection); - //services.Configure(redisConfig); + var cacheConfig = configuration.GetSection(EasyCachingConstValue.RedisSection); + services.Configure(providerName,cacheConfig); services.AddSingleton(); services.TryAddSingleton(); services.AddSingleton(x => { var optionsMon = x.GetRequiredService>(); - var options = optionsMon.Get(name); - return new RedisDatabaseProvider(name, options); + var options = optionsMon.Get(providerName); + return new RedisDatabaseProvider(providerName, options); }); - //services.AddSingleton(); + services.AddSingleton(x => { var dbProviders = x.GetServices(); var serializer = x.GetRequiredService(); var options = x.GetRequiredService>(); var factory = x.GetService(); - return new DefaultRedisCachingProvider(name, dbProviders, serializer, options, factory); + return new DefaultRedisCachingProvider(providerName, dbProviders, serializer, options, factory); }); return services; diff --git a/src/EasyCaching.SQLite/SQLiteCacheServiceCollectionExtensions.cs b/src/EasyCaching.SQLite/SQLiteCacheServiceCollectionExtensions.cs index 33d072c8..3aaebd3a 100644 --- a/src/EasyCaching.SQLite/SQLiteCacheServiceCollectionExtensions.cs +++ b/src/EasyCaching.SQLite/SQLiteCacheServiceCollectionExtensions.cs @@ -35,7 +35,6 @@ public static IServiceCollection AddSQLiteCache( return services; } - /// /// Adds the SQLite cache. /// @@ -68,23 +67,30 @@ public static IServiceCollection AddSQLiteCache( return services; } - + /// + /// Adds the SQL ite cache with factory. + /// + /// The SQL ite cache with factory. + /// Services. + /// Provider name. + /// Provider action. public static IServiceCollection AddSQLiteCacheWithFactory( this IServiceCollection services, - string name, + string providerName, Action providerAction) { ArgumentCheck.NotNull(services, nameof(services)); + ArgumentCheck.NotNullOrWhiteSpace(providerName, nameof(providerName)); services.AddOptions(); - services.Configure(providerAction); + services.Configure(providerName, providerAction); services.AddSingleton(); services.AddSingleton(x => { var optionsMon = x.GetRequiredService>(); - var options = optionsMon.Get(name); - return new SQLiteDatabaseProvider(name, options); + var options = optionsMon.Get(providerName); + return new SQLiteDatabaseProvider(providerName, options); }); services.AddSingleton(x => @@ -92,60 +98,35 @@ public static IServiceCollection AddSQLiteCacheWithFactory( var dbProviders = x.GetServices(); var options = x.GetRequiredService>(); var factory = x.GetService(); - return new DefaultSQLiteCachingProvider(name, dbProviders, options, factory); + return new DefaultSQLiteCachingProvider(providerName, dbProviders, options, factory); }); return services; } /// - /// Adds the default redis cache. + /// Adds the SQL ite cache with factory. /// - /// - /// - /// - /// The default redis cache. + /// The SQL ite cache with factory. /// Services. + /// Provider name. /// Configuration. public static IServiceCollection AddSQLiteCacheWithFactory( this IServiceCollection services, - string name, + string providerName, IConfiguration configuration) { + ArgumentCheck.NotNullOrWhiteSpace(providerName, nameof(providerName)); + var cacheConfig = configuration.GetSection(EasyCachingConstValue.SQLiteSection); - services.Configure(name, cacheConfig); + services.Configure(providerName, cacheConfig); - //var redisConfig = configuration.GetSection(EasyCachingConstValue.ConfigChildSection); - //services.Configure(redisConfig); services.AddSingleton(); services.AddSingleton(x => { var optionsMon = x.GetRequiredService>(); - var options = optionsMon.Get(name); - return new SQLiteDatabaseProvider(name, options); + var options = optionsMon.Get(providerName); + return new SQLiteDatabaseProvider(providerName, options); }); services.AddSingleton(x => @@ -153,7 +134,7 @@ public static IServiceCollection AddSQLiteCacheWithFactory( var dbProviders = x.GetServices(); var options = x.GetRequiredService>(); var factory = x.GetService(); - return new DefaultSQLiteCachingProvider(name, dbProviders, options, factory); + return new DefaultSQLiteCachingProvider(providerName, dbProviders, options, factory); }); return services; diff --git a/test/EasyCaching.UnitTests/CachingTests/MemcachedProviderTest.cs b/test/EasyCaching.UnitTests/CachingTests/MemcachedProviderTest.cs index e531b131..5693aa04 100644 --- a/test/EasyCaching.UnitTests/CachingTests/MemcachedProviderTest.cs +++ b/test/EasyCaching.UnitTests/CachingTests/MemcachedProviderTest.cs @@ -166,7 +166,7 @@ public class MemcachedProviderWithFactoryTest : BaseCachingProviderTest public MemcachedProviderWithFactoryTest() { IServiceCollection services = new ServiceCollection(); - services.AddDefaultMemcached("MyTest",options => + services.AddDefaultMemcachedWithFactory("MyTest",options => { options.DBConfig.AddServer("127.0.0.1", 11211); }); From c423996608a914e17b60604e42478656c2a0a140 Mon Sep 17 00:00:00 2001 From: catcherwong Date: Wed, 12 Dec 2018 22:40:11 +0800 Subject: [PATCH 19/22] :bulb: Documenting source code. --- .../DefaultInMemoryCachingProvider.cs | 22 +++++++++++++--- .../DefaultMemcachedCachingProvider.cs | 25 ++++++++++++++----- .../EasyCaching.Memcached.csproj | 2 +- .../DefaultRedisCachingProvider.cs | 22 +++++++++++++--- .../DefaultSQLiteCachingProvider.cs | 18 +++++++++++-- 5 files changed, 72 insertions(+), 17 deletions(-) diff --git a/src/EasyCaching.InMemory/DefaultInMemoryCachingProvider.cs b/src/EasyCaching.InMemory/DefaultInMemoryCachingProvider.cs index 7e47033d..4d6a9d55 100644 --- a/src/EasyCaching.InMemory/DefaultInMemoryCachingProvider.cs +++ b/src/EasyCaching.InMemory/DefaultInMemoryCachingProvider.cs @@ -35,6 +35,16 @@ public class DefaultInMemoryCachingProvider : IEasyCachingProvider /// private readonly ILogger _logger; + /// + /// The cache stats. + /// + private readonly CacheStats _cacheStats; + + /// + /// The name. + /// + private readonly string _name; + /// /// /// is not distributed cache. @@ -60,12 +70,16 @@ public class DefaultInMemoryCachingProvider : IEasyCachingProvider /// The type of the caching provider. public CachingProviderType CachingProviderType => _options.CachingProviderType; - private readonly CacheStats _cacheStats; - - private readonly string _name; - + /// + /// Gets the cache stats. + /// + /// The cache stats. public CacheStats CacheStats => _cacheStats; + /// + /// Gets the name. + /// + /// The name. public string Name => _name; /// diff --git a/src/EasyCaching.Memcached/DefaultMemcachedCachingProvider.cs b/src/EasyCaching.Memcached/DefaultMemcachedCachingProvider.cs index cc910ad7..6327e904 100644 --- a/src/EasyCaching.Memcached/DefaultMemcachedCachingProvider.cs +++ b/src/EasyCaching.Memcached/DefaultMemcachedCachingProvider.cs @@ -2,7 +2,6 @@ { using EasyCaching.Core; using EasyCaching.Core.Internal; - using Enyim.Caching; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; @@ -20,7 +19,7 @@ public class DefaultMemcachedCachingProvider : IEasyCachingProvider /// /// The memcached client. /// - private readonly IMemcachedClient _memcachedClient; + private readonly EasyCachingMemcachedClient _memcachedClient; /// /// The options. @@ -32,6 +31,16 @@ public class DefaultMemcachedCachingProvider : IEasyCachingProvider /// private readonly ILogger _logger; + /// + /// The cache stats. + /// + private readonly CacheStats _cacheStats; + + /// + /// The name. + /// + private readonly string _name; + /// /// /// is distributed cache. @@ -56,12 +65,16 @@ public class DefaultMemcachedCachingProvider : IEasyCachingProvider /// The type of the caching provider. public CachingProviderType CachingProviderType => _options.CachingProviderType; - private readonly CacheStats _cacheStats; - + /// + /// Gets the cache stats. + /// + /// The cache stats. public CacheStats CacheStats => _cacheStats; - private readonly string _name; - + /// + /// Gets the name. + /// + /// The name. public string Name => this._name; /// diff --git a/src/EasyCaching.Memcached/EasyCaching.Memcached.csproj b/src/EasyCaching.Memcached/EasyCaching.Memcached.csproj index db108b52..8c42d049 100644 --- a/src/EasyCaching.Memcached/EasyCaching.Memcached.csproj +++ b/src/EasyCaching.Memcached/EasyCaching.Memcached.csproj @@ -24,6 +24,6 @@ - + diff --git a/src/EasyCaching.Redis/DefaultRedisCachingProvider.cs b/src/EasyCaching.Redis/DefaultRedisCachingProvider.cs index 502a55c6..6fc7e2ab 100644 --- a/src/EasyCaching.Redis/DefaultRedisCachingProvider.cs +++ b/src/EasyCaching.Redis/DefaultRedisCachingProvider.cs @@ -45,6 +45,16 @@ public class DefaultRedisCachingProvider : IEasyCachingProvider /// private readonly RedisOptions _options; + /// + /// The cache stats. + /// + private readonly CacheStats _cacheStats; + + /// + /// The name. + /// + private readonly string _name; + /// /// /// is distributed cache. @@ -69,12 +79,16 @@ public class DefaultRedisCachingProvider : IEasyCachingProvider /// The type of the caching provider. public CachingProviderType CachingProviderType => _options.CachingProviderType; - private readonly CacheStats _cacheStats; - + /// + /// Gets the cache stats. + /// + /// The cache stats. public CacheStats CacheStats => _cacheStats; - private readonly string _name; - + /// + /// Gets the name. + /// + /// The name. public string Name => this._name; /// diff --git a/src/EasyCaching.SQLite/DefaultSQLiteCachingProvider.cs b/src/EasyCaching.SQLite/DefaultSQLiteCachingProvider.cs index 942c8d82..362eb62a 100644 --- a/src/EasyCaching.SQLite/DefaultSQLiteCachingProvider.cs +++ b/src/EasyCaching.SQLite/DefaultSQLiteCachingProvider.cs @@ -36,6 +36,14 @@ public class DefaultSQLiteCachingProvider : IEasyCachingProvider /// private readonly SqliteConnection _cache; + /// + /// The cache stats. + /// + private readonly CacheStats _cacheStats; + + /// + /// The name. + /// private readonly string _name; /// @@ -93,10 +101,16 @@ public DefaultSQLiteCachingProvider( /// The type of the caching provider. public CachingProviderType CachingProviderType => _options.CachingProviderType; - private readonly CacheStats _cacheStats; - + /// + /// Gets the cache stats. + /// + /// The cache stats. public CacheStats CacheStats => _cacheStats; + /// + /// Gets the name. + /// + /// The name. public string Name => this._name; /// From 072a5b047193686000b87bd2c5f4ef7f5fed5d47 Mon Sep 17 00:00:00 2001 From: catcherwong Date: Wed, 12 Dec 2018 22:50:08 +0800 Subject: [PATCH 20/22] :ok_hand: Customize the section name for factory. --- .../InMemoryCacheServiceCollectionExtensions.cs | 4 +++- .../MemcachedServiceCollectionExtensions.cs | 5 ++++- .../RedisCacheServiceCollectionExtensions.cs | 5 ++++- .../SQLiteCacheServiceCollectionExtensions.cs | 5 ++++- 4 files changed, 15 insertions(+), 4 deletions(-) diff --git a/src/EasyCaching.InMemory/InMemoryCacheServiceCollectionExtensions.cs b/src/EasyCaching.InMemory/InMemoryCacheServiceCollectionExtensions.cs index 2e663641..c2d203c6 100644 --- a/src/EasyCaching.InMemory/InMemoryCacheServiceCollectionExtensions.cs +++ b/src/EasyCaching.InMemory/InMemoryCacheServiceCollectionExtensions.cs @@ -85,7 +85,9 @@ public static IServiceCollection AddDefaultInMemoryCache( /// /// The default in-memory cache. /// Services. - public static IServiceCollection AddDefaultInMemoryCacheWithFactory(this IServiceCollection services,string providerName = EasyCachingConstValue.DefaultInMemoryName) + public static IServiceCollection AddDefaultInMemoryCacheWithFactory( + this IServiceCollection services, + string providerName = EasyCachingConstValue.DefaultInMemoryName) { ArgumentCheck.NotNullOrWhiteSpace(providerName, nameof(providerName)); diff --git a/src/EasyCaching.Memcached/MemcachedServiceCollectionExtensions.cs b/src/EasyCaching.Memcached/MemcachedServiceCollectionExtensions.cs index 0b5dc583..dc3bfc22 100644 --- a/src/EasyCaching.Memcached/MemcachedServiceCollectionExtensions.cs +++ b/src/EasyCaching.Memcached/MemcachedServiceCollectionExtensions.cs @@ -180,16 +180,19 @@ public static IServiceCollection AddDefaultMemcachedWithFactory( /// The default memcached with factory. /// Services. /// Provider name. + /// Section name. /// Configuration. public static IServiceCollection AddDefaultMemcachedWithFactory( this IServiceCollection services, string providerName, + string sectionName, IConfiguration configuration) { ArgumentCheck.NotNull(services, nameof(services)); ArgumentCheck.NotNullOrWhiteSpace(providerName, nameof(providerName)); + ArgumentCheck.NotNullOrWhiteSpace(sectionName, nameof(sectionName)); - var cacheConfig = configuration.GetSection(EasyCachingConstValue.MemcachedSection); + var cacheConfig = configuration.GetSection(sectionName); services.Configure(providerName,cacheConfig); services.AddSingleton(); diff --git a/src/EasyCaching.Redis/RedisCacheServiceCollectionExtensions.cs b/src/EasyCaching.Redis/RedisCacheServiceCollectionExtensions.cs index 8c266ae9..cafb9333 100644 --- a/src/EasyCaching.Redis/RedisCacheServiceCollectionExtensions.cs +++ b/src/EasyCaching.Redis/RedisCacheServiceCollectionExtensions.cs @@ -129,16 +129,19 @@ public static IServiceCollection AddDefaultRedisCacheWithFactory( /// The default redis cache with factory. /// Services. /// Provider name. + /// Section name. /// Configuration. public static IServiceCollection AddDefaultRedisCacheWithFactory( this IServiceCollection services, string providerName, + string sectionName, IConfiguration configuration) { ArgumentCheck.NotNull(services, nameof(services)); ArgumentCheck.NotNullOrWhiteSpace(providerName, nameof(providerName)); + ArgumentCheck.NotNullOrWhiteSpace(sectionName, nameof(sectionName)); - var cacheConfig = configuration.GetSection(EasyCachingConstValue.RedisSection); + var cacheConfig = configuration.GetSection(sectionName); services.Configure(providerName,cacheConfig); services.AddSingleton(); diff --git a/src/EasyCaching.SQLite/SQLiteCacheServiceCollectionExtensions.cs b/src/EasyCaching.SQLite/SQLiteCacheServiceCollectionExtensions.cs index 3aaebd3a..d052bec0 100644 --- a/src/EasyCaching.SQLite/SQLiteCacheServiceCollectionExtensions.cs +++ b/src/EasyCaching.SQLite/SQLiteCacheServiceCollectionExtensions.cs @@ -110,15 +110,18 @@ public static IServiceCollection AddSQLiteCacheWithFactory( /// The SQL ite cache with factory. /// Services. /// Provider name. + /// Section name. /// Configuration. public static IServiceCollection AddSQLiteCacheWithFactory( this IServiceCollection services, string providerName, + string sectionName, IConfiguration configuration) { ArgumentCheck.NotNullOrWhiteSpace(providerName, nameof(providerName)); + ArgumentCheck.NotNullOrWhiteSpace(sectionName, nameof(sectionName)); - var cacheConfig = configuration.GetSection(EasyCachingConstValue.SQLiteSection); + var cacheConfig = configuration.GetSection(sectionName); services.Configure(providerName, cacheConfig); services.AddSingleton(); From 7bd9de4e8b01297db13f9cad936734960b522412 Mon Sep 17 00:00:00 2001 From: catcherwong Date: Thu, 13 Dec 2018 20:58:28 +0800 Subject: [PATCH 21/22] :green_heart: Fixing Unstable CI Build. --- .travis.yml | 2 +- appveyor.yml | 94 ++++++++++--------- .../CachingTests/MemcachedProviderTest.cs | 2 +- 3 files changed, 54 insertions(+), 44 deletions(-) diff --git a/.travis.yml b/.travis.yml index 582663d5..f788195c 100644 --- a/.travis.yml +++ b/.travis.yml @@ -27,4 +27,4 @@ script: - if test "$TRAVIS_OS_NAME" == "linux"; then dotnet restore; fi - if test "$TRAVIS_OS_NAME" == "osx"; then dotnet restore --disable-parallel; fi - dotnet build -c Release - - if test "$TRAVIS_OS_NAME" == "linux"; then dotnet test -c Release ./test/EasyCaching.UnitTests/EasyCaching.UnitTests.csproj; fi + #- if test "$TRAVIS_OS_NAME" == "linux"; then dotnet test -c Release ./test/EasyCaching.UnitTests/EasyCaching.UnitTests.csproj; fi diff --git a/appveyor.yml b/appveyor.yml index 8491eeb3..ed38fe5c 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -1,7 +1,9 @@ version: 1.0.{build} -image: Visual Studio 2017 Preview +image: +- Ubuntu1804 +- Visual Studio 2017 configuration: Release -clone_folder: C:\projects\easycaching\ +clone_depth: 50 pull_requests: do_not_increment_build_number: true @@ -17,50 +19,58 @@ skip_commits: - .travis.yml - .gitignore -install: -#- ps: Invoke-WebRequest "https://raw.githubusercontent.com/dotnet/cli/master/scripts/obtain/dotnet-install.ps1" -OutFile "dotnet-install.ps1" -#- ps: .\dotnet-install.ps1 --Version 2.1.301 -#- ps: dotnet --info -- cmd: >- - cd C:\projects\easycaching\tools\RedisConfigs\3.0.503 +for: +- + matrix: + only: + - image: Visual Studio 2017 + clone_folder: C:\projects\easycaching\ - redis-server.exe --service-install --service-name "redis-6379" "..\Basic\master-6379.conf" + install: + - cmd: >- + cd C:\projects\easycaching\tools\RedisConfigs\3.0.503 + redis-server.exe --service-install --service-name "redis-6379" "..\Basic\master-6379.conf" + net start redis-6379 + sc create memcached1 binpath= "c:\projects\easycaching\tools\memcached\memcached.exe -d runservice -m 64 -c 2048 -p 11211" start= auto displayname= "memcached1" + sc create memcached2 binpath= "c:\projects\easycaching\tools\memcached\memcached.exe -d runservice -m 64 -c 2048 -p 11212" start= auto displayname= "memcached2" + net start memcached1 + net start memcached2 + cd C:\projects\easycaching + + before_build: + - ps: dotnet restore - net start redis-6379 + build_script: + - ps: dotnet build -c Release - c:\projects\easycaching\tools\memcached\memcached.exe -d install + test_script: + - ps: dotnet test -c Release --no-build .\test\EasyCaching.UnitTests\EasyCaching.UnitTests.csproj - net start memcached +- + matrix: + only: + - image: Ubuntu1804 - cd C:\projects\easycaching - -before_build: -- cmd: dotnet restore + clone_folder: /home/appveyor/projects/easycaching -build: - project: EasyCaching.sln - parallel: true - verbosity: minimal - -test_script: -- cmd: >- - dotnet test -c Release --no-build .\test\EasyCaching.UnitTests\EasyCaching.UnitTests.csproj -#before_test: -#- ps: >- -# nuget install coveralls.net -Version 0.7.0 -OutputDirectory tools - -# nuget install OpenCover -Version 4.6.519 -OutputDirectory tools + services: + - redis -#test_script: -#- ps: tools\OpenCover.4.6.519\tools\OpenCover.Console.exe -target:"dotnet.exe" -targetargs:" test test\EasyCaching.UnitTests\EasyCaching.UnitTests.csproj -c Debug /p:DebugType=full" -register:user -filter:"+[EasyCaching*]* -[EasyCaching*Tests]*" -oldstyle -returntargetcode -output:coverage.xml - -#after_test: -#- ps: >- -# if ($env:APPVEYOR_REPO_BRANCH -eq "master" -And -not $env:APPVEYOR_PULL_REQUEST_NUMBER) -# { -# tools\coveralls.net.0.7.0\tools\csmacnz.Coveralls.exe --opencover -i coverage.xml --serviceName appveyor --useRelativePaths -# } -# else -# { -# echo "not master branch...." -# } + install: + - sh: >- + sudo apt-get install libevent libevent-deve + + sudo apt-get install memcached + + sudo memcached -p 11211 -u root -m 64m -d + + sudo memcached -p 11212 -u root -m 64m -d + + before_build: + - sh: dotnet restore + + build_script: + - sh: dotnet build -c Release + + test_script: + - sh: dotnet test -c Release --no-build ./test/EasyCaching.UnitTests/EasyCaching.UnitTests.csproj \ No newline at end of file diff --git a/test/EasyCaching.UnitTests/CachingTests/MemcachedProviderTest.cs b/test/EasyCaching.UnitTests/CachingTests/MemcachedProviderTest.cs index 5693aa04..6f9fa5b9 100644 --- a/test/EasyCaching.UnitTests/CachingTests/MemcachedProviderTest.cs +++ b/test/EasyCaching.UnitTests/CachingTests/MemcachedProviderTest.cs @@ -168,7 +168,7 @@ public MemcachedProviderWithFactoryTest() IServiceCollection services = new ServiceCollection(); services.AddDefaultMemcachedWithFactory("MyTest",options => { - options.DBConfig.AddServer("127.0.0.1", 11211); + options.DBConfig.AddServer("127.0.0.1", 11212); }); services.AddLogging(); IServiceProvider serviceProvider = services.BuildServiceProvider(); From fa69e570e8beb7045e137f1b931d973ca8143c8f Mon Sep 17 00:00:00 2001 From: catcherwong Date: Thu, 13 Dec 2018 22:55:30 +0800 Subject: [PATCH 22/22] :wrench: Update appveyor.yml --- appveyor.yml | 37 +++++++++++++++++-------------------- 1 file changed, 17 insertions(+), 20 deletions(-) diff --git a/appveyor.yml b/appveyor.yml index ed38fe5c..fae6f7fd 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -27,16 +27,15 @@ for: clone_folder: C:\projects\easycaching\ install: - - cmd: >- - cd C:\projects\easycaching\tools\RedisConfigs\3.0.503 - redis-server.exe --service-install --service-name "redis-6379" "..\Basic\master-6379.conf" - net start redis-6379 - sc create memcached1 binpath= "c:\projects\easycaching\tools\memcached\memcached.exe -d runservice -m 64 -c 2048 -p 11211" start= auto displayname= "memcached1" - sc create memcached2 binpath= "c:\projects\easycaching\tools\memcached\memcached.exe -d runservice -m 64 -c 2048 -p 11212" start= auto displayname= "memcached2" - net start memcached1 - net start memcached2 - cd C:\projects\easycaching - + - ps: cd c:\projects\easycaching\tools\RedisConfigs\3.0.503\ + - ps: .\redis-server.exe --service-install --service-name "redis-6379" "..\Basic\master-6379.conf" + - ps: net start redis-6379 + - ps: new-service –Name memcached1 –DisplayName memcached1 –BinaryPathName “c:\projects\easycaching\tools\memcached\memcached.exe -d runservice -m 64 -c 2048 -p 11211” –StartupType Automatic + - ps: new-service –Name memcached2 –DisplayName memcached2 –BinaryPathName “c:\projects\easycaching\tools\memcached\memcached.exe -d runservice -m 64 -c 2048 -p 11212” –StartupType Automatic + - ps: net start memcached1 + - ps: net start memcached2 + - ps: cd c:\projects\easycaching + before_build: - ps: dotnet restore @@ -57,15 +56,11 @@ for: - redis install: - - sh: >- - sudo apt-get install libevent libevent-deve - - sudo apt-get install memcached - - sudo memcached -p 11211 -u root -m 64m -d - - sudo memcached -p 11212 -u root -m 64m -d - + #- sh: sudo apt-get install libevent libevent-deve + - sh: sudo apt-get install memcached + - sh: sudo memcached -p 11211 -u root -m 64m -d + - sh: sudo memcached -p 11212 -u root -m 64m -d + before_build: - sh: dotnet restore @@ -73,4 +68,6 @@ for: - sh: dotnet build -c Release test_script: - - sh: dotnet test -c Release --no-build ./test/EasyCaching.UnitTests/EasyCaching.UnitTests.csproj \ No newline at end of file + - sh: dotnet test -c Release --no-build ./test/EasyCaching.UnitTests/EasyCaching.UnitTests.csproj + + \ No newline at end of file