ElasticSearchClientFactory.cs 3.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
  2. //
  3. // 本项目主要遵循 MIT 许可证和 Apache 许可证(版本 2.0)进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
  4. //
  5. // 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动!任何基于本项目二次开发而产生的一切法律纠纷和责任,我们不承担任何责任!
  6. using Elastic.Clients.Elasticsearch;
  7. using Elastic.Transport;
  8. namespace Admin.NET.Core;
  9. public class ElasticSearchClientFactory
  10. {
  11. /// <summary>
  12. /// 创建 ES 客户端(通用方法)
  13. /// </summary>
  14. /// <typeparam name="TOptions">配置类型(支持通用或场景专用)</typeparam>
  15. /// <param name="configPath">配置文件路径(如 "ElasticSearch:Logging")</param>
  16. /// <returns>ES 客户端实例(或 null if 未启用)</returns>
  17. public static ElasticsearchClient? CreateClient<TOptions>(string configPath) where TOptions : ElasticSearchOptions, new()
  18. {
  19. // 从配置文件读取当前场景的配置
  20. var options = App.GetConfig<TOptions>(configPath);
  21. if (options == null)
  22. throw Oops.Oh($"未找到{configPath}配置项");
  23. if (!options.Enabled)
  24. return null;
  25. // 验证服务地址
  26. if (options.ServerUris == null || !options.ServerUris.Any())
  27. throw new ArgumentException($"ES 配置 {configPath} 未设置 ServerUris");
  28. // 构建连接池(支持集群)
  29. var uris = options.ServerUris.Select(uri => new Uri(uri)).ToList();
  30. var connectionPool = new StaticNodePool(uris);
  31. var connectionSettings = new ElasticsearchClientSettings(connectionPool)
  32. .DefaultIndex(options.DefaultIndex) // 设置默认索引
  33. .DisableDirectStreaming() // 开启请求/响应日志,方便排查问题
  34. .OnRequestCompleted(response =>
  35. {
  36. if (response.HttpStatusCode == 401)
  37. {
  38. Console.WriteLine("ES 请求被拒绝:未提供有效认证信息");
  39. }
  40. });
  41. // 配置认证
  42. ConfigureAuthentication(connectionSettings, options);
  43. // 配置 HTTPS 证书指纹
  44. if (!string.IsNullOrEmpty(options.Fingerprint))
  45. connectionSettings.CertificateFingerprint(options.Fingerprint);
  46. return new ElasticsearchClient(connectionSettings);
  47. }
  48. /// <summary>
  49. /// 配置认证(通用逻辑)
  50. /// </summary>
  51. private static void ConfigureAuthentication(ElasticsearchClientSettings settings, ElasticSearchOptions options)
  52. {
  53. switch (options.AuthType)
  54. {
  55. case ElasticSearchAuthTypeEnum.Basic:
  56. settings.Authentication(new BasicAuthentication(options.User, options.Password));
  57. break;
  58. case ElasticSearchAuthTypeEnum.ApiKey:
  59. settings.Authentication(new ApiKey(options.ApiKey));
  60. break;
  61. case ElasticSearchAuthTypeEnum.Base64ApiKey:
  62. settings.Authentication(new Base64ApiKey(options.Base64ApiKey));
  63. break;
  64. case ElasticSearchAuthTypeEnum.None:
  65. // 无需认证
  66. break;
  67. default:
  68. throw new ArgumentOutOfRangeException(nameof(options.AuthType));
  69. }
  70. }
  71. }