RedisCfgSource.cs 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. using Apq.Cfg.Sources;
  2. using Microsoft.Extensions.Configuration;
  3. using Microsoft.Extensions.Configuration.Memory;
  4. using StackExchange.Redis;
  5. namespace Apq.Cfg.Redis;
  6. /// <summary>
  7. /// Redis 配置源
  8. /// </summary>
  9. internal sealed class RedisCfgSource : IWritableCfgSource, IDisposable
  10. {
  11. private const int MinScanPageSize = 10;
  12. private const int MaxScanPageSize = 1000;
  13. private readonly ConnectionMultiplexer _multiplexer;
  14. private readonly RedisOptions _options;
  15. private volatile bool _disposed;
  16. public RedisCfgSource(RedisOptions options, int level, bool isPrimaryWriter)
  17. {
  18. _options = options;
  19. Level = level;
  20. IsPrimaryWriter = isPrimaryWriter;
  21. var conn = EnsureAllowAdmin(options.ConnectionString!);
  22. if (_options.ConnectTimeoutMs > 0) conn += $",connectTimeout={_options.ConnectTimeoutMs}";
  23. if (_options.OperationTimeoutMs > 0) conn += $",syncTimeout={_options.OperationTimeoutMs}";
  24. conn += ",abortConnect=false";
  25. _multiplexer = ConnectionMultiplexer.Connect(conn);
  26. }
  27. public int Level { get; }
  28. public bool IsWriteable => true;
  29. public bool IsPrimaryWriter { get; }
  30. public void Dispose()
  31. {
  32. if (_disposed) return;
  33. _disposed = true;
  34. try { _multiplexer?.Dispose(); }
  35. catch { }
  36. }
  37. public IConfigurationSource BuildSource()
  38. {
  39. ThrowIfDisposed();
  40. var data = new List<KeyValuePair<string, string?>>();
  41. if (string.IsNullOrWhiteSpace(_options.ConnectionString))
  42. return new MemoryConfigurationSource { InitialData = data };
  43. try
  44. {
  45. var db = _multiplexer.GetDatabase(_options.Database ?? -1);
  46. var endpoints = _multiplexer.GetEndPoints();
  47. var server = endpoints.Length > 0 ? _multiplexer.GetServer(endpoints[0]) : null;
  48. if (server != null)
  49. {
  50. var pattern = string.IsNullOrEmpty(_options.KeyPrefix) ? "*" : _options.KeyPrefix + "*";
  51. var pageSize = Math.Clamp(_options.ScanPageSize, MinScanPageSize, MaxScanPageSize);
  52. var prefixLen = _options.KeyPrefix?.Length ?? 0;
  53. foreach (var key in server.Keys(db.Database, pattern, pageSize))
  54. {
  55. var val = db.StringGet(key);
  56. var keyStr = key.ToString();
  57. if (!string.IsNullOrEmpty(keyStr))
  58. {
  59. // 去掉前缀,还原为原始配置 key
  60. var configKey = prefixLen > 0 ? keyStr.Substring(prefixLen) : keyStr;
  61. data.Add(new KeyValuePair<string, string?>(configKey, val.HasValue ? val.ToString() : null));
  62. }
  63. }
  64. }
  65. }
  66. catch { }
  67. return new MemoryConfigurationSource { InitialData = data };
  68. }
  69. public async Task ApplyChangesAsync(IReadOnlyDictionary<string, string?> changes, CancellationToken cancellationToken)
  70. {
  71. ThrowIfDisposed();
  72. if (string.IsNullOrWhiteSpace(_options.ConnectionString)) return;
  73. var db = _multiplexer.GetDatabase(_options.Database ?? -1);
  74. var batch = db.CreateBatch();
  75. var tasks = new List<Task>();
  76. foreach (var (key, value) in changes)
  77. {
  78. var k = string.IsNullOrEmpty(_options.KeyPrefix) ? key : _options.KeyPrefix + key;
  79. tasks.Add(value is null ? batch.KeyDeleteAsync(k) : batch.StringSetAsync(k, value));
  80. }
  81. batch.Execute();
  82. await Task.WhenAll(tasks).ConfigureAwait(false);
  83. if (!string.IsNullOrWhiteSpace(_options.Channel))
  84. {
  85. try
  86. {
  87. var sub = _multiplexer.GetSubscriber();
  88. await sub.PublishAsync(RedisChannel.Literal(_options.Channel!), "update").ConfigureAwait(false);
  89. }
  90. catch { }
  91. }
  92. }
  93. private void ThrowIfDisposed()
  94. {
  95. if (_disposed) throw new ObjectDisposedException(nameof(RedisCfgSource));
  96. }
  97. private static string EnsureAllowAdmin(string connectionString)
  98. {
  99. return connectionString.Contains("allowAdmin", StringComparison.OrdinalIgnoreCase)
  100. ? connectionString
  101. : connectionString + ",allowAdmin=true";
  102. }
  103. }