IOSSServiceManager.cs 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. using OnceMi.AspNetCore.OSS;
  2. namespace Admin.NET.Core.Service;
  3. /// <summary>
  4. /// OSS服务管理器接口
  5. /// </summary>
  6. public interface IOSSServiceManager : IDisposable
  7. {
  8. /// <summary>
  9. /// 获取OSS服务实例
  10. /// </summary>
  11. /// <param name="provider">存储提供者配置</param>
  12. /// <returns></returns>
  13. Task<IOSSService> GetOSSServiceAsync(SysFileProvider provider);
  14. /// <summary>
  15. /// 清除缓存
  16. /// </summary>
  17. void ClearCache();
  18. }
  19. /// <summary>
  20. /// OSS服务管理器实现
  21. /// </summary>
  22. public class OSSServiceManager : IOSSServiceManager, ITransient
  23. {
  24. private readonly IServiceProvider _serviceProvider;
  25. private readonly ConcurrentDictionary<string, IOSSService> _ossServiceCache;
  26. private readonly object _lockObject = new object();
  27. private bool _disposed = false;
  28. public OSSServiceManager(IServiceProvider serviceProvider)
  29. {
  30. _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));
  31. _ossServiceCache = new ConcurrentDictionary<string, IOSSService>();
  32. }
  33. /// <summary>
  34. /// 获取OSS服务实例(带缓存)
  35. /// </summary>
  36. /// <param name="provider">存储提供者配置</param>
  37. /// <returns></returns>
  38. public async Task<IOSSService> GetOSSServiceAsync(SysFileProvider provider)
  39. {
  40. if (provider == null)
  41. throw new ArgumentNullException(nameof(provider));
  42. var cacheKey = provider.ConfigKey;
  43. // 尝试从缓存获取
  44. if (_ossServiceCache.TryGetValue(cacheKey, out var cachedService))
  45. {
  46. return cachedService;
  47. }
  48. // 验证配置
  49. if (!await ValidateConfigurationAsync(provider))
  50. {
  51. throw new InvalidOperationException($"OSS提供者配置无效: {provider.DisplayName}");
  52. }
  53. // 线程安全地创建新服务
  54. lock (_lockObject)
  55. {
  56. // 双重检查锁定模式
  57. if (_ossServiceCache.TryGetValue(cacheKey, out cachedService))
  58. {
  59. return cachedService;
  60. }
  61. // 转换配置并创建服务
  62. var ossOptions = ConvertToOSSOptions(provider);
  63. var ossService = CreateOSSService(ossOptions);
  64. // 添加到缓存
  65. _ossServiceCache.TryAdd(cacheKey, ossService);
  66. return ossService;
  67. }
  68. }
  69. /// <summary>
  70. /// 创建OSS服务实例
  71. /// </summary>
  72. /// <param name="options">OSS配置选项</param>
  73. /// <returns></returns>
  74. private IOSSService CreateOSSService(OSSOptions options)
  75. {
  76. ArgumentNullException.ThrowIfNull(options);
  77. try
  78. {
  79. // 使用现有的IOSSServiceFactory,但需要先注册配置
  80. var providerName = Enum.GetName(options.Provider);
  81. var configSectionName = $"TempOSS_{Guid.NewGuid():N}";
  82. // 创建临时配置
  83. var configData = new Dictionary<string, string>
  84. {
  85. [$"{configSectionName}:Provider"] = providerName,
  86. [$"{configSectionName}:Endpoint"] = options.Endpoint ?? "",
  87. [$"{configSectionName}:AccessKey"] = options.AccessKey ?? "",
  88. [$"{configSectionName}:SecretKey"] = options.SecretKey ?? "",
  89. [$"{configSectionName}:Region"] = options.Region ?? "",
  90. [$"{configSectionName}:IsEnableHttps"] = options.IsEnableHttps.ToString(),
  91. [$"{configSectionName}:IsEnableCache"] = options.IsEnableCache.ToString()
  92. };
  93. var tempConfig = new ConfigurationBuilder()
  94. .AddInMemoryCollection(configData)
  95. .Build();
  96. // 创建临时服务集合,但不立即释放
  97. var services = new ServiceCollection();
  98. services.AddSingleton<IConfiguration>(tempConfig);
  99. services.AddLogging();
  100. services.AddOSSService(providerName, configSectionName);
  101. // 构建服务提供者并创建OSS服务
  102. var tempServiceProvider = services.BuildServiceProvider();
  103. var ossServiceFactory = tempServiceProvider.GetRequiredService<IOSSServiceFactory>();
  104. var ossService = ossServiceFactory.Create(providerName);
  105. // 注意:不要释放tempServiceProvider,因为ossService可能依赖它
  106. // 这里我们接受这个内存开销,因为缓存会减少创建频率
  107. return ossService;
  108. }
  109. catch (Exception ex)
  110. {
  111. throw Oops.Oh($"创建OSS服务失败: {ex.Message}");
  112. }
  113. }
  114. /// <summary>
  115. /// 验证配置
  116. /// </summary>
  117. /// <param name="provider">存储提供者配置</param>
  118. /// <returns></returns>
  119. private Task<bool> ValidateConfigurationAsync(SysFileProvider provider)
  120. {
  121. if (provider == null) return Task.FromResult(false);
  122. // 基本字段验证
  123. var isValid = !string.IsNullOrWhiteSpace(provider.Provider) &&
  124. !string.IsNullOrWhiteSpace(provider.BucketName) &&
  125. !string.IsNullOrWhiteSpace(provider.AccessKey) &&
  126. !string.IsNullOrWhiteSpace(provider.SecretKey);
  127. // Minio额外需要Endpoint
  128. if (provider.Provider.ToUpper() == "MINIO")
  129. {
  130. isValid = isValid && !string.IsNullOrWhiteSpace(provider.Endpoint);
  131. }
  132. return Task.FromResult(isValid);
  133. }
  134. /// <summary>
  135. /// 将SysFileProvider转换为OSSOptions
  136. /// </summary>
  137. /// <param name="provider"></param>
  138. /// <returns></returns>
  139. private OSSOptions ConvertToOSSOptions(SysFileProvider provider)
  140. {
  141. if (provider == null)
  142. throw new ArgumentNullException(nameof(provider));
  143. var ossOptions = new OSSOptions
  144. {
  145. Provider = Enum.Parse<OSSProvider>(provider.Provider),
  146. Endpoint = provider.Endpoint,
  147. Region = provider.Region,
  148. IsEnableHttps = provider.IsEnableHttps ?? true,
  149. IsEnableCache = provider.IsEnableCache ?? true
  150. };
  151. // 设置认证信息(所有提供者现在都使用统一的字段)
  152. ossOptions.AccessKey = provider.AccessKey;
  153. ossOptions.SecretKey = provider.SecretKey;
  154. return ossOptions;
  155. }
  156. /// <summary>
  157. /// 清除缓存
  158. /// </summary>
  159. public void ClearCache()
  160. {
  161. lock (_lockObject)
  162. {
  163. _ossServiceCache.Clear();
  164. }
  165. }
  166. /// <summary>
  167. /// 释放资源
  168. /// </summary>
  169. public void Dispose()
  170. {
  171. if (!_disposed)
  172. {
  173. lock (_lockObject)
  174. {
  175. _ossServiceCache.Clear();
  176. }
  177. _disposed = true;
  178. }
  179. }
  180. }