You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

209 lines
7.9KB

  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 serviceTDengine,
  37. PersonCacheManager personCacheMgr,
  38. BloodPressReferenceValueCacheManager bpRefValCacheManager,
  39. IResolverFactory resolverFactory,
  40. IOptions<TDengineServiceConfig> configTDengineService,
  41. MsgQueueManager msgQueueManager,
  42. ILogger<TDengineDataSubcribe> logger
  43. )
  44. {
  45. _serviceTDengine = serviceTDengine;
  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. var conn = _serviceTDengine.Connection();
  92. DoReceive(conn);
  93. }
  94. public void DoReceive(IntPtr Connection)
  95. {
  96. // string topic = "topic_hm_bp_stats";
  97. string topic = nameof(TopicHmBloodPress).ToLower();
  98. TopicHmBloodPress fields = new();
  99. PropertyInfo[] props = fields.GetType().GetProperties();
  100. // 获取 fields
  101. string attributes = "";
  102. foreach (PropertyInfo prop in props)
  103. {
  104. JsonPropertyAttribute attr = prop.GetCustomAttribute<JsonPropertyAttribute>()!;
  105. if (attr != null)
  106. {
  107. attributes += attr.PropertyName + ",";
  108. }
  109. }
  110. attributes = attributes.TrimEnd(',');
  111. //create topic
  112. IntPtr res = TDengine.Query(Connection, $"create topic if not exists {topic} as select {attributes} from health_monitor.stb_hm_bloodpress");
  113. if (TDengine.ErrorNo(res) != 0)
  114. {
  115. _logger.LogError($"create topic failed, reason:{TDengine.Error(res)}");
  116. throw new Exception($"create topic failed, reason:{TDengine.Error(res)}");
  117. }
  118. var cfg = new ConsumerConfig
  119. {
  120. GourpId = "group_1",
  121. TDConnectUser = _configTDengineService.UserName,
  122. TDConnectPasswd = _configTDengineService.Password,
  123. MsgWithTableName = "true",
  124. TDConnectIp = _configTDengineService.Host,
  125. };
  126. // create consumer
  127. var consumer = new ConsumerBuilder(cfg)
  128. .Build();
  129. // subscribe
  130. consumer.Subscribe(topic);
  131. while (!_tokenSource!.IsCancellationRequested)
  132. {
  133. var consumeRes = consumer.Consume(300);
  134. foreach (KeyValuePair<TopicPartition, TaosResult> kv in consumeRes.Message)
  135. {
  136. for (int i = 0; i < kv.Value.Datas.Count; i++)
  137. {
  138. if (((i + 1) % kv.Value.Metas.Count == 0))
  139. {
  140. try
  141. {
  142. IDictionary<string, object> row = new Dictionary<string, object>();
  143. foreach (var meta in kv.Value.Metas)
  144. {
  145. int index = i - (kv.Value.Metas.Count - kv.Value.Metas.IndexOf(meta) - 1);
  146. //var value = kv.Value.Datas[index];
  147. row.Add(meta.name, kv.Value.Datas[index]);
  148. }
  149. var db = kv.Key.db;
  150. var table = kv.Key.table;
  151. var kvTopic = kv.Key.topic;
  152. var body = JsonConvert.SerializeObject(row);
  153. ReceiveMessageModel msg = new(db, table, kvTopic, row["message_id"].ToString()!, body);
  154. ParsePackage(msg);
  155. }
  156. catch (Exception ex)
  157. {
  158. _logger.LogError("解析包发生异常:{ex.Message}, {ex.StackTrace}", ex.Message, ex.StackTrace);
  159. }
  160. }
  161. }
  162. }
  163. consumer.Commit(consumeRes);
  164. //_logger.LogInformation("监听中....");
  165. // Console.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff},监听中....");
  166. }
  167. // close consumer after use.Otherwise will lead memory leak.
  168. consumer.Close();
  169. TDengine.Close(Connection);
  170. }
  171. public void ParsePackage(ReceiveMessageModel model)
  172. {
  173. var msg = _resolverFactory.ParseAndWrap(model);
  174. if (msg == null) return;
  175. _msgQueueManager.Enqueue(msg);
  176. }
  177. }
  178. }