From 02c5166f0fe680b1e1b40b52d5900f519368d3aa Mon Sep 17 00:00:00 2001 From: "erfanmahmoudi98@outlook.com" Date: Sun, 17 Sep 2023 11:30:16 +0330 Subject: [PATCH 01/11] Add locks sample --- EasyCaching.sln | 16 +++-- .../Controllers/LocksController.cs | 70 +++++++++++++++++++ .../EasyCaching.Demo.Locks.csproj | 20 ++++++ sample/EasyCaching.Demo.Locks/GlobalUsings.cs | 4 ++ sample/EasyCaching.Demo.Locks/Program.cs | 53 ++++++++++++++ .../appsettings.Development.json | 8 +++ .../EasyCaching.Demo.Locks/appsettings.json | 9 +++ 7 files changed, 176 insertions(+), 4 deletions(-) create mode 100644 sample/EasyCaching.Demo.Locks/Controllers/LocksController.cs create mode 100644 sample/EasyCaching.Demo.Locks/EasyCaching.Demo.Locks.csproj create mode 100644 sample/EasyCaching.Demo.Locks/GlobalUsings.cs create mode 100644 sample/EasyCaching.Demo.Locks/Program.cs create mode 100644 sample/EasyCaching.Demo.Locks/appsettings.Development.json create mode 100644 sample/EasyCaching.Demo.Locks/appsettings.json diff --git a/EasyCaching.sln b/EasyCaching.sln index 7d07ad0a..a2d217c4 100644 --- a/EasyCaching.sln +++ b/EasyCaching.sln @@ -1,4 +1,5 @@ -Microsoft Visual Studio Solution File, Format Version 12.00 + +Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 17 VisualStudioVersion = 17.2.32616.157 MinimumVisualStudioVersion = 10.0.40219.1 @@ -72,11 +73,13 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EasyCaching.Serialization.S EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EasyCaching.Bus.ConfluentKafka", "bus\EasyCaching.Bus.ConfluentKafka\EasyCaching.Bus.ConfluentKafka.csproj", "{F7FBADEB-D766-4595-949A-07104B52692C}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EasyCaching.Bus.Zookeeper", "bus\EasyCaching.Bus.Zookeeper\EasyCaching.Bus.Zookeeper.csproj", "{5E488583-391E-4E15-83C1-7301B4FE79AE}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EasyCaching.Bus.Zookeeper", "bus\EasyCaching.Bus.Zookeeper\EasyCaching.Bus.Zookeeper.csproj", "{5E488583-391E-4E15-83C1-7301B4FE79AE}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EasyCaching.FasterKv", "src\EasyCaching.FasterKv\EasyCaching.FasterKv.csproj", "{7191E567-38DF-4879-82E1-73EC618AFCAC}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EasyCaching.FasterKv", "src\EasyCaching.FasterKv\EasyCaching.FasterKv.csproj", "{7191E567-38DF-4879-82E1-73EC618AFCAC}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EasyCaching.Serialization.MemoryPack", "serialization\EasyCaching.Serialization.MemoryPack\EasyCaching.Serialization.MemoryPack.csproj", "{EEF22C21-F380-4980-B72C-F14488369333}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EasyCaching.Serialization.MemoryPack", "serialization\EasyCaching.Serialization.MemoryPack\EasyCaching.Serialization.MemoryPack.csproj", "{EEF22C21-F380-4980-B72C-F14488369333}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EasyCaching.Demo.Locks", "sample\EasyCaching.Demo.Locks\EasyCaching.Demo.Locks.csproj", "{9B15A0A0-BD6B-40B0-90D4-848BC3E4AF98}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -208,6 +211,10 @@ Global {EEF22C21-F380-4980-B72C-F14488369333}.Debug|Any CPU.Build.0 = Debug|Any CPU {EEF22C21-F380-4980-B72C-F14488369333}.Release|Any CPU.ActiveCfg = Release|Any CPU {EEF22C21-F380-4980-B72C-F14488369333}.Release|Any CPU.Build.0 = Release|Any CPU + {9B15A0A0-BD6B-40B0-90D4-848BC3E4AF98}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {9B15A0A0-BD6B-40B0-90D4-848BC3E4AF98}.Debug|Any CPU.Build.0 = Debug|Any CPU + {9B15A0A0-BD6B-40B0-90D4-848BC3E4AF98}.Release|Any CPU.ActiveCfg = Release|Any CPU + {9B15A0A0-BD6B-40B0-90D4-848BC3E4AF98}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -244,6 +251,7 @@ Global {5E488583-391E-4E15-83C1-7301B4FE79AE} = {B337509B-75F9-4851-821F-9BBE87C4E4BC} {7191E567-38DF-4879-82E1-73EC618AFCAC} = {A0F5CC7E-155F-4726-8DEB-E966950B3FE9} {EEF22C21-F380-4980-B72C-F14488369333} = {15070C49-A507-4844-BCFE-D319CFBC9A63} + {9B15A0A0-BD6B-40B0-90D4-848BC3E4AF98} = {F88D727A-9F9C-43D9-90B1-D4A02BF8BC98} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {63A57886-054B-476C-AAE1-8D7C8917682E} diff --git a/sample/EasyCaching.Demo.Locks/Controllers/LocksController.cs b/sample/EasyCaching.Demo.Locks/Controllers/LocksController.cs new file mode 100644 index 00000000..c7cf7530 --- /dev/null +++ b/sample/EasyCaching.Demo.Locks/Controllers/LocksController.cs @@ -0,0 +1,70 @@ +namespace EasyCaching.Demo.Locks.Controllers; + +[Route("api/[controller]")] +public class LocksController : Controller +{ + private readonly IDistributedLockFactory _distributedLockFactory; + + public LocksController(IDistributedLockFactory distributedLockFactory) + { + _distributedLockFactory = distributedLockFactory; + } + + [HttpPost("distributed-locking")] + public async Task DistributedLockingOperation(int millisecondsTimeout) + { + using var distributedLock = _distributedLockFactory.CreateLock("DefaultRedis", "YourKey"); + + try + { + if (await distributedLock.LockAsync(millisecondsTimeout)) + { + // Simulate operation + Thread.Sleep(2000); + } + else + { + // Proper error + } + } + catch (Exception ex) + { + // log error + throw; + } + finally + { + // release lock at the end + await distributedLock.ReleaseAsync(); + } + } + + [HttpPost("memory-locking")] + public async Task MemoryLockingOperation(int millisecondsTimeout) + { + using var memoryLock = _distributedLockFactory.CreateLock("DefaultInMemory", "YourKey"); + + try + { + if (await memoryLock.LockAsync(millisecondsTimeout)) + { + // Simulate operation + Thread.Sleep(2000); + } + else + { + // Proper error + } + } + catch (Exception ex) + { + // log error + throw; + } + finally + { + // release lock at the end + await memoryLock.ReleaseAsync(); + } + } +} diff --git a/sample/EasyCaching.Demo.Locks/EasyCaching.Demo.Locks.csproj b/sample/EasyCaching.Demo.Locks/EasyCaching.Demo.Locks.csproj new file mode 100644 index 00000000..dc06abc5 --- /dev/null +++ b/sample/EasyCaching.Demo.Locks/EasyCaching.Demo.Locks.csproj @@ -0,0 +1,20 @@ + + + + net6.0 + enable + enable + + + + + + + + + + + + + + diff --git a/sample/EasyCaching.Demo.Locks/GlobalUsings.cs b/sample/EasyCaching.Demo.Locks/GlobalUsings.cs new file mode 100644 index 00000000..838d0c76 --- /dev/null +++ b/sample/EasyCaching.Demo.Locks/GlobalUsings.cs @@ -0,0 +1,4 @@ +global using EasyCaching.Core.Configurations; +global using EasyCaching.Core.DistributedLock; +global using Microsoft.AspNetCore.Mvc; +global using EasyCaching.Redis.DistributedLock; \ No newline at end of file diff --git a/sample/EasyCaching.Demo.Locks/Program.cs b/sample/EasyCaching.Demo.Locks/Program.cs new file mode 100644 index 00000000..c2d00cdb --- /dev/null +++ b/sample/EasyCaching.Demo.Locks/Program.cs @@ -0,0 +1,53 @@ +var builder = WebApplication.CreateBuilder(args); + +// Add services to the container. + +builder.Services.AddControllers(); +// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle +builder.Services.AddEndpointsApiExplorer(); +builder.Services.AddSwaggerGen(); + +builder.Services.AddEasyCaching(option => +{ + //use memory cache + option.UseInMemory() + .UseMemoryLock(); // use memory lock + + //use redis cache + option.UseRedis(config => + { + config.DBConfig.Endpoints.Add(new ServerEndPoint("127.0.0.1", 6379)); + config.DBConfig.SyncTimeout = 10000; + config.DBConfig.AsyncTimeout = 10000; + config.SerializerName = "NewtonsoftJson"; + }) + .WithJson()//with josn serialization + .UseRedisLock(); // use distributed lock +}); + +#region How Inject Distributed and Memory lock + +// inject to use distributed lock +builder.Services.AddSingleton(); + +// inject to use memory lock +builder.Services.AddSingleton(); + +#endregion + +var app = builder.Build(); + +// Configure the HTTP request pipeline. +if (app.Environment.IsDevelopment()) +{ + app.UseSwagger(); + app.UseSwaggerUI(); +} + +app.UseHttpsRedirection(); + +app.UseAuthorization(); + +app.MapControllers(); + +app.Run(); diff --git a/sample/EasyCaching.Demo.Locks/appsettings.Development.json b/sample/EasyCaching.Demo.Locks/appsettings.Development.json new file mode 100644 index 00000000..0c208ae9 --- /dev/null +++ b/sample/EasyCaching.Demo.Locks/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/sample/EasyCaching.Demo.Locks/appsettings.json b/sample/EasyCaching.Demo.Locks/appsettings.json new file mode 100644 index 00000000..10f68b8c --- /dev/null +++ b/sample/EasyCaching.Demo.Locks/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +} From f26e1a026a719d54242c4f328f866a722f3eb37b Mon Sep 17 00:00:00 2001 From: "t.sarmis" Date: Thu, 2 Feb 2023 14:17:03 +0200 Subject: [PATCH 02/11] add stream-based rabbit mq bus --- EasyCaching.sln | 9 +- build/version.props | 1 + .../Configurations/RabbitMQBusOptions.cs | 2 +- .../EasyCachingOptionsExtensions.cs | 68 +++++ .../RabbitMQStreamBusOptionsExtension.cs | 43 +++ .../DefaultRabbitMQStreamBus.cs | 250 ++++++++++++++++++ .../EasyCaching.Bus.RabbitMQStream.csproj | 50 ++++ 7 files changed, 421 insertions(+), 2 deletions(-) create mode 100644 bus/EasyCaching.Bus.RabbitMQStream/Configurations/EasyCachingOptionsExtensions.cs create mode 100644 bus/EasyCaching.Bus.RabbitMQStream/Configurations/RabbitMQStreamBusOptionsExtension.cs create mode 100644 bus/EasyCaching.Bus.RabbitMQStream/DefaultRabbitMQStreamBus.cs create mode 100644 bus/EasyCaching.Bus.RabbitMQStream/EasyCaching.Bus.RabbitMQStream.csproj diff --git a/EasyCaching.sln b/EasyCaching.sln index a2d217c4..9ae4c577 100644 --- a/EasyCaching.sln +++ b/EasyCaching.sln @@ -77,7 +77,9 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EasyCaching.Bus.Zookeeper", EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EasyCaching.FasterKv", "src\EasyCaching.FasterKv\EasyCaching.FasterKv.csproj", "{7191E567-38DF-4879-82E1-73EC618AFCAC}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EasyCaching.Serialization.MemoryPack", "serialization\EasyCaching.Serialization.MemoryPack\EasyCaching.Serialization.MemoryPack.csproj", "{EEF22C21-F380-4980-B72C-F14488369333}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EasyCaching.Bus.RabbitMQStream", "bus\EasyCaching.Bus.RabbitMQStream\EasyCaching.Bus.RabbitMQStream.csproj", "{3C9D5E40-B3A5-4649-8B40-08094644B0FB}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EasyCaching.Serialization.MemoryPack", "serialization\EasyCaching.Serialization.MemoryPack\EasyCaching.Serialization.MemoryPack.csproj", "{EEF22C21-F380-4980-B72C-F14488369333}" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EasyCaching.Demo.Locks", "sample\EasyCaching.Demo.Locks\EasyCaching.Demo.Locks.csproj", "{9B15A0A0-BD6B-40B0-90D4-848BC3E4AF98}" EndProject @@ -211,6 +213,10 @@ Global {EEF22C21-F380-4980-B72C-F14488369333}.Debug|Any CPU.Build.0 = Debug|Any CPU {EEF22C21-F380-4980-B72C-F14488369333}.Release|Any CPU.ActiveCfg = Release|Any CPU {EEF22C21-F380-4980-B72C-F14488369333}.Release|Any CPU.Build.0 = Release|Any CPU + {3C9D5E40-B3A5-4649-8B40-08094644B0FB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {3C9D5E40-B3A5-4649-8B40-08094644B0FB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {3C9D5E40-B3A5-4649-8B40-08094644B0FB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {3C9D5E40-B3A5-4649-8B40-08094644B0FB}.Release|Any CPU.Build.0 = Release|Any CPU {9B15A0A0-BD6B-40B0-90D4-848BC3E4AF98}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {9B15A0A0-BD6B-40B0-90D4-848BC3E4AF98}.Debug|Any CPU.Build.0 = Debug|Any CPU {9B15A0A0-BD6B-40B0-90D4-848BC3E4AF98}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -251,6 +257,7 @@ Global {5E488583-391E-4E15-83C1-7301B4FE79AE} = {B337509B-75F9-4851-821F-9BBE87C4E4BC} {7191E567-38DF-4879-82E1-73EC618AFCAC} = {A0F5CC7E-155F-4726-8DEB-E966950B3FE9} {EEF22C21-F380-4980-B72C-F14488369333} = {15070C49-A507-4844-BCFE-D319CFBC9A63} + {3C9D5E40-B3A5-4649-8B40-08094644B0FB} = {B337509B-75F9-4851-821F-9BBE87C4E4BC} {9B15A0A0-BD6B-40B0-90D4-848BC3E4AF98} = {F88D727A-9F9C-43D9-90B1-D4A02BF8BC98} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution diff --git a/build/version.props b/build/version.props index 5dc47ec6..00acbff7 100644 --- a/build/version.props +++ b/build/version.props @@ -16,6 +16,7 @@ 1.9.1 1.9.1 1.9.1 + 1.9.1 1.9.1 1.9.1 1.9.1 diff --git a/bus/EasyCaching.Bus.RabbitMQ/Configurations/RabbitMQBusOptions.cs b/bus/EasyCaching.Bus.RabbitMQ/Configurations/RabbitMQBusOptions.cs index f5a09bf6..359568fe 100644 --- a/bus/EasyCaching.Bus.RabbitMQ/Configurations/RabbitMQBusOptions.cs +++ b/bus/EasyCaching.Bus.RabbitMQ/Configurations/RabbitMQBusOptions.cs @@ -6,7 +6,7 @@ /// RabbitMQ Bus options. /// public class RabbitMQBusOptions : BaseRabbitMQOptions - { + { /// /// Gets or sets the name of the queue. /// diff --git a/bus/EasyCaching.Bus.RabbitMQStream/Configurations/EasyCachingOptionsExtensions.cs b/bus/EasyCaching.Bus.RabbitMQStream/Configurations/EasyCachingOptionsExtensions.cs new file mode 100644 index 00000000..9edbb383 --- /dev/null +++ b/bus/EasyCaching.Bus.RabbitMQStream/Configurations/EasyCachingOptionsExtensions.cs @@ -0,0 +1,68 @@ +namespace Microsoft.Extensions.DependencyInjection +{ + using System; + using EasyCaching.Bus.RabbitMQ; + using EasyCaching.Bus.RabbitMQStream; + using EasyCaching.Core; + using EasyCaching.Core.Configurations; + using Microsoft.Extensions.Configuration; + + /// + /// EasyCaching options extensions. + /// + public static class EasyCachingOptionsExtensions + { + /// + /// Withs the RabbitMQStream bus (specify the config via hard code). + /// + /// Options. + /// Configure bus settings. + + public static EasyCachingOptions WithRabbitMQStreamBus( + this EasyCachingOptions options + , Action configure + ) + { + ArgumentCheck.NotNull(configure, nameof(configure)); + + options.RegisterExtension(new RabbitMQStreamBusOptionsExtension(configure)); + return options; + } + + /// + /// Withs the RabbitMQStream bus (read config from configuration file). + /// + /// Options. + /// The configuration. + /// The section name in the configuration file. + public static EasyCachingOptions WithRabbitMQStreamBus( + this EasyCachingOptions options + , IConfiguration configuration + , string sectionName = EasyCachingConstValue.RabbitMQBusSection + ) + { + var dbConfig = configuration.GetSection(sectionName); + var busOptions = new RabbitMQBusOptions(); + dbConfig.Bind(busOptions); + + void configure(RabbitMQBusOptions x) + { + x.HostName = busOptions.HostName; + x.Password = busOptions.Password; + x.Port = busOptions.Port; + x.QueueMessageExpires = busOptions.QueueMessageExpires; + x.RequestedConnectionTimeout = busOptions.RequestedConnectionTimeout; + //x.RouteKey = busOptions.RouteKey; + x.SocketReadTimeout = busOptions.SocketReadTimeout; + x.SocketWriteTimeout = busOptions.SocketWriteTimeout; + x.TopicExchangeName = busOptions.TopicExchangeName; + x.UserName = busOptions.UserName; + x.VirtualHost = busOptions.VirtualHost; + x.QueueName = busOptions.QueueName; + } + + options.RegisterExtension(new RabbitMQStreamBusOptionsExtension(configure)); + return options; + } + } +} \ No newline at end of file diff --git a/bus/EasyCaching.Bus.RabbitMQStream/Configurations/RabbitMQStreamBusOptionsExtension.cs b/bus/EasyCaching.Bus.RabbitMQStream/Configurations/RabbitMQStreamBusOptionsExtension.cs new file mode 100644 index 00000000..275cf5ae --- /dev/null +++ b/bus/EasyCaching.Bus.RabbitMQStream/Configurations/RabbitMQStreamBusOptionsExtension.cs @@ -0,0 +1,43 @@ +namespace EasyCaching.Bus.RabbitMQStream +{ + using System; + using EasyCaching.Bus.RabbitMQ; + using EasyCaching.Core.Bus; + using EasyCaching.Core.Configurations; + using global::RabbitMQ.Client; + using Microsoft.Extensions.DependencyInjection; + using Microsoft.Extensions.ObjectPool; + + /// + /// RabbitMQ Bus options extension. + /// + public class RabbitMQStreamBusOptionsExtension : IEasyCachingOptionsExtension + { + /// + /// The configure. + /// + private readonly Action configure; + + /// + /// Initializes a new instance of the class. + /// + /// Configure. + public RabbitMQStreamBusOptionsExtension(Action configure) + { + this.configure = configure; + } + + /// + /// Adds the services. + /// + /// Services. + public void AddServices(IServiceCollection services) + { + services.AddOptions(); + services.Configure(configure); + + services.AddSingleton, ModelPooledObjectPolicy>(); + services.AddSingleton(); + } + } +} diff --git a/bus/EasyCaching.Bus.RabbitMQStream/DefaultRabbitMQStreamBus.cs b/bus/EasyCaching.Bus.RabbitMQStream/DefaultRabbitMQStreamBus.cs new file mode 100644 index 00000000..e4f82948 --- /dev/null +++ b/bus/EasyCaching.Bus.RabbitMQStream/DefaultRabbitMQStreamBus.cs @@ -0,0 +1,250 @@ +using Microsoft.Extensions.Logging; + +namespace EasyCaching.Bus.RabbitMQ +{ + using System; + using System.Collections.Generic; + using System.Threading; + using System.Threading.Tasks; + using EasyCaching.Core; + using EasyCaching.Core.Bus; + using EasyCaching.Core.Serialization; + using global::RabbitMQ.Client; + using global::RabbitMQ.Client.Events; + using Microsoft.Extensions.ObjectPool; + using Microsoft.Extensions.Options; + + /// + /// Default RabbitMQ Bus. + /// + public class DefaultRabbitMQStreamBus : EasyCachingAbstractBus + { + /// + /// The subscriber connection. + /// + private readonly IConnection _subConnection; + + /// + /// The publish channel pool. + /// + private readonly ObjectPool _pubChannelPool; + + /// + /// The rabbitMQ Bus options. + /// + private readonly RabbitMQBusOptions _options; + + /// + /// The serializer. + /// + private readonly IEasyCachingSerializer _serializer; + + /// + /// The logger. + /// + private readonly ILogger _logger; + + /// + /// The identifier. + /// + private readonly string _busId; + + private static readonly Dictionary _streamArgs = new Dictionary + { + { "x-queue-type", "stream" }, + { "x-max-age", "5m" }, + { "x-stream-max-segment-size-bytes", 4_000_000 } + }; + + /// + /// Initializes a new instance of the class. + /// + /// Object policy. + /// RabbitMQ Options. + /// Serializer. + public DefaultRabbitMQStreamBus( + IPooledObjectPolicy objectPolicy + , IOptions rabbitMQOptions + , IEasyCachingSerializer serializer + , Lazy> logger) + { + this._options = rabbitMQOptions.Value; + this._serializer = serializer; + this._logger = logger.Value; + + _logger?.LogInformation("DefaultRabbitMQStreamBus: Initializing"); + try + { + var factory = new ConnectionFactory + { + HostName = _options.HostName, + UserName = _options.UserName, + Port = _options.Port, + Password = _options.Password, + VirtualHost = _options.VirtualHost, + RequestedConnectionTimeout = System.TimeSpan.FromMilliseconds(_options.RequestedConnectionTimeout), + SocketReadTimeout = System.TimeSpan.FromMilliseconds(_options.SocketReadTimeout), + SocketWriteTimeout = System.TimeSpan.FromMilliseconds(_options.SocketWriteTimeout), + ClientProvidedName = _options.ClientProvidedName + }; + + _subConnection = factory.CreateConnection(); + + _subConnection.ConnectionShutdown += (_, e) => + { + _logger?.LogError($"ConnectionShutdown: {e.ReplyText}"); + }; + + var provider = new DefaultObjectPoolProvider(); + + _pubChannelPool = provider.Create(objectPolicy); + + _busId = Guid.NewGuid().ToString("N"); + + BusName = "easycachingbus"; + } + catch (Exception ex) + { + _logger?.LogError(ex, $"DefaultRabbitMQStreamBus: Initializing failed ({ex.Message})"); + throw; + } + } + + /// + /// Publish the specified topic and message. + /// + /// Topic. + /// Message. + public override void BasePublish(string topic, EasyCachingMessage message) + { + var channel = _pubChannelPool.Get(); + + try + { + var body = _serializer.Serialize(message); + + channel.ExchangeDeclare(_options.TopicExchangeName, ExchangeType.Topic, true, false, null); + channel.BasicPublish(_options.TopicExchangeName, topic, false, null, body); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + finally + { + _pubChannelPool.Return(channel); + } + } + + /// + /// Publish the specified topic and message async. + /// + /// The async. + /// Topic. + /// Message. + /// Cancellation token. + public override Task BasePublishAsync(string topic, EasyCachingMessage message, CancellationToken cancellationToken = default(CancellationToken)) + { + var channel = _pubChannelPool.Get(); + try + { + var body = _serializer.Serialize(message); + + channel.ExchangeDeclare(_options.TopicExchangeName, ExchangeType.Topic, true, false, null); + channel.BasicPublish(_options.TopicExchangeName, topic, false, null, body); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + finally + { + _pubChannelPool.Return(channel); + } + return Task.CompletedTask; + } + + /// + /// Subscribe the specified topic and action. + /// + /// Topic. + /// Action. + public override void BaseSubscribe(string topic, Action action) + { + var queueName = $"rmq.stream.easycaching.{topic}"; + + Task.Factory.StartNew( + () => StartConsumer(queueName, topic), + TaskCreationOptions.LongRunning); + } + + /// + /// Subscribe the specified topic and action async. + /// + /// Topic. + /// Action. + /// Cancellation token. + public override Task BaseSubscribeAsync(string topic, Action action, CancellationToken cancellationToken = default(CancellationToken)) + { + _logger?.LogWarning($"BaseSubscribeAsync for {topic}"); + + var queueName = $"rmq.stream.easycaching.{topic}"; + + StartConsumer(queueName, topic); + return Task.CompletedTask; + } + + private void StartConsumer(string queueName, string topic) + { + _logger?.LogWarning($"Starting Consumer for {topic} ({queueName})"); + var channel = _subConnection.CreateModel(); + + channel.ModelShutdown += (_, e) => + { + _logger?.LogError($"ModelShutdown: {e.ReplyText}"); + }; + + // Streams require Qos setup + channel.BasicQos(0, 100, false); + channel.ExchangeDeclare(_options.TopicExchangeName, ExchangeType.Topic, true, false, null); + channel.QueueDeclare(queueName, true, false, false, _streamArgs); + // bind the queue with the exchange. + channel.QueueBind(queueName, _options.TopicExchangeName, topic); + var consumer = new EventingBasicConsumer(channel); + consumer.Received += OnMessage; + + consumer.ConsumerCancelled += (sender, e) => + { + _logger?.LogError($"EasyCaching.DefaultRabbitMQStreamBus.OnConsumerCancelled: (Q: {queueName})"); + }; + + consumer.Shutdown += (sender, e) => + { + _logger?.LogError($"EasyCaching.DefaultRabbitMQStreamBus.OnConsumerShutdown: (Q: {queueName}) {e.ReplyText}"); + StartConsumer(queueName, topic); + BaseOnReconnect(); + }; + + channel.BasicConsume(queueName, false, consumer); + } + + /// + /// Ons the message. + /// + /// Sender. + /// E. + private void OnMessage(object sender, BasicDeliverEventArgs e) + { + try + { + var message = _serializer.Deserialize(e.Body.ToArray()); + _logger?.LogDebug(string.Join(",", message.CacheKeys)); + BaseOnMessage(message); + } + finally + { + (sender as EventingBasicConsumer)?.Model.BasicAck(e.DeliveryTag, false); + } + } + } +} diff --git a/bus/EasyCaching.Bus.RabbitMQStream/EasyCaching.Bus.RabbitMQStream.csproj b/bus/EasyCaching.Bus.RabbitMQStream/EasyCaching.Bus.RabbitMQStream.csproj new file mode 100644 index 00000000..4a1d9b02 --- /dev/null +++ b/bus/EasyCaching.Bus.RabbitMQStream/EasyCaching.Bus.RabbitMQStream.csproj @@ -0,0 +1,50 @@ + + + + + netstandard2.0;net6.0 + ncc;Thomas Sarmis + ncc;Thomas Sarmis + $(EasyCachingRabbitStreamBusPackageVersion) + + + A simple caching bus(message bus) based on RabbitMQ using amqp Streams. + + Bus,Hybrid,RabbitMQ,Caching,Cache + https://github.com/dotnetcore/EasyCaching + LICENSE + https://github.com/dotnetcore/EasyCaching + https://github.com/dotnetcore/EasyCaching + nuget-icon.png + + $(EasyCachingRabbitStreamBusPackageNotes) + + + + + true + $(NoWarn);1591 + + + + + + + + + + + + + + + + + + + + + + + + From 4e939bfb68f16b99bc85ae36e07b8c1eefe7e5b3 Mon Sep 17 00:00:00 2001 From: Memoyu Date: Tue, 19 Sep 2023 17:18:57 +0800 Subject: [PATCH 03/11] fix: fix some warning --- .../DefaultRabbitMQStreamBus.cs | 1 + sample/EasyCaching.Demo.Locks/Controllers/LocksController.cs | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/bus/EasyCaching.Bus.RabbitMQStream/DefaultRabbitMQStreamBus.cs b/bus/EasyCaching.Bus.RabbitMQStream/DefaultRabbitMQStreamBus.cs index e4f82948..ac602cdb 100644 --- a/bus/EasyCaching.Bus.RabbitMQStream/DefaultRabbitMQStreamBus.cs +++ b/bus/EasyCaching.Bus.RabbitMQStream/DefaultRabbitMQStreamBus.cs @@ -62,6 +62,7 @@ public class DefaultRabbitMQStreamBus : EasyCachingAbstractBus /// Object policy. /// RabbitMQ Options. /// Serializer. + /// Logger. public DefaultRabbitMQStreamBus( IPooledObjectPolicy objectPolicy , IOptions rabbitMQOptions diff --git a/sample/EasyCaching.Demo.Locks/Controllers/LocksController.cs b/sample/EasyCaching.Demo.Locks/Controllers/LocksController.cs index c7cf7530..b6400a70 100644 --- a/sample/EasyCaching.Demo.Locks/Controllers/LocksController.cs +++ b/sample/EasyCaching.Demo.Locks/Controllers/LocksController.cs @@ -30,7 +30,7 @@ public async Task DistributedLockingOperation(int millisecondsTimeout) catch (Exception ex) { // log error - throw; + throw new Exception("Exception", ex); } finally { @@ -59,7 +59,7 @@ public async Task MemoryLockingOperation(int millisecondsTimeout) catch (Exception ex) { // log error - throw; + throw new Exception("Exception", ex); } finally { From c34e22e87f62328966e023e1a67b31ea86247b4a Mon Sep 17 00:00:00 2001 From: Memoyu Date: Tue, 19 Sep 2023 17:45:34 +0800 Subject: [PATCH 04/11] fix: fix some test warning and update json component for EasyCaching.LiteDB --- .../EasyCaching.LiteDB.csproj | 2 +- .../FasterKvCachingProviderTest.cs | 32 ------------------- .../CachingTests/MemcachedProviderTest.cs | 11 ------- .../MemoryPackSerializerTest.cs | 1 + 4 files changed, 2 insertions(+), 44 deletions(-) diff --git a/src/EasyCaching.LiteDB/EasyCaching.LiteDB.csproj b/src/EasyCaching.LiteDB/EasyCaching.LiteDB.csproj index 2f6f6724..4c3ccb2b 100644 --- a/src/EasyCaching.LiteDB/EasyCaching.LiteDB.csproj +++ b/src/EasyCaching.LiteDB/EasyCaching.LiteDB.csproj @@ -35,7 +35,7 @@ - + diff --git a/test/EasyCaching.UnitTests/CachingTests/FasterKvCachingProviderTest.cs b/test/EasyCaching.UnitTests/CachingTests/FasterKvCachingProviderTest.cs index d16ecf8c..f344a5d7 100644 --- a/test/EasyCaching.UnitTests/CachingTests/FasterKvCachingProviderTest.cs +++ b/test/EasyCaching.UnitTests/CachingTests/FasterKvCachingProviderTest.cs @@ -76,17 +76,6 @@ protected override void Get_Parallel_Should_Succeed() { } - public override Task GetAllByPrefix_Async_Should_Throw_ArgumentNullException_When_Prefix_IsNullOrWhiteSpace( - string preifx) - { - return Task.CompletedTask; - } - - public override void GetAllByPrefix_Should_Throw_ArgumentNullException_When_CacheKey_IsNullOrWhiteSpace( - string prefix) - { - } - protected override Task Get_Count_Async_With_Prefix_Should_Succeed() { return Task.CompletedTask; @@ -132,31 +121,10 @@ protected override void GetExpiration_Should_Succeed() { } - public override void RemoveByPattern_Should_Succeed() - { - } - - public override Task RemoveByPatternAsync_Should_Succeed() - { - return Task.CompletedTask; - } - - public override Task RemoveByPrefix_Async_Should_Throw_ArgumentNullException_When_Prefix_IsNullOrWhiteSpace( - string preifx) - - { - return Task.CompletedTask; - } - protected override void RemoveByPrefix_Should_Succeed() { } - public override void RemoveByPrefix_Should_Throw_ArgumentNullException_When_CacheKey_IsNullOrWhiteSpace( - string prefix) - { - } - protected override Task RemoveByPrefixAsync_Should_Succeed() { return Task.CompletedTask; diff --git a/test/EasyCaching.UnitTests/CachingTests/MemcachedProviderTest.cs b/test/EasyCaching.UnitTests/CachingTests/MemcachedProviderTest.cs index 0d5cf30a..74ab4ee3 100644 --- a/test/EasyCaching.UnitTests/CachingTests/MemcachedProviderTest.cs +++ b/test/EasyCaching.UnitTests/CachingTests/MemcachedProviderTest.cs @@ -115,17 +115,6 @@ protected override void GetByPrefix_Should_Succeed() { } - [Fact] - public override void RemoveByPattern_Should_Succeed() - { - } - - [Fact] - public override async Task RemoveByPatternAsync_Should_Succeed() - { - await Task.FromResult(1); - } - [Fact] protected override async Task GetByPrefixAsync_Should_Succeed() { diff --git a/test/EasyCaching.UnitTests/SerializerTests/MemoryPackSerializerTest.cs b/test/EasyCaching.UnitTests/SerializerTests/MemoryPackSerializerTest.cs index 32cbbfb9..6f65205e 100644 --- a/test/EasyCaching.UnitTests/SerializerTests/MemoryPackSerializerTest.cs +++ b/test/EasyCaching.UnitTests/SerializerTests/MemoryPackSerializerTest.cs @@ -14,6 +14,7 @@ public MemoryPackSerializerTest() } //This should be overrided becuse it is not supported by memory-pack + [Fact] public override void DeserializeObject_should_Succeed() { Person input = new("test", "test1"); From 2577ee8d015209b7168c6c7a3760f2cf0f5c0baf Mon Sep 17 00:00:00 2001 From: Memoyu Date: Wed, 20 Sep 2023 10:13:20 +0800 Subject: [PATCH 05/11] fix: update actions version #474 --- .github/workflows/build.yml | 4 ++-- .github/workflows/buildandtest.yml | 4 ++-- .github/workflows/release.yml | 8 ++++---- .github/workflows/release_stable.yml | 8 ++++---- 4 files changed, 12 insertions(+), 12 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index ad85ec95..2b4ab1a7 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -16,9 +16,9 @@ jobs: os: [ windows-latest ] steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v4 - name: Setup .NET SDK 6.0.x - uses: actions/setup-dotnet@v1 + uses: actions/setup-dotnet@v3 with: dotnet-version: 6.0.x diff --git a/.github/workflows/buildandtest.yml b/.github/workflows/buildandtest.yml index fb79d718..2466ba79 100644 --- a/.github/workflows/buildandtest.yml +++ b/.github/workflows/buildandtest.yml @@ -38,9 +38,9 @@ jobs: - 11212:11211 steps: - - uses: actions/checkout@v2 + - uses: actions/checkout@v4 - name: Setup .NET SDK 6.0.x - uses: actions/setup-dotnet@v1 + uses: actions/setup-dotnet@v3 with: dotnet-version: 6.0.x diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index ef7049cc..f21feffd 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -13,9 +13,9 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v1 + - uses: actions/checkout@v4 - name: Setup .NET Core - uses: actions/setup-dotnet@v1 + uses: actions/setup-dotnet@v3 with: dotnet-version: 6.0.x - name: Build with dotnet @@ -23,7 +23,7 @@ jobs: - name: Pack with dotnet run: dotnet pack /home/runner/work/EasyCaching/EasyCaching/EasyCaching.sln --version-suffix alpha`date +%Y%m%d%H%M%S` -o /home/runner/work/nugetpkgs -c Release --no-build - name: Upload artifact - uses: actions/upload-artifact@v1 + uses: actions/upload-artifact@v3 with: name: nugetpkgs path: /home/runner/work/nugetpkgs @@ -35,7 +35,7 @@ jobs: steps: - name: Download build artifacts - uses: actions/download-artifact@v1 + uses: actions/download-artifact@v3 with: name: nugetpkgs - name: list nugetpkgs diff --git a/.github/workflows/release_stable.yml b/.github/workflows/release_stable.yml index cb7a7eca..a9137b7a 100644 --- a/.github/workflows/release_stable.yml +++ b/.github/workflows/release_stable.yml @@ -11,9 +11,9 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v1 + - uses: actions/checkout@v4 - name: Setup .NET Core - uses: actions/setup-dotnet@v1 + uses: actions/setup-dotnet@v3 with: dotnet-version: 6.0.x - name: Build with dotnet @@ -21,7 +21,7 @@ jobs: - name: Pack with dotnet run: dotnet pack /home/runner/work/EasyCaching/EasyCaching/EasyCaching.sln -o /home/runner/work/nugetpkgs -c Release --no-build - name: Upload artifact - uses: actions/upload-artifact@v1 + uses: actions/upload-artifact@v3 with: name: nugetpkgs path: /home/runner/work/nugetpkgs @@ -33,7 +33,7 @@ jobs: steps: - name: Download build artifacts - uses: actions/download-artifact@v1 + uses: actions/download-artifact@v3 with: name: nugetpkgs - name: list nugetpkgs From c53d63e612e6674f6666ca3f960cf770aee8d2cd Mon Sep 17 00:00:00 2001 From: Memoyu Date: Wed, 20 Sep 2023 10:25:08 +0800 Subject: [PATCH 06/11] fix: CI error --- .../FasterKvCachingProviderTest.cs | 35 +++++++++++++++++++ .../CachingTests/MemcachedProviderTest.cs | 11 ++++++ 2 files changed, 46 insertions(+) diff --git a/test/EasyCaching.UnitTests/CachingTests/FasterKvCachingProviderTest.cs b/test/EasyCaching.UnitTests/CachingTests/FasterKvCachingProviderTest.cs index f344a5d7..6543931b 100644 --- a/test/EasyCaching.UnitTests/CachingTests/FasterKvCachingProviderTest.cs +++ b/test/EasyCaching.UnitTests/CachingTests/FasterKvCachingProviderTest.cs @@ -76,16 +76,49 @@ protected override void Get_Parallel_Should_Succeed() { } + public override Task GetAllByPrefix_Async_Should_Throw_ArgumentNullException_When_Prefix_IsNullOrWhiteSpace( + string preifx) + { + return Task.CompletedTask; + } + + public override void GetAllByPrefix_Should_Throw_ArgumentNullException_When_CacheKey_IsNullOrWhiteSpace( + string prefix) + { + } + protected override Task Get_Count_Async_With_Prefix_Should_Succeed() { return Task.CompletedTask; } + public override void RemoveByPattern_Should_Succeed() + { + } + + public override Task RemoveByPatternAsync_Should_Succeed() + { + return Task.CompletedTask; + } + + public override Task RemoveByPrefix_Async_Should_Throw_ArgumentNullException_When_Prefix_IsNullOrWhiteSpace( + string preifx) + + { + return Task.CompletedTask; + } + + public override void RemoveByPrefix_Should_Throw_ArgumentNullException_When_CacheKey_IsNullOrWhiteSpace( + string prefix) + { + } + protected override Task Get_Count_Async_Without_Prefix_Should_Succeed() { return Task.CompletedTask; } + protected override void Get_Count_With_Prefix_Should_Succeed() { } @@ -107,6 +140,8 @@ protected override Task GetByPrefixAsync_Should_Succeed() return Task.CompletedTask; } + + protected override Task GetByPrefixAsync_With_Not_Existed_Prefix_Should_Return_Empty_Dict() { return Task.CompletedTask; diff --git a/test/EasyCaching.UnitTests/CachingTests/MemcachedProviderTest.cs b/test/EasyCaching.UnitTests/CachingTests/MemcachedProviderTest.cs index 74ab4ee3..0d5cf30a 100644 --- a/test/EasyCaching.UnitTests/CachingTests/MemcachedProviderTest.cs +++ b/test/EasyCaching.UnitTests/CachingTests/MemcachedProviderTest.cs @@ -115,6 +115,17 @@ protected override void GetByPrefix_Should_Succeed() { } + [Fact] + public override void RemoveByPattern_Should_Succeed() + { + } + + [Fact] + public override async Task RemoveByPatternAsync_Should_Succeed() + { + await Task.FromResult(1); + } + [Fact] protected override async Task GetByPrefixAsync_Should_Succeed() { From 125917a68c2f62bec895ebaf7af02195c86388be Mon Sep 17 00:00:00 2001 From: Bastien Didier Date: Wed, 27 Sep 2023 11:57:23 +0200 Subject: [PATCH 07/11] always use utc to compare the expiry --- .../DefaultLiteDBCachingProvider.cs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/EasyCaching.LiteDB/DefaultLiteDBCachingProvider.cs b/src/EasyCaching.LiteDB/DefaultLiteDBCachingProvider.cs index 908919a6..bf2e5809 100644 --- a/src/EasyCaching.LiteDB/DefaultLiteDBCachingProvider.cs +++ b/src/EasyCaching.LiteDB/DefaultLiteDBCachingProvider.cs @@ -113,7 +113,7 @@ public override bool BaseExists(string cacheKey) { ArgumentCheck.NotNullOrWhiteSpace(cacheKey, nameof(cacheKey)); - var dbResult = _cache.Count(fc => fc.cachekey == cacheKey && fc.expiration > DateTimeOffset.Now.ToUnixTimeSeconds()); + var dbResult = _cache.Count(fc => fc.cachekey == cacheKey && fc.expiration > DateTimeOffset.UtcNow.ToUnixTimeSeconds()); return dbResult > 0; } @@ -131,7 +131,7 @@ public override CacheValue BaseGet(string cacheKey, Func dataRetriever, ArgumentCheck.NotNullOrWhiteSpace(cacheKey, nameof(cacheKey)); ArgumentCheck.NotNegativeOrZero(expiration, nameof(expiration)); - var cacheItem = _cache.FindOne(c => c.cachekey == cacheKey && c.expiration > DateTimeOffset.Now.ToUnixTimeSeconds()); + var cacheItem = _cache.FindOne(c => c.cachekey == cacheKey && c.expiration > DateTimeOffset.UtcNow.ToUnixTimeSeconds()); if (cacheItem != null) { @@ -164,7 +164,7 @@ public override CacheValue BaseGet(string cacheKey) { ArgumentCheck.NotNullOrWhiteSpace(cacheKey, nameof(cacheKey)); - var cacheItem = _cache.FindOne(c => c.cachekey == cacheKey && c.expiration > DateTimeOffset.Now.ToUnixTimeSeconds()); + var cacheItem = _cache.FindOne(c => c.cachekey == cacheKey && c.expiration > DateTimeOffset.UtcNow.ToUnixTimeSeconds()); if (cacheItem != null || _options.CacheNulls) { @@ -317,7 +317,7 @@ public override IDictionary> BaseGetAll(IEnumerable lst.Contains(c.cachekey) && c.expiration > DateTimeOffset.Now.ToUnixTimeSeconds()).ToList(); + var list = _cache.Find(c => lst.Contains(c.cachekey) && c.expiration > DateTimeOffset.UtcNow.ToUnixTimeSeconds()).ToList(); return GetDict(list); } @@ -354,7 +354,7 @@ private IDictionary> GetDict(List list) public override IDictionary> BaseGetByPrefix(string prefix) { ArgumentCheck.NotNullOrWhiteSpace(prefix, nameof(prefix)); - var list = _cache.Find(c => c.cachekey.StartsWith(prefix) && c.expiration > DateTimeOffset.Now.ToUnixTimeSeconds()).ToList(); + var list = _cache.Find(c => c.cachekey.StartsWith(prefix) && c.expiration > DateTimeOffset.UtcNow.ToUnixTimeSeconds()).ToList(); return GetDict(list); } @@ -380,11 +380,11 @@ public override int BaseGetCount(string prefix = "") { if (string.IsNullOrWhiteSpace(prefix)) { - return _cache.Count(c => c.expiration > DateTimeOffset.Now.ToUnixTimeSeconds()); + return _cache.Count(c => c.expiration > DateTimeOffset.UtcNow.ToUnixTimeSeconds()); } else { - return _cache.Count(c => c.cachekey.StartsWith(prefix) && c.expiration > DateTimeOffset.Now.ToUnixTimeSeconds()); + return _cache.Count(c => c.cachekey.StartsWith(prefix) && c.expiration > DateTimeOffset.UtcNow.ToUnixTimeSeconds()); } } @@ -413,7 +413,7 @@ public override bool BaseTrySet(string cacheKey, T cacheValue, TimeSpan expir expiration.Add(new TimeSpan(0, 0, addSec)); } - var r = _cache.FindOne(c => c.cachekey == cacheKey && c.expiration > DateTimeOffset.Now.ToUnixTimeSeconds()); + var r = _cache.FindOne(c => c.cachekey == cacheKey && c.expiration > DateTimeOffset.UtcNow.ToUnixTimeSeconds()); bool result = false; if (r == null) { From 8f2c764bb5a446588ae2037aca7f4ff2692c27f7 Mon Sep 17 00:00:00 2001 From: Memoyu Date: Thu, 12 Oct 2023 23:16:06 +0800 Subject: [PATCH 08/11] Upgrade CSRedisCore version to 3.8.671 (#499) * fix: Upgrade CSRedisCore version to 3.8.671 #496 * test: add Use_Redis6_ACL test --- .../EasyCaching.CSRedis.csproj | 2 +- .../CSRedisCachingProviderTest.cs | 62 +++++++++++++------ 2 files changed, 45 insertions(+), 19 deletions(-) diff --git a/src/EasyCaching.CSRedis/EasyCaching.CSRedis.csproj b/src/EasyCaching.CSRedis/EasyCaching.CSRedis.csproj index 9ddaee11..c651637a 100644 --- a/src/EasyCaching.CSRedis/EasyCaching.CSRedis.csproj +++ b/src/EasyCaching.CSRedis/EasyCaching.CSRedis.csproj @@ -32,7 +32,7 @@ - + diff --git a/test/EasyCaching.UnitTests/CachingTests/CSRedisCachingProviderTest.cs b/test/EasyCaching.UnitTests/CachingTests/CSRedisCachingProviderTest.cs index c90a2343..8ded8e1a 100644 --- a/test/EasyCaching.UnitTests/CachingTests/CSRedisCachingProviderTest.cs +++ b/test/EasyCaching.UnitTests/CachingTests/CSRedisCachingProviderTest.cs @@ -41,6 +41,32 @@ protected override IEasyCachingProvider CreateCachingProvider(Action(); } + /*[Fact] + public async void Use_Redis6_ACL_Should_Succeed() + { + IServiceCollection services = new ServiceCollection(); + services.AddEasyCaching(x => + x.UseCSRedis(options => + { + options.DBConfig = new CSRedisDBOptions + { + ConnectionStrings = new System.Collections.Generic.List + { + "127.0.0.1:6388,user=user,password=userpwd,defaultDatabase=13,poolsize=10" + } + }; + }).UseCSRedisLock().WithJson(EasyCachingConstValue.DefaultCSRedisName)); + IServiceProvider serviceProvider = services.BuildServiceProvider(); + var provider = serviceProvider.GetService(); + var key = Guid.NewGuid().ToString(); + var value = "value"; + await provider.SetAsync(key, value, TimeSpan.FromSeconds(20)); + + var getValue = await provider.GetAsync(key); + + Assert.Equal(value, getValue?.Value); + }*/ + [Fact] public void GetDatabase_Should_Succeed() { @@ -148,7 +174,7 @@ public CSRedisCachingProviderWithKeyPrefixTest() config.SerializerName = "json"; }, "WithKeyPrefix"); - + x.WithJson("json"); }); @@ -194,7 +220,7 @@ public void RemoveByPrefixTest() Assert.False(val3.HasValue); Assert.False(val4.HasValue); } - + [Theory] [InlineData("WithKeyPrefix")] [InlineData("NotKeyPrefix")] @@ -219,7 +245,7 @@ public void RemoveByKeyPatternTest(string provider) var val6 = WithKeyPrefix.Get("sky:birds:bar"); var val7 = WithKeyPrefix.Get("sky:birds:test:bar"); var val8 = WithKeyPrefix.Get("akey"); - + Assert.True(val1.HasValue); Assert.True(val2.HasValue); Assert.True(val3.HasValue); @@ -231,15 +257,15 @@ public void RemoveByKeyPatternTest(string provider) // contains WithKeyPrefix.RemoveByPattern("*:pots:*"); - + // postfix WithKeyPrefix.RemoveByPattern("*foo"); - + // prefix - WithKeyPrefix.RemoveByPattern("sky*"); - + WithKeyPrefix.RemoveByPattern("sky*"); + // exact - WithKeyPrefix.RemoveByPattern("akey"); + WithKeyPrefix.RemoveByPattern("akey"); var val9 = WithKeyPrefix.Get("garden:pots:flowers"); var val10 = WithKeyPrefix.Get("garden:pots:flowers:test"); @@ -249,7 +275,7 @@ public void RemoveByKeyPatternTest(string provider) var val14 = WithKeyPrefix.Get("sky:birds:bar"); var val15 = WithKeyPrefix.Get("sky:birds:test:bar"); var val16 = WithKeyPrefix.Get("akey"); - + Assert.False(val9.HasValue); Assert.False(val10.HasValue); Assert.True(val11.HasValue); @@ -259,8 +285,8 @@ public void RemoveByKeyPatternTest(string provider) Assert.False(val15.HasValue); Assert.False(val16.HasValue); } - - [Theory] + + [Theory] [InlineData("WithKeyPrefix")] [InlineData("NotKeyPrefix")] public async Task RemoveByKeyPatternAsyncTest(string provider) @@ -284,7 +310,7 @@ public async Task RemoveByKeyPatternAsyncTest(string provider) var val6 = WithKeyPrefix.Get("sky:birds:bar"); var val7 = WithKeyPrefix.Get("sky:birds:test:bar"); var val8 = WithKeyPrefix.Get("akey"); - + Assert.True(val1.HasValue); Assert.True(val2.HasValue); Assert.True(val3.HasValue); @@ -296,15 +322,15 @@ public async Task RemoveByKeyPatternAsyncTest(string provider) // contains await WithKeyPrefix.RemoveByPatternAsync("*:pots:*"); - + // postfix await WithKeyPrefix.RemoveByPatternAsync("*foo"); - + // prefix - await WithKeyPrefix.RemoveByPatternAsync("sky*"); - + await WithKeyPrefix.RemoveByPatternAsync("sky*"); + // exact - await WithKeyPrefix.RemoveByPatternAsync("akey"); + await WithKeyPrefix.RemoveByPatternAsync("akey"); var val9 = WithKeyPrefix.Get("garden:pots:flowers"); var val10 = WithKeyPrefix.Get("garden:pots:flowers:test"); @@ -314,7 +340,7 @@ public async Task RemoveByKeyPatternAsyncTest(string provider) var val14 = WithKeyPrefix.Get("sky:birds:bar"); var val15 = WithKeyPrefix.Get("sky:birds:test:bar"); var val16 = WithKeyPrefix.Get("akey"); - + Assert.False(val9.HasValue); Assert.False(val10.HasValue); Assert.True(val11.HasValue); From 151be2b646d3dcb6dbf62736f302e1d3308936b8 Mon Sep 17 00:00:00 2001 From: Memoyu Date: Fri, 13 Oct 2023 08:41:12 +0800 Subject: [PATCH 09/11] Fix no check expires when get cache count in memory cache (#498) * fix: no check expires when get cache count in memory cache * styles: format code #497 * feat: add test --- .../Internal/InMemoryCaching.cs | 12 ++++++------ .../CachingTests/MemoryCachingProviderTest.cs | 15 +++++++++++++++ 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/src/EasyCaching.InMemory/Internal/InMemoryCaching.cs b/src/EasyCaching.InMemory/Internal/InMemoryCaching.cs index 408f7fa8..913ebb10 100644 --- a/src/EasyCaching.InMemory/Internal/InMemoryCaching.cs +++ b/src/EasyCaching.InMemory/Internal/InMemoryCaching.cs @@ -49,8 +49,8 @@ public void Clear(string prefix = "") public int GetCount(string prefix = "") { return string.IsNullOrWhiteSpace(prefix) - ? _memory.Count - : _memory.Count(x => x.Key.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)); + ? _memory.Values.Where(x => x.ExpiresAt > SystemClock.UtcNow).Count() + : _memory.Values.Where(x => x.Key.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) && x.ExpiresAt > SystemClock.UtcNow).Count(); } internal void RemoveExpiredKey(string key) @@ -283,7 +283,7 @@ public int RemoveByPattern(string searchKey, SearchKeyPattern searchPattern) public IEnumerable GetAllKeys(string prefix) { return _memory.Values.Where(x => x.Key.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) && x.ExpiresAt > SystemClock.UtcNow) - .Select(x=> x.Key).ToList(); + .Select(x => x.Key).ToList(); } private static bool FilterByPattern(string key, string searchKey, SearchKeyPattern searchKeyPattern) @@ -314,10 +314,10 @@ public IDictionary> GetAll(IEnumerable keys) public IDictionary> GetAll(string prefix = "") { - var values = string.IsNullOrEmpty(prefix) - ? _memory.Values.Where(x => x.ExpiresAt > SystemClock.UtcNow) + var values = string.IsNullOrEmpty(prefix) + ? _memory.Values.Where(x => x.ExpiresAt > SystemClock.UtcNow) : _memory.Values.Where(x => x.Key.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) && x.ExpiresAt > SystemClock.UtcNow); - + return values.ToDictionary(k => k.Key, v => new CacheValue(v.GetValue(_options.EnableReadDeepClone), true)); } diff --git a/test/EasyCaching.UnitTests/CachingTests/MemoryCachingProviderTest.cs b/test/EasyCaching.UnitTests/CachingTests/MemoryCachingProviderTest.cs index 899b2589..0795a6ea 100644 --- a/test/EasyCaching.UnitTests/CachingTests/MemoryCachingProviderTest.cs +++ b/test/EasyCaching.UnitTests/CachingTests/MemoryCachingProviderTest.cs @@ -155,6 +155,21 @@ public void Evicted_Event_Should_Trigger_When_GetExpiredItems() _provider.Get(key1); System.Threading.Thread.Sleep(500); } + + [Fact] + public async void Issues497_GetCountAsync_Check_Expires_Test() + { + for (int i = 0; i < 9; i++) + { + await _provider.SetAsync(Guid.NewGuid().ToString(), $"value-{i}", TimeSpan.FromSeconds(5)); + } + + Assert.Equal(9, await _provider.GetCountAsync()); + + await Task.Delay(5000); + + Assert.Equal(0, await _provider.GetCountAsync()); + } } public class MemoryCachingProviderWithFactoryTest : BaseCachingProviderWithFactoryTest From b3c34dcb7560b7a4307694d6d8b72eaac700ca69 Mon Sep 17 00:00:00 2001 From: Catcher Wong Date: Sun, 15 Oct 2023 10:00:42 +0000 Subject: [PATCH 10/11] chore: fix release wf error (#500) --- .github/workflows/release.yml | 1 + .github/workflows/release_stable.yml | 1 + 2 files changed, 2 insertions(+) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index f21feffd..61396945 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -38,6 +38,7 @@ jobs: uses: actions/download-artifact@v3 with: name: nugetpkgs + path: nugetpkgs - name: list nugetpkgs run: ls nugetpkgs - name: Release diff --git a/.github/workflows/release_stable.yml b/.github/workflows/release_stable.yml index a9137b7a..b4448612 100644 --- a/.github/workflows/release_stable.yml +++ b/.github/workflows/release_stable.yml @@ -36,6 +36,7 @@ jobs: uses: actions/download-artifact@v3 with: name: nugetpkgs + path: nugetpkgs - name: list nugetpkgs run: ls nugetpkgs - name: Release From 36516bdbf9efbbcd5cb70e79a992f9f43c71523a Mon Sep 17 00:00:00 2001 From: catcherwong Date: Tue, 31 Oct 2023 00:32:27 +0000 Subject: [PATCH 11/11] update version to 1.9.2 Signed-off-by: catcherwong --- build/releasenotes.props | 5 ++++ build/version.props | 50 ++++++++++++++++++++-------------------- 2 files changed, 30 insertions(+), 25 deletions(-) diff --git a/build/releasenotes.props b/build/releasenotes.props index 1fe50f01..68666432 100644 --- a/build/releasenotes.props +++ b/build/releasenotes.props @@ -14,6 +14,7 @@ 1. Upgrading dependencies. + 2. Fix no check expires when get cache count 1. Upgrading dependencies. @@ -59,6 +60,7 @@ 1. Upgrading dependencies. + 2. Always use utc to compare the expiry 1. Upgrading dependencies. @@ -69,5 +71,8 @@ 1. Upgrading dependencies. + + 1. Initial release. + diff --git a/build/version.props b/build/version.props index 00acbff7..18841930 100644 --- a/build/version.props +++ b/build/version.props @@ -1,29 +1,29 @@ - 1.9.1 - 1.9.1 - 1.9.1 - 1.9.1 - 1.9.1 - 1.9.1 - 1.9.1 - 1.9.1 - 1.9.1 - 1.9.1 - 1.9.1 - 1.9.1 - 1.9.1 - 1.9.1 - 1.9.1 - 1.9.1 - 1.9.1 - 1.9.1 - 1.9.1 - 1.9.1 - 1.9.1 - 1.9.1 - 1.9.1 - 1.9.1 - 1.9.1 + 1.9.2 + 1.9.2 + 1.9.2 + 1.9.2 + 1.9.2 + 1.9.2 + 1.9.2 + 1.9.2 + 1.9.2 + 1.9.2 + 1.9.2 + 1.9.2 + 1.9.2 + 1.9.2 + 1.9.2 + 1.9.2 + 1.9.2 + 1.9.2 + 1.9.2 + 1.9.2 + 1.9.2 + 1.9.2 + 1.9.2 + 1.9.2 + 1.9.2