Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

232 lines
9.2KB

  1. using HealthMonitor.Common.helper;
  2. using HealthMonitor.Model.Config;
  3. using HealthMonitor.Service.Biz.db.Dto;
  4. using Microsoft.Extensions.Logging;
  5. using Microsoft.Extensions.Options;
  6. using Newtonsoft.Json;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Linq;
  10. using System.Text;
  11. using System.Threading.Tasks;
  12. using TDengineDriver;
  13. using TDengineDriver.Impl;
  14. namespace HealthMonitor.Service.Biz.db
  15. {
  16. public class TDengineService
  17. {
  18. private readonly ILogger<TDengineService> _logger;
  19. private readonly HttpHelper _httpHelper=default!;
  20. private readonly TDengineServiceConfig _configTDengineService;
  21. public TDengineService(ILogger<TDengineService> logger,
  22. IOptions<TDengineServiceConfig> configTDengineService,
  23. HttpHelper httpHelper
  24. )
  25. {
  26. _logger = logger;
  27. _configTDengineService = configTDengineService.Value;
  28. _httpHelper = httpHelper;
  29. }
  30. public IntPtr Connection()
  31. {
  32. string host = _configTDengineService.Host;
  33. string user = _configTDengineService.UserName;
  34. string db = _configTDengineService.DB;
  35. short port = _configTDengineService.Port;
  36. string password = _configTDengineService.Password;
  37. IntPtr conn = TDengine.Connect(host, user, password, db, port);
  38. //string host = "172.16.255.180";
  39. //short port = 6030;
  40. //string user = "root";
  41. //string password = "taosdata";
  42. //string db = "health_monitor";
  43. //IntPtr conn = TDengine.Connect(host, user, password, db, port);
  44. // Check if get connection success
  45. if (conn == IntPtr.Zero)
  46. {
  47. Console.WriteLine("Connect to TDengine failed");
  48. }
  49. else
  50. {
  51. Console.WriteLine("Connect to TDengine success");
  52. }
  53. return conn;
  54. }
  55. public void ExecuteSQL(IntPtr conn, string sql)
  56. {
  57. IntPtr res = TDengine.Query(conn, sql);
  58. // Check if query success
  59. if ((res == IntPtr.Zero) || (TDengine.ErrorNo(res) != 0))
  60. {
  61. Console.Write(sql + " failure, ");
  62. // Get error message while Res is a not null pointer.
  63. if (res != IntPtr.Zero)
  64. {
  65. Console.Write("reason:" + TDengine.Error(res));
  66. }
  67. }
  68. else
  69. {
  70. Console.Write(sql + " success, {0} rows affected", TDengine.AffectRows(res));
  71. //... do something with res ...
  72. // Important: need to free result to avoid memory leak.
  73. TDengine.FreeResult(res);
  74. }
  75. }
  76. public void ExecuteQuerySQL(IntPtr conn, string sql)
  77. {
  78. IntPtr res = TDengine.Query(conn, sql);
  79. // Check if query success
  80. if ((res == IntPtr.Zero) || (TDengine.ErrorNo(res) != 0))
  81. {
  82. Console.Write(sql + " failure, ");
  83. // Get error message while Res is a not null pointer.
  84. if (res != IntPtr.Zero)
  85. {
  86. Console.Write("reason:" + TDengine.Error(res));
  87. }
  88. }
  89. else
  90. {
  91. Console.Write(sql + " success, {0} rows affected", TDengine.AffectRows(res));
  92. //... do something with res ...
  93. List<TDengineDriver.TDengineMeta> resMeta = LibTaos.GetMeta(res);
  94. List<Object> resData = LibTaos.GetData(res);
  95. foreach (var meta in resMeta)
  96. {
  97. Console.Write($"\t|{meta.name} {meta.TypeName()} ({meta.size})\t|");
  98. }
  99. for (int i = 0; i < resData.Count; i++)
  100. {
  101. Console.Write($"|{resData[i].ToString()} \t");
  102. //Console.WriteLine("{0},{1},{2}", i, resMeta.Count, (i) % resMeta.Count);
  103. if (((i + 1) % resMeta.Count == 0))
  104. {
  105. Console.WriteLine("");
  106. }
  107. }
  108. // Important: need to free result to avoid memory leak.
  109. TDengine.FreeResult(res);
  110. }
  111. }
  112. public void CheckRes(IntPtr conn, IntPtr res, String errorMsg)
  113. {
  114. if (TDengine.ErrorNo(res) != 0)
  115. {
  116. throw new Exception($"{errorMsg} since: {TDengine.Error(res)}");
  117. }
  118. }
  119. public void ExecuteInsertSQL(IntPtr conn, string sql)
  120. {
  121. try
  122. {
  123. //sql = "INSERT INTO d1001 USING meters TAGS('California.SanFrancisco', 2) VALUES ('2018-10-03 14:38:05.000', 10.30000, 219, 0.31000) ('2018-10-03 14:38:15.000', 12.60000, 218, 0.33000) ('2018-10-03 14:38:16.800', 12.30000, 221, 0.31000) " +
  124. // "d1002 USING power.meters TAGS('California.SanFrancisco', 3) VALUES('2018-10-03 14:38:16.650', 10.30000, 218, 0.25000) " +
  125. // "d1003 USING power.meters TAGS('California.LosAngeles', 2) VALUES('2018-10-03 14:38:05.500', 11.80000, 221, 0.28000)('2018-10-03 14:38:16.600', 13.40000, 223, 0.29000) " +
  126. // "d1004 USING power.meters TAGS('California.LosAngeles', 3) VALUES('2018-10-03 14:38:05.000', 10.80000, 223, 0.29000)('2018-10-03 14:38:06.500', 11.50000, 221, 0.35000)";
  127. IntPtr res = TDengine.Query(conn, sql);
  128. CheckRes(conn, res, "failed to insert data");
  129. int affectedRows = TDengine.AffectRows(res);
  130. Console.WriteLine("affectedRows " + affectedRows);
  131. TDengine.FreeResult(res);
  132. }
  133. finally
  134. {
  135. TDengine.Close(conn);
  136. }
  137. }
  138. public async Task<bool> GernalRestSql(string sql)
  139. {
  140. //"http://{server}:{port}/rest/sql/{db}"
  141. var url = $"http://{_configTDengineService.Host}:{_configTDengineService.RestPort}/rest/sql/{_configTDengineService.DB}";
  142. List<KeyValuePair<string, string>> headers = new()
  143. {
  144. new KeyValuePair<string, string>("Authorization", "Basic " + _configTDengineService.Token)
  145. };
  146. var result = await _httpHelper.HttpToPostAsync(url, sql, headers).ConfigureAwait(false);
  147. var res = JsonConvert.DeserializeObject<TDengineRestResBase>(result!);
  148. if (result != null)
  149. {
  150. if (res?.Code == 0)
  151. {
  152. _logger.LogInformation($"{nameof(GernalRestSql)},SQL 语句执行成功|{sql}");
  153. return true;
  154. }
  155. else
  156. {
  157. _logger.LogWarning($"{nameof(GernalRestSql)},SQL 语句执行失败||{sql}");
  158. return false;
  159. }
  160. }
  161. else
  162. {
  163. _logger.LogError($"{nameof(GernalRestSql)},TDengine 服务器IP:{_configTDengineService.Host} 错误,请联系运维人员");
  164. return false;
  165. }
  166. //return res.Code==0;
  167. }
  168. public async Task<string?> GernalRestSqlResText(string sql)
  169. {
  170. var url = $"http://{_configTDengineService.Host}:{_configTDengineService.RestPort}/rest/sql/{_configTDengineService.DB}";
  171. List<KeyValuePair<string, string>> headers = new()
  172. {
  173. new KeyValuePair<string, string>("Authorization", "Basic " + _configTDengineService.Token)
  174. };
  175. var result = await _httpHelper.HttpToPostAsync(url, sql, headers).ConfigureAwait(false);
  176. return result;
  177. }
  178. public async Task<Aggregate> GetAggregateValue(string field,string tbName,string? condition)
  179. {
  180. var sql = $"SELECT MAX({field}), MIN({field}) FROM {_configTDengineService.DB}.{tbName} WHERE {condition}";
  181. var result = await GernalRestSqlResText(sql);
  182. var res = JsonConvert.DeserializeObject<Aggregate>(result!);
  183. List<dynamic> data = res?.Data!;
  184. return new Aggregate
  185. {
  186. Max = data.Count.Equals(0) ? 0 : data[0][0],
  187. Min = data.Count.Equals(0) ? 0 : data[0][1],
  188. };
  189. }
  190. public async Task<int> GetAvgExceptMaxMinValue(string field, string tbName, string? condition)
  191. {
  192. var sql = $"SELECT MAX({field}), MIN({field}) FROM {_configTDengineService.DB}.{tbName} WHERE {condition}";
  193. var result = await GernalRestSqlResText(sql);
  194. var res = JsonConvert.DeserializeObject<TDengineRestResBase>(result!);
  195. List<dynamic> data = res?.Data!;
  196. var sqlAvg = $"SELECT AVG({field}) FROM {_configTDengineService.DB}.{tbName} WHERE {condition} AND {field} < { (data.Count.Equals(0)? 0: data[0][0]) } and {field} > {(data.Count.Equals(0) ? 0 : data[0][1])}";
  197. result = await GernalRestSqlResText(sqlAvg);
  198. res = JsonConvert.DeserializeObject<TDengineRestResBase>(result!);
  199. data = res?.Data!;
  200. return data.Count.Equals(0)?0:(int)data[0][0];
  201. }
  202. }
  203. }