AzureRedisFactory.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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 ConnectionMultiplexer GetConnectionMultiplexer( string name = "Default")
  43. {
  44. try
  45. {
  46. var cm = ConnectionMultiplexers.GetOrAdd(name, x => ConnectionMultiplexer.Connect(_optionsMonitor.Get(name).RedisConnectionString));
  47. return cm;
  48. }
  49. catch (OptionsValidationException e)
  50. {
  51. _logger?.LogWarning(e, e.Message);
  52. return null;
  53. }
  54. }
  55. //public (IDatabase db , IServer server ) GetRedisDbCmClient(int dbnum = -1, string name = "Default")
  56. //{
  57. // try
  58. // {
  59. // var cm = ConnectionMultiplexers.GetOrAdd(name, x => ConnectionMultiplexer.Connect(_optionsMonitor.Get(name).RedisConnectionString));
  60. // return (cm.GetDatabase(dbnum),cm.GetServer(cm.GetEndPoints()[0]));
  61. // }
  62. // catch (OptionsValidationException e)
  63. // {
  64. // _logger?.LogWarning(e, e.Message);
  65. // return (null,null);
  66. // }
  67. //}
  68. }
  69. }