AzureRedisFactory.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. using Microsoft.Azure.Cosmos.Table;
  2. using Microsoft.Extensions.Options;
  3. using Microsoft.Extensions.Logging;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Text;
  7. using Microsoft.Extensions.DependencyInjection;
  8. using Azure.Storage.Blobs;
  9. using Azure.Storage.Blobs.Models;
  10. using Azure.Storage.Blobs.Specialized;
  11. using StackExchange.Redis;
  12. using System.Collections.Concurrent;
  13. namespace TEAMModelOS.SDK.DI
  14. {
  15. public class AzureRedisFactory
  16. {
  17. private readonly IServiceProvider _services;
  18. private readonly IOptionsMonitor<AzureRedisFactoryOptions> _optionsMonitor;
  19. private readonly ILogger _logger;
  20. private ConcurrentDictionary<string, ConnectionMultiplexer> ConnectionMultiplexers { get; } = new ConcurrentDictionary<string, ConnectionMultiplexer>();
  21. public AzureRedisFactory(IServiceProvider services, IOptionsMonitor<AzureRedisFactoryOptions> optionsMonitor, ILogger<AzureRedisFactory> logger)
  22. {
  23. if (services == null) throw new ArgumentNullException(nameof(services));
  24. if (optionsMonitor == null) throw new ArgumentNullException(nameof(optionsMonitor));
  25. _services = services;
  26. _optionsMonitor = optionsMonitor;
  27. _logger = logger;
  28. }
  29. public IDatabase GetRedisClient( int dbnum = -1,string name = "Default")
  30. {
  31. try
  32. {
  33. var cm = ConnectionMultiplexers.GetOrAdd(name, x => ConnectionMultiplexer.Connect(_optionsMonitor.Get(name).RedisConnectionString));
  34. return cm.GetDatabase(dbnum);
  35. }
  36. catch (OptionsValidationException e)
  37. {
  38. _logger?.LogWarning(e, e.Message);
  39. return null;
  40. }
  41. }
  42. //public (IDatabase db , IServer server ) GetRedisDbCmClient(int dbnum = -1, string name = "Default")
  43. //{
  44. // try
  45. // {
  46. // var cm = ConnectionMultiplexers.GetOrAdd(name, x => ConnectionMultiplexer.Connect(_optionsMonitor.Get(name).RedisConnectionString));
  47. // return (cm.GetDatabase(dbnum),cm.GetServer(cm.GetEndPoints()[0]));
  48. // }
  49. // catch (OptionsValidationException e)
  50. // {
  51. // _logger?.LogWarning(e, e.Message);
  52. // return (null,null);
  53. // }
  54. //}
  55. }
  56. }