Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

207 lines
7.5KB

  1. using HealthMonitor.Common;
  2. using HealthMonitor.Core.Dal;
  3. using HealthMonitor.Model.Config;
  4. using HealthMonitor.Service.Biz.db;
  5. using HealthMonitor.Service.Cache;
  6. using HealthMonitor.Service.Resolver.Factory;
  7. using HealthMonitor.Service.Resolver.Interface;
  8. using HealthMonitor.Service.Sub.Topic.Model;
  9. using Microsoft.Extensions.Logging;
  10. using Microsoft.Extensions.Options;
  11. using Newtonsoft.Json;
  12. using System;
  13. using System.Collections.Concurrent;
  14. using System.Collections.Generic;
  15. using System.Linq;
  16. using System.Reflection;
  17. using System.Text;
  18. using System.Threading.Tasks;
  19. using TDengineDriver;
  20. using TDengineTMQ;
  21. using TelpoDataService.Util.Entities.GpsLocationHistory;
  22. namespace HealthMonitor.Service.Sub
  23. {
  24. public class TDengineDataSubcribe
  25. {
  26. private readonly ILogger<TDengineDataSubcribe> _logger;
  27. private readonly MsgQueueManager _msgQueueManager;
  28. private readonly TDengineService _serviceTDengine;
  29. private readonly PersonCacheManager _personCacheMgr;
  30. private readonly TDengineServiceConfig _configTDengineService;
  31. private readonly BloodPressReferenceValueCacheManager _bpRefValCacheManager;
  32. private readonly IResolverFactory _resolverFactory;
  33. private CancellationTokenSource? _tokenSource = null;
  34. //private int cnt = 0;
  35. public TDengineDataSubcribe(
  36. TDengineService serviceDengine,
  37. PersonCacheManager personCacheMgr,
  38. BloodPressReferenceValueCacheManager bpRefValCacheManager,
  39. IResolverFactory resolverFactory,
  40. IOptions<TDengineServiceConfig> configTDengineService,
  41. MsgQueueManager msgQueueManager,
  42. ILogger<TDengineDataSubcribe> logger
  43. )
  44. {
  45. _serviceTDengine = serviceDengine;
  46. _personCacheMgr = personCacheMgr;
  47. _bpRefValCacheManager = bpRefValCacheManager;
  48. _logger = logger;
  49. _resolverFactory = resolverFactory;
  50. _msgQueueManager = msgQueueManager;
  51. _configTDengineService = configTDengineService.Value;
  52. }
  53. public void BeginListen(CancellationToken stoppingToken)
  54. {
  55. //var cfg = new ConsumerConfig
  56. //{
  57. // GourpId = "group_1",
  58. // TDConnectUser = "root",
  59. // TDConnectPasswd = "taosdata",
  60. // MsgWithTableName = "true",
  61. // TDConnectIp = "47.116.142.20",
  62. //};
  63. //var conn = GetConnection();
  64. //ProcessMsg(consumer);
  65. //防止造成多线程运行
  66. _tokenSource?.Cancel();
  67. _tokenSource = CancellationTokenSource.CreateLinkedTokenSource(stoppingToken);
  68. DoTDengineConnect();
  69. }
  70. public void DoTDengineConnect()
  71. {
  72. string host = _configTDengineService.Host;
  73. short port = 6030;
  74. string username = _configTDengineService.UserName;
  75. string password = _configTDengineService.Password;
  76. string dbname = _configTDengineService.DB;
  77. //#if DEBUG
  78. // //string configDir = "C:/TDengine/cfg";
  79. // //TDengine.Options((int)TDengineInitOption.TSDB_OPTION_CONFIGDIR, configDir);
  80. // TDengine.Options((int)TDengineInitOption.TSDB_OPTION_TIMEZONE, "Asia/Beijing");
  81. //#endif
  82. var conn = TDengine.Connect(host, username, password, dbname, port);
  83. if (conn == IntPtr.Zero)
  84. {
  85. _logger.LogError("reason:{TDengine.Error(conn)}", TDengine.Error(conn));
  86. }
  87. else
  88. {
  89. _logger.LogInformation($"连接 TDengine 成功....");
  90. }
  91. DoReceive(conn);
  92. }
  93. public void DoReceive(IntPtr Connection)
  94. {
  95. var cfg = new ConsumerConfig
  96. {
  97. GourpId = "group_1",
  98. TDConnectUser = _configTDengineService.UserName,
  99. TDConnectPasswd = _configTDengineService.Password,
  100. MsgWithTableName = "true",
  101. TDConnectIp = _configTDengineService.Host,
  102. };
  103. // string topic = "topic_hm_bp_stats";
  104. string topic = nameof(TopicHmBloodPress).ToLower();
  105. TopicHmBloodPress fields = new();
  106. PropertyInfo[] props = fields.GetType().GetProperties();
  107. // 获取 fields
  108. string attributes = "";
  109. foreach (PropertyInfo prop in props)
  110. {
  111. JsonPropertyAttribute attr = prop.GetCustomAttribute<JsonPropertyAttribute>()!;
  112. if (attr != null)
  113. {
  114. attributes += attr.PropertyName + ",";
  115. }
  116. }
  117. attributes = attributes.TrimEnd(',');
  118. //create topic
  119. IntPtr res = TDengine.Query(Connection, $"create topic if not exists {topic} as select {attributes} from health_monitor.stb_hm_bloodpress");
  120. if (TDengine.ErrorNo(res) != 0)
  121. {
  122. throw new Exception($"create topic failed, reason:{TDengine.Error(res)}");
  123. }
  124. // create consumer
  125. var consumer = new ConsumerBuilder(cfg)
  126. .Build();
  127. // subscribe
  128. consumer.Subscribe(topic);
  129. while (!_tokenSource!.IsCancellationRequested)
  130. {
  131. var consumeRes = consumer.Consume(300);
  132. foreach (KeyValuePair<TopicPartition, TaosResult> kv in consumeRes.Message)
  133. {
  134. for (int i = 0; i < kv.Value.Datas.Count; i++)
  135. {
  136. if (((i + 1) % kv.Value.Metas.Count == 0))
  137. {
  138. try
  139. {
  140. IDictionary<string, object> row = new Dictionary<string, object>();
  141. foreach (var meta in kv.Value.Metas)
  142. {
  143. int index = i - (kv.Value.Metas.Count - kv.Value.Metas.IndexOf(meta) - 1);
  144. //var value = kv.Value.Datas[index];
  145. row.Add(meta.name, kv.Value.Datas[index]);
  146. }
  147. var db = kv.Key.db;
  148. var table = kv.Key.table;
  149. var kvTopic = kv.Key.topic;
  150. var body = JsonConvert.SerializeObject(row);
  151. ReceiveMessageModel msg = new(db, table, kvTopic, row["message_id"].ToString()!, body);
  152. ParsePackage(msg);
  153. }
  154. catch (Exception ex)
  155. {
  156. _logger.LogError("解析包发生异常:{ex.Message}, {ex.StackTrace}", ex.Message, ex.StackTrace);
  157. }
  158. }
  159. }
  160. }
  161. consumer.Commit(consumeRes);
  162. _logger.LogInformation("监听中....");
  163. }
  164. // close consumer after use.Otherwise will lead memory leak.
  165. consumer.Close();
  166. TDengine.Close(Connection);
  167. }
  168. public void ParsePackage(ReceiveMessageModel model)
  169. {
  170. var msg = _resolverFactory.ParseAndWrap(model);
  171. if (msg == null) return;
  172. _msgQueueManager.Enqueue(msg);
  173. }
  174. }
  175. }