using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Options; using StackExchange.Redis; using System.Collections.Concurrent; namespace HTEX.Complex.Service.AzureRedis { public class AzureRedisFactoryOptions { public string Name { get; set; } public string RedisConnectionString { get; set; } } public static class AzureRedisFactoryExtensions { public static IServiceCollection AddAzureRedis(this IServiceCollection services, string connectionString, string name = "Default") { if (services == null) throw new ArgumentNullException(nameof(services)); if (connectionString == null) throw new ArgumentNullException(nameof(connectionString)); services.TryAddSingleton(); services.Configure(name, o => { o.Name = name; o.RedisConnectionString = connectionString; }); return services; } } public class AzureRedisFactory { private readonly IServiceProvider _services; private readonly IOptionsMonitor _optionsMonitor; private readonly ILogger _logger; private ConcurrentDictionary ConnectionMultiplexers { get; } = new ConcurrentDictionary(); public AzureRedisFactory(IServiceProvider services, IOptionsMonitor optionsMonitor, ILogger logger) { if (services == null) throw new ArgumentNullException(nameof(services)); if (optionsMonitor == null) throw new ArgumentNullException(nameof(optionsMonitor)); _services = services; _optionsMonitor = optionsMonitor; _logger = logger; } public IDatabase GetRedisClient(int dbnum = -1, string name = "Default") { try { var cm = ConnectionMultiplexers.GetOrAdd(name, x => ConnectionMultiplexer.Connect(_optionsMonitor.Get(name).RedisConnectionString)); return cm.GetDatabase(dbnum); } catch (OptionsValidationException e) { _logger?.LogWarning(e, e.Message); return null; } } //public (IDatabase db , IServer server ) GetRedisDbCmClient(int dbnum = -1, string name = "Default") //{ // try // { // var cm = ConnectionMultiplexers.GetOrAdd(name, x => ConnectionMultiplexer.Connect(_optionsMonitor.Get(name).RedisConnectionString)); // return (cm.GetDatabase(dbnum),cm.GetServer(cm.GetEndPoints()[0])); // } // catch (OptionsValidationException e) // { // _logger?.LogWarning(e, e.Message); // return (null,null); // } //} } }