MeterValueDbService.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  1. using Dapper;
  2. using EVCB_OCPP.Domain;
  3. using EVCB_OCPP.WSServer.Helper;
  4. using Microsoft.Data.SqlClient;
  5. using Microsoft.EntityFrameworkCore;
  6. using Microsoft.EntityFrameworkCore.Metadata.Internal;
  7. using Microsoft.Extensions.Configuration;
  8. using Microsoft.Extensions.Logging;
  9. using System.Data;
  10. using System.Data.Common;
  11. using System.Diagnostics;
  12. namespace EVCB_OCPP.WSServer.Service;
  13. public class MeterValueDbService
  14. {
  15. private readonly IDbContextFactory<MeterValueDBContext> meterValueDbContextFactory;
  16. private readonly SqlConnectionFactory<MeterValueDBContext> sqlConnectionFactory;
  17. private readonly ILoggerFactory loggerFactory;
  18. private readonly MeterValueGroupSingleHandler meterValueGroupSingleHandler;
  19. private readonly QueueSemaphore insertSemaphore;
  20. private readonly ILogger logger;
  21. private readonly Queue<string> _existTables = new();
  22. private GroupSingleHandler<InsertMeterValueParam> insertMeterValueHandler;
  23. public MeterValueDbService(
  24. IDbContextFactory<MeterValueDBContext> meterValueDbContextFactory,
  25. SqlConnectionFactory<MeterValueDBContext> sqlConnectionFactory,
  26. ILogger<MeterValueDbService> logger,
  27. ILoggerFactory loggerFactory,
  28. IConfiguration configuration
  29. //, MeterValueGroupSingleHandler meterValueGroupSingleHandler
  30. )
  31. {
  32. this.meterValueDbContextFactory = meterValueDbContextFactory;
  33. this.sqlConnectionFactory = sqlConnectionFactory;
  34. this.loggerFactory = loggerFactory;
  35. //this.meterValueGroupSingleHandler = meterValueGroupSingleHandler;
  36. //this.meterValueConnectionString = configuration.GetConnectionString("MeterValueDBContext");
  37. this.logger = logger;
  38. InitInsertMeterValueHandler();
  39. var insertLimit = GetInsertLimit(configuration);
  40. insertSemaphore = new QueueSemaphore(insertLimit);
  41. }
  42. public Task InsertAsync(string chargeBoxId, byte connectorId, decimal value, DateTime createdOn
  43. , int contextId, int formatId, int measurandId, int phaseId
  44. , int locationId, int unitId, int transactionId)
  45. {
  46. var param = new InsertMeterValueParam(chargeBoxId, connectorId, value, createdOn, contextId, formatId, measurandId, phaseId, locationId, unitId, transactionId);
  47. //return insertMeterValueHandler.HandleAsync(param);
  48. return InsertAsync(param);
  49. //return meterValueGroupSingleHandler.HandleAsync(param);
  50. }
  51. public Task InsertAsync(InsertMeterValueParam param)
  52. {
  53. //return InsertWithEF(param);
  54. return InsertWithDapper(param);
  55. }
  56. public Task InsertBundleAsync(IEnumerable<InsertMeterValueParam> param)
  57. {
  58. return BundleInsertWithDapper(param);
  59. }
  60. private void InitInsertMeterValueHandler()
  61. {
  62. if (insertMeterValueHandler is not null)
  63. {
  64. throw new Exception($"{nameof(InitInsertMeterValueHandler)} should only called once");
  65. }
  66. insertMeterValueHandler = new GroupSingleHandler<InsertMeterValueParam>(
  67. //BulkInsertWithBulkCopy,
  68. BundleInsertWithDapper,
  69. //loggerFactory.CreateLogger("InsertMeterValueHandler")
  70. logger,
  71. workerCnt:1
  72. );
  73. }
  74. private async Task BundleInsertWithStoredProcedure(IEnumerable<InsertMeterValueParam> parms)
  75. {
  76. foreach (var param in parms)
  77. {
  78. await InsertWithStoredProcedure(param);
  79. }
  80. }
  81. private async Task InsertWithEF(InsertMeterValueParam param)
  82. {
  83. using var token = await insertSemaphore.GetToken();
  84. using var db = await meterValueDbContextFactory.CreateDbContextAsync();
  85. string sp = "[dbo].[uspInsertMeterValueRecord] @ChargeBoxId, @ConnectorId,@Value,@CreatedOn,@ContextId,@FormatId,@MeasurandId,@PhaseId,@LocationId,@UnitId,@TransactionId";
  86. List<SqlParameter> parameter = new List<SqlParameter>();
  87. parameter.AddInsertMeterValueRecordSqlParameters(
  88. chargeBoxId: param.chargeBoxId
  89. , connectorId: (byte)param.connectorId
  90. , value: param.value
  91. , createdOn: param.createdOn
  92. , contextId: param.contextId
  93. , formatId: param.formatId
  94. , measurandId: param.measurandId
  95. , phaseId: param.phaseId
  96. , locationId: param.locationId
  97. , unitId: param.unitId
  98. , transactionId: param.transactionId);
  99. await db.Database.ExecuteSqlRawAsync(sp, parameter.ToArray());
  100. }
  101. private async Task InsertWithDapper(InsertMeterValueParam param)
  102. {
  103. var watch = Stopwatch.StartNew();
  104. long t0, t1;
  105. if (!await GetTableExist(param.createdOn))
  106. {
  107. t0 = watch.ElapsedMilliseconds;
  108. await InsertWithStoredProcedure(param);
  109. watch.Stop();
  110. t1 = watch.ElapsedMilliseconds;
  111. if (t1 > 500)
  112. {
  113. logger.LogWarning("MeterValue InsertWithStoredProcedure {0}/{1}", t0, t1);
  114. }
  115. return;
  116. }
  117. t0 = watch.ElapsedMilliseconds;
  118. var tableName = GetTableName(param.createdOn);
  119. await InsertWithNoCheckDapper(tableName, param);
  120. watch.Stop();
  121. t1 = watch.ElapsedMilliseconds;
  122. if(t1 > 700)
  123. {
  124. logger.LogWarning("MeterValue Dapper {0}/{1}", t0, t1);
  125. }
  126. }
  127. private async Task BundleInsertWithDapper(IEnumerable<InsertMeterValueParam> parms)
  128. {
  129. var watch = Stopwatch.StartNew();
  130. long t0, t1, t2, t3, t4;
  131. var parmsList = parms.ToList();
  132. foreach (var param in parms)
  133. {
  134. if (!await GetTableExist(param.createdOn))
  135. {
  136. await InsertWithStoredProcedure(param);
  137. parmsList.Remove(param);
  138. }
  139. }
  140. t0 = watch.ElapsedMilliseconds;
  141. //logger.LogInformation("MeterValue bundle insert cnt {0}", parmsList.Count);
  142. var gruopParams = parmsList.GroupBy(x => GetTableName(x.createdOn));
  143. t1 = watch.ElapsedMilliseconds;
  144. using SqlConnection sqlConnection = await sqlConnectionFactory.CreateAsync();
  145. //using var trans = await sqlConnection.BeginTransactionAsync();
  146. t2 = watch.ElapsedMilliseconds;
  147. List<Task> ExecuteTasks = new List<Task>();
  148. foreach (var group in gruopParams)
  149. {
  150. var tableName = group.Key;
  151. foreach(var param in group)
  152. {
  153. await InsertWithNoCheckDapper(tableName, param, sqlConnection
  154. //, trans
  155. );
  156. }
  157. }
  158. t3 = watch.ElapsedMilliseconds;
  159. //await trans.CommitAsync();
  160. watch.Stop();
  161. t4 = watch.ElapsedMilliseconds;
  162. if (t4 > 500)
  163. {
  164. logger.LogWarning("MeterValue Dapper {0}/{1}/{2}/{3}/{4}/{5}", t0, t1, t2, t3, t4, parms.Count());
  165. }
  166. }
  167. private async Task InsertWithNoCheckDapper(string tableName, InsertMeterValueParam data, SqlConnection conn = null, DbTransaction trans = null)
  168. {
  169. string command = $"""
  170. INSERT INTO {tableName} (ConnectorId, Value, CreatedOn, ContextId, FormatId, MeasurandId, PhaseId, LocationId, UnitId, ChargeBoxId, TransactionId)
  171. VALUES (@ConnectorId, @Value, @CreatedOn, @ContextId, @FormatId, @MeasurandId, @PhaseId, @LocationId, @UnitId, @ChargeBoxId, @TransactionId);
  172. """;
  173. bool isLocalConnection = conn is null;
  174. SqlConnection connection = isLocalConnection ? await sqlConnectionFactory.CreateAsync() : conn;
  175. var parameters = new DynamicParameters();
  176. parameters.Add("ConnectorId", data.connectorId, DbType.Int16);
  177. parameters.Add("Value", data.value, DbType.Decimal, precision: 18, scale: 8);
  178. parameters.Add("CreatedOn", data.createdOn, DbType.DateTime);
  179. parameters.Add("ContextId", data.contextId, DbType.Int32);
  180. parameters.Add("FormatId", data.formatId, DbType.Int32);
  181. parameters.Add("MeasurandId", data.measurandId, DbType.Int32);
  182. parameters.Add("PhaseId", data.phaseId, DbType.Int32);
  183. parameters.Add("LocationId", data.locationId, DbType.Int32);
  184. parameters.Add("UnitId", data.unitId, DbType.Int32);
  185. parameters.Add("ChargeBoxId", data.chargeBoxId, DbType.String, size: 50);
  186. parameters.Add("TransactionId", data.transactionId, DbType.Int32);
  187. await connection.ExecuteAsync(command, parameters, trans);
  188. if (isLocalConnection)
  189. {
  190. connection.Dispose();
  191. }
  192. }
  193. private async Task BulkInsertWithBulkCopy(IEnumerable<InsertMeterValueParam> parms)
  194. {
  195. var watcher = Stopwatch.StartNew();
  196. long t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0;
  197. var parmsList = parms.ToList();
  198. foreach (var param in parms)
  199. {
  200. if (!await GetTableExist(param.createdOn))
  201. {
  202. await InsertWithStoredProcedure(param);
  203. parmsList.Remove(param);
  204. }
  205. }
  206. //logger.LogInformation("MeterValue bundle insert cnt {0}", parmsList.Count);
  207. var gruopParams = parmsList.GroupBy(x => GetTableName(x.createdOn));
  208. t0 = watcher.ElapsedMilliseconds;
  209. foreach (var group in gruopParams)
  210. {
  211. var table = new DataTable();
  212. table.Columns.Add("ChargeBoxId");
  213. table.Columns.Add("ConnectorId");
  214. table.Columns.Add("Value");
  215. table.Columns.Add("CreatedOn");
  216. table.Columns.Add("ContextId");
  217. table.Columns.Add("FormatId");
  218. table.Columns.Add("MeasurandId");
  219. table.Columns.Add("PhaseId");
  220. table.Columns.Add("LocationId");
  221. table.Columns.Add("UnitId");
  222. table.Columns.Add("TransactionId");
  223. foreach (var param in group)
  224. {
  225. var row = table.NewRow();
  226. row["ChargeBoxId"] = param.chargeBoxId;
  227. row["ConnectorId"] = param.connectorId;
  228. row["Value"] = param.value;
  229. row["CreatedOn"] = param.createdOn;
  230. row["ContextId"] = param.contextId;
  231. row["FormatId"] = param.formatId;
  232. row["MeasurandId"] = param.measurandId;
  233. row["PhaseId"] = param.phaseId;
  234. row["LocationId"] = param.locationId;
  235. row["UnitId"] = param.unitId;
  236. row["TransactionId"] = param.transactionId;
  237. table.Rows.Add(row);
  238. }
  239. t1 = watcher.ElapsedMilliseconds;
  240. using SqlConnection sqlConnection = await sqlConnectionFactory.CreateAsync();
  241. using SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(sqlConnection);
  242. t2 = watcher.ElapsedMilliseconds;
  243. sqlBulkCopy.BatchSize = group.Count();
  244. sqlBulkCopy.DestinationTableName = group.Key;
  245. sqlBulkCopy.ColumnMappings.Add("ChargeBoxId", "ChargeBoxId");
  246. sqlBulkCopy.ColumnMappings.Add("ConnectorId", "ConnectorId");
  247. sqlBulkCopy.ColumnMappings.Add("Value", "Value");
  248. sqlBulkCopy.ColumnMappings.Add("CreatedOn", "CreatedOn");
  249. sqlBulkCopy.ColumnMappings.Add("ContextId", "ContextId");
  250. sqlBulkCopy.ColumnMappings.Add("FormatId", "FormatId");
  251. sqlBulkCopy.ColumnMappings.Add("MeasurandId", "MeasurandId");
  252. sqlBulkCopy.ColumnMappings.Add("PhaseId", "PhaseId");
  253. sqlBulkCopy.ColumnMappings.Add("LocationId", "LocationId");
  254. sqlBulkCopy.ColumnMappings.Add("UnitId", "UnitId");
  255. sqlBulkCopy.ColumnMappings.Add("TransactionId", "TransactionId");
  256. t3 = watcher.ElapsedMilliseconds;
  257. await sqlBulkCopy.WriteToServerAsync(table);
  258. }
  259. watcher.Stop();
  260. t4 = watcher.ElapsedMilliseconds;
  261. if (t4 > 500)
  262. {
  263. logger.LogWarning("MeterValue BulkInsertWithBulkCopy Slow {0}/{1}/{2}/{3}/{4}/{5}", t0,t1,t2,t3,t4, parms.Count());
  264. }
  265. }
  266. private async ValueTask<bool> GetTableExist(DateTime tableDateTime)
  267. {
  268. var tableName = GetTableName(tableDateTime);
  269. if (_existTables.Contains(tableName))
  270. {
  271. return true;
  272. }
  273. FormattableString checkTableSql = $"SELECT Count(*) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = {tableName}";
  274. using var db = await meterValueDbContextFactory.CreateDbContextAsync();
  275. var resultList = db.Database.SqlQuery<int>(checkTableSql)?.ToList();
  276. if (resultList is not null && resultList.Count > 0 && resultList[0] > 0)
  277. {
  278. _existTables.Enqueue(tableName);
  279. if (_existTables.Count > 30)
  280. {
  281. _existTables.TryDequeue(out _);
  282. }
  283. return true;
  284. }
  285. return false;
  286. }
  287. private async Task InsertWithStoredProcedure(InsertMeterValueParam param)
  288. {
  289. using var db = await meterValueDbContextFactory.CreateDbContextAsync();
  290. string sp = "[dbo].[uspInsertMeterValueRecord] @ChargeBoxId," +
  291. "@ConnectorId,@Value,@CreatedOn,@ContextId,@FormatId,@MeasurandId,@PhaseId,@LocationId,@UnitId,@TransactionId";
  292. List<SqlParameter> parameter = new List<SqlParameter>();
  293. parameter.AddInsertMeterValueRecordSqlParameters(
  294. chargeBoxId: param.chargeBoxId
  295. , connectorId: (byte)param.connectorId
  296. , value: param.value
  297. , createdOn: param.createdOn
  298. , contextId: param.contextId
  299. , formatId: param.formatId
  300. , measurandId: param.measurandId
  301. , phaseId: param.phaseId
  302. , locationId: param.locationId
  303. , unitId: param.unitId
  304. , transactionId: param.transactionId);
  305. await db.Database.ExecuteSqlRawAsync(sp, parameter.ToArray());
  306. }
  307. private static string GetTableName(DateTime dateTime)
  308. => $"ConnectorMeterValueRecord{dateTime:yyMMdd}";
  309. private int GetInsertLimit(IConfiguration configuration)
  310. {
  311. var limitConfig = configuration["MeterValueDbInsertLimit"];
  312. int limit = 10;
  313. if (limitConfig != default)
  314. {
  315. int.TryParse(limitConfig, out limit);
  316. }
  317. return limit;
  318. }
  319. }
  320. public record InsertMeterValueParam(string chargeBoxId, byte connectorId, decimal value, DateTime createdOn
  321. , int contextId, int formatId, int measurandId, int phaseId
  322. , int locationId, int unitId, int transactionId);