AzureRedisFactory.cs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using Microsoft.Extensions.DependencyInjection.Extensions;
  2. using Microsoft.Extensions.Options;
  3. using StackExchange.Redis;
  4. using System.Collections.Concurrent;
  5. namespace HTEX.Complex.Service.AzureRedis
  6. {
  7. public class AzureRedisFactoryOptions
  8. {
  9. public string Name { get; set; }
  10. public string RedisConnectionString { get; set; }
  11. }
  12. public static class AzureRedisFactoryExtensions
  13. {
  14. public static IServiceCollection AddAzureRedis(this IServiceCollection services, string connectionString, string name = "Default")
  15. {
  16. if (services == null) throw new ArgumentNullException(nameof(services));
  17. if (connectionString == null) throw new ArgumentNullException(nameof(connectionString));
  18. services.TryAddSingleton<AzureRedisFactory>();
  19. services.Configure<AzureRedisFactoryOptions>(name, o => { o.Name = name; o.RedisConnectionString = connectionString; });
  20. return services;
  21. }
  22. }
  23. public class AzureRedisFactory
  24. {
  25. private readonly IServiceProvider _services;
  26. private readonly IOptionsMonitor<AzureRedisFactoryOptions> _optionsMonitor;
  27. private readonly ILogger _logger;
  28. private ConcurrentDictionary<string, ConnectionMultiplexer> ConnectionMultiplexers { get; } = new ConcurrentDictionary<string, ConnectionMultiplexer>();
  29. public AzureRedisFactory(IServiceProvider services, IOptionsMonitor<AzureRedisFactoryOptions> optionsMonitor, ILogger<AzureRedisFactory> logger)
  30. {
  31. if (services == null) throw new ArgumentNullException(nameof(services));
  32. if (optionsMonitor == null) throw new ArgumentNullException(nameof(optionsMonitor));
  33. _services = services;
  34. _optionsMonitor = optionsMonitor;
  35. _logger = logger;
  36. }
  37. public IDatabase GetRedisClient(int dbnum = -1, string name = "Default")
  38. {
  39. try
  40. {
  41. var cm = ConnectionMultiplexers.GetOrAdd(name, x => ConnectionMultiplexer.Connect(_optionsMonitor.Get(name).RedisConnectionString));
  42. return cm.GetDatabase(dbnum);
  43. }
  44. catch (OptionsValidationException e)
  45. {
  46. _logger?.LogWarning(e, e.Message);
  47. return null;
  48. }
  49. }
  50. //public (IDatabase db , IServer server ) GetRedisDbCmClient(int dbnum = -1, string name = "Default")
  51. //{
  52. // try
  53. // {
  54. // var cm = ConnectionMultiplexers.GetOrAdd(name, x => ConnectionMultiplexer.Connect(_optionsMonitor.Get(name).RedisConnectionString));
  55. // return (cm.GetDatabase(dbnum),cm.GetServer(cm.GetEndPoints()[0]));
  56. // }
  57. // catch (OptionsValidationException e)
  58. // {
  59. // _logger?.LogWarning(e, e.Message);
  60. // return (null,null);
  61. // }
  62. //}
  63. }
  64. }