AzureCosmosFactory.cs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using Azure;
  2. using Azure.Cosmos;
  3. using Microsoft.Extensions.Configuration;
  4. using Microsoft.Extensions.Logging;
  5. using Microsoft.Extensions.Options;
  6. using System;
  7. using System.Collections.Concurrent;
  8. using System.Collections.Generic;
  9. using System.Linq;
  10. using System.Threading.Tasks;
  11. using TEAMModelOS.Models;
  12. using TEAMModelOS.SDK.Context.Attributes.Azure;
  13. using TEAMModelOS.SDK.Context.Configuration;
  14. using TEAMModelOS.SDK.DI.AzureCosmos.Inner;
  15. using TEAMModelOS.SDK.Helper.Common.ReflectorExtensions;
  16. using System.Diagnostics;
  17. using System.IO;
  18. using System.Linq.Expressions;
  19. using System.Net;
  20. using System.Reflection;
  21. using System.Text;
  22. using System.Text.Json;
  23. using System.Threading;
  24. using TEAMModelOS.SDK.Context.Exception;
  25. using TEAMModelOS.SDK.DI;
  26. using Azure.Cosmos.Serialization;
  27. namespace TEAMModelOS.SDK.DI
  28. {
  29. public class AzureCosmosFactory
  30. {
  31. private readonly IServiceProvider _services;
  32. private readonly IOptionsMonitor<AzureCosmosFactoryOptions> _optionsMonitor;
  33. private readonly ILogger _logger;
  34. //private Option _option;
  35. private ConcurrentDictionary<string, CosmosClient> CosmosClients { get; } = new ConcurrentDictionary<string, CosmosClient>();
  36. // private CosmosDatabase database { get; set; }
  37. public AzureCosmosFactory(IServiceProvider services, IOptionsMonitor<AzureCosmosFactoryOptions> optionsMonitor, ILogger<AzureCosmosFactory> logger)
  38. {
  39. if (services == null) throw new ArgumentNullException(nameof(services));
  40. if (optionsMonitor == null) throw new ArgumentNullException(nameof(optionsMonitor));
  41. _services = services;
  42. _optionsMonitor = optionsMonitor;
  43. _logger = logger;
  44. }
  45. /// <summary>
  46. /// 取得CosmosClient,支持安全執行緒
  47. /// </summary>
  48. /// <param name="name"></param>
  49. /// <param name="region">可以使用Regions.{區域}設置,指定此屬性後,SDK會首選該區域來執行操作。此外,SDK會自動選擇後備的地理複製區域以實現高可用性。如果未指定此屬性,則SDK會將寫區域用作所有操作的首選區域</param>
  50. /// <returns></returns>
  51. public CosmosClient GetCosmosClient(string region = null, string name = "Default")
  52. {
  53. try
  54. {
  55. var cm = CosmosClients.GetOrAdd(name, x => new CosmosClient(_optionsMonitor.Get(name).CosmosConnectionString, new CosmosClientOptions() { ApplicationRegion = region, SerializerOptions = new CosmosSerializationOptions() { PropertyNamingPolicy = CosmosPropertyNamingPolicy.CamelCase } }));
  56. return cm;
  57. }
  58. catch (Exception e)
  59. {
  60. _logger?.LogWarning(e, e.Message);
  61. return null;
  62. }
  63. }
  64. }
  65. }