12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970 |
- 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<AzureRedisFactory>();
- services.Configure<AzureRedisFactoryOptions>(name, o => { o.Name = name; o.RedisConnectionString = connectionString; });
- return services;
- }
- }
- public class AzureRedisFactory
- {
- private readonly IServiceProvider _services;
- private readonly IOptionsMonitor<AzureRedisFactoryOptions> _optionsMonitor;
- private readonly ILogger _logger;
- private ConcurrentDictionary<string, ConnectionMultiplexer> ConnectionMultiplexers { get; } = new ConcurrentDictionary<string, ConnectionMultiplexer>();
- public AzureRedisFactory(IServiceProvider services, IOptionsMonitor<AzureRedisFactoryOptions> optionsMonitor, ILogger<AzureRedisFactory> 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);
- // }
- //}
- }
- }
|