AzureCosmosFactory.cs 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. using Azure.Core.Serialization;
  2. using Microsoft.Azure.Cosmos;
  3. using Microsoft.Extensions.Logging;
  4. using Microsoft.Extensions.Options;
  5. using System;
  6. using System.Collections.Concurrent;
  7. using System.Text.Json;
  8. using System.Text.Json.Serialization;
  9. using System.IO;
  10. namespace TEAMModelOS.SDK.DI
  11. {
  12. public class AzureCosmosFactory
  13. {
  14. private readonly IServiceProvider _services;
  15. private readonly IOptionsMonitor<AzureCosmosFactoryOptions> _optionsMonitor;
  16. private readonly ILogger _logger;
  17. //private Option _option;
  18. private ConcurrentDictionary<string, CosmosClient> CosmosClients { get; } = new ConcurrentDictionary<string, CosmosClient>();
  19. // private CosmosDatabase database { get; set; }
  20. public AzureCosmosFactory(IServiceProvider services, IOptionsMonitor<AzureCosmosFactoryOptions> optionsMonitor, ILogger<AzureCosmosFactory> logger)
  21. {
  22. if (services == null) throw new ArgumentNullException(nameof(services));
  23. if (optionsMonitor == null) throw new ArgumentNullException(nameof(optionsMonitor));
  24. _services = services;
  25. _optionsMonitor = optionsMonitor;
  26. _logger = logger;
  27. }
  28. /// <summary>
  29. /// 取得CosmosClient,支持安全執行緒
  30. /// </summary>
  31. /// <param name="name"></param>
  32. /// <param name="region">可以使用Regions.{區域}設置,指定此屬性後,SDK會首選該區域來執行操作。此外,SDK會自動選擇後備的地理複製區域以實現高可用性。如果未指定此屬性,則SDK會將寫區域用作所有操作的首選區域</param>
  33. /// <returns></returns>
  34. public CosmosClient GetCosmosClient(string? region = null, string name = "Default")
  35. {
  36. try
  37. {
  38. //CosmosClientOptions 的 SerializerOptions = new CosmosSerializationOptions() { PropertyNamingPolicy = CosmosPropertyNamingPolicy.CamelCase }
  39. //需等待官方修正
  40. JsonSerializerOptions jsonSerializerOptions = new JsonSerializerOptions()
  41. {
  42. DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
  43. };
  44. var cm = CosmosClients.GetOrAdd(name, x => new CosmosClient(_optionsMonitor.Get(name).CosmosConnectionString, new CosmosClientOptions()
  45. {
  46. // Serializer= new CosmosSystemTextJsonSerializer(jsonSerializerOptions),
  47. ApplicationRegion = region
  48. }));
  49. return cm;
  50. }
  51. catch (Exception e)
  52. {
  53. _logger?.LogWarning(e, e.Message);
  54. throw;
  55. }
  56. }
  57. }
  58. /// <summary>
  59. /// Uses <see cref="Azure.Core.Serialization.JsonObjectSerializer"/> which leverages System.Text.Json providing a simple API to interact with on the Azure SDKs.
  60. /// </summary>
  61. // <SystemTextJsonSerializer>
  62. public class CosmosSystemTextJsonSerializer : CosmosSerializer
  63. {
  64. private readonly JsonObjectSerializer systemTextJsonSerializer;
  65. public CosmosSystemTextJsonSerializer(JsonSerializerOptions jsonSerializerOptions)
  66. {
  67. this.systemTextJsonSerializer = new JsonObjectSerializer(jsonSerializerOptions);
  68. }
  69. public override T FromStream<T>(Stream stream)
  70. {
  71. using (stream)
  72. {
  73. if (stream.CanSeek
  74. && stream.Length == 0)
  75. {
  76. return default;
  77. }
  78. if (typeof(Stream).IsAssignableFrom(typeof(T)))
  79. {
  80. return (T)(object)stream;
  81. }
  82. return (T)this.systemTextJsonSerializer.Deserialize(stream, typeof(T), default);
  83. }
  84. }
  85. public override Stream ToStream<T>(T input)
  86. {
  87. if (input!= null)
  88. {
  89. MemoryStream streamPayload = new MemoryStream();
  90. this.systemTextJsonSerializer.Serialize(streamPayload, input, input.GetType(), default);
  91. streamPayload.Position = 0;
  92. return streamPayload;
  93. }
  94. else {
  95. return new MemoryStream();
  96. }
  97. }
  98. }
  99. // </SystemTextJsonSerializer>
  100. }