MeterValueDbService.cs 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. using EVCB_OCPP.Domain;
  2. using EVCB_OCPP.Packet.Messages.SubTypes;
  3. using EVCB_OCPP.WSServer.Helper;
  4. using Microsoft.Data.SqlClient;
  5. using Microsoft.EntityFrameworkCore;
  6. using Microsoft.Extensions.Configuration;
  7. using Microsoft.Extensions.Logging;
  8. using System;
  9. using System.Collections.Concurrent;
  10. using System.Collections.Generic;
  11. using System.Configuration;
  12. using System.Data;
  13. using System.Diagnostics;
  14. using System.Linq;
  15. using System.Text;
  16. using System.Threading.Tasks;
  17. namespace EVCB_OCPP.WSServer.Service;
  18. public class MeterValueDbService
  19. {
  20. private readonly IDbContextFactory<MeterValueDBContext> meterValueDbContextFactory;
  21. private readonly ILoggerFactory loggerFactory;
  22. private readonly QueueSemaphore insertSemaphore;
  23. private readonly string meterValueConnectionString;
  24. private readonly ILogger logger;
  25. private GroupSingleHandler<InsertMeterValueParam> insertMeterValueHandler;
  26. private Queue<string> _existTables = new();
  27. public MeterValueDbService(
  28. IDbContextFactory<MeterValueDBContext> meterValueDbContextFactory,
  29. ILogger<MeterValueDbService> logger,
  30. ILoggerFactory loggerFactory,
  31. IConfiguration configuration)
  32. {
  33. this.meterValueDbContextFactory = meterValueDbContextFactory;
  34. this.loggerFactory = loggerFactory;
  35. this.meterValueConnectionString = configuration.GetConnectionString("MeterValueDBContext");
  36. this.logger = logger;
  37. InitInsertMeterValueHandler();
  38. var insertLimit = GetInsertLimit(configuration);
  39. insertSemaphore = new QueueSemaphore(insertLimit);
  40. }
  41. public Task InsertAsync(string chargeBoxId, byte connectorId, decimal value, DateTime createdOn
  42. , int contextId, int formatId, int measurandId, int phaseId
  43. , int locationId, int unitId, int transactionId)
  44. {
  45. //using var token = await insertSemaphore.GetToken();
  46. //using var db = await meterValueDbContextFactory.CreateDbContextAsync();
  47. //string sp = "[dbo].[uspInsertMeterValueRecord] @ChargeBoxId, @ConnectorId,@Value,@CreatedOn,@ContextId,@FormatId,@MeasurandId,@PhaseId,@LocationId,@UnitId,@TransactionId";
  48. var param = new InsertMeterValueParam(chargeBoxId, connectorId, value, createdOn, contextId, formatId, measurandId, phaseId, locationId, unitId, transactionId);
  49. //List<SqlParameter> parameter = new List<SqlParameter>();
  50. //parameter.AddInsertMeterValueRecordSqlParameters(
  51. // chargeBoxId: param.chargeBoxId
  52. // , connectorId: (byte)param.connectorId
  53. // , value: param.value
  54. // , createdOn: param.createdOn
  55. // , contextId: param.contextId
  56. // , formatId: param.formatId
  57. // , measurandId: param.measurandId
  58. // , phaseId: param.phaseId
  59. // , locationId: param.locationId
  60. // , unitId: param.unitId
  61. // , transactionId: param.transactionId);
  62. //await db.Database.ExecuteSqlRawAsync(sp, parameter.ToArray());
  63. return insertMeterValueHandler.HandleAsync(param);
  64. }
  65. private void InitInsertMeterValueHandler()
  66. {
  67. if (insertMeterValueHandler is not null)
  68. {
  69. throw new Exception($"{nameof(InitInsertMeterValueHandler)} should only called once");
  70. }
  71. insertMeterValueHandler = new GroupSingleHandler<InsertMeterValueParam>(
  72. BulkInsertWithCache,
  73. //loggerFactory.CreateLogger("InsertMeterValueHandler")
  74. logger
  75. );
  76. }
  77. private async Task BundleInsertWithStoredProcedure(IEnumerable<InsertMeterValueParam> parms)
  78. {
  79. foreach (var param in parms)
  80. {
  81. await InsertWithStoredProcedure(param);
  82. }
  83. }
  84. private async Task BulkInsertWithCache(IEnumerable<InsertMeterValueParam> parms)
  85. {
  86. var watcher = Stopwatch.StartNew();
  87. long t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0;
  88. var parmsList = parms.ToList();
  89. foreach (var param in parms)
  90. {
  91. if (!await GetTableExist(param.createdOn))
  92. {
  93. await InsertWithStoredProcedure(param);
  94. parmsList.Remove(param);
  95. }
  96. }
  97. //logger.LogInformation("MeterValue bundle insert cnt {0}", parmsList.Count);
  98. var gruopParams = parmsList.GroupBy(x => GetTableName(x.createdOn));
  99. t0 = watcher.ElapsedMilliseconds;
  100. foreach (var group in gruopParams)
  101. {
  102. var table = new DataTable();
  103. table.Columns.Add("ChargeBoxId");
  104. table.Columns.Add("ConnectorId");
  105. table.Columns.Add("Value");
  106. table.Columns.Add("CreatedOn");
  107. table.Columns.Add("ContextId");
  108. table.Columns.Add("FormatId");
  109. table.Columns.Add("MeasurandId");
  110. table.Columns.Add("PhaseId");
  111. table.Columns.Add("LocationId");
  112. table.Columns.Add("UnitId");
  113. table.Columns.Add("TransactionId");
  114. foreach (var param in group)
  115. {
  116. var row = table.NewRow();
  117. row["ChargeBoxId"] = param.chargeBoxId;
  118. row["ConnectorId"] = param.connectorId;
  119. row["Value"] = param.value;
  120. row["CreatedOn"] = param.createdOn;
  121. row["ContextId"] = param.contextId;
  122. row["FormatId"] = param.formatId;
  123. row["MeasurandId"] = param.measurandId;
  124. row["PhaseId"] = param.phaseId;
  125. row["LocationId"] = param.locationId;
  126. row["UnitId"] = param.unitId;
  127. row["TransactionId"] = param.transactionId;
  128. table.Rows.Add(row);
  129. }
  130. t1 = watcher.ElapsedMilliseconds;
  131. using SqlConnection sqlConnection = new SqlConnection(meterValueConnectionString);
  132. sqlConnection.Open();
  133. using SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(sqlConnection);
  134. t2 = watcher.ElapsedMilliseconds;
  135. sqlBulkCopy.BatchSize = group.Count();
  136. sqlBulkCopy.DestinationTableName = group.Key;
  137. sqlBulkCopy.ColumnMappings.Add("ChargeBoxId", "ChargeBoxId");
  138. sqlBulkCopy.ColumnMappings.Add("ConnectorId", "ConnectorId");
  139. sqlBulkCopy.ColumnMappings.Add("Value", "Value");
  140. sqlBulkCopy.ColumnMappings.Add("CreatedOn", "CreatedOn");
  141. sqlBulkCopy.ColumnMappings.Add("ContextId", "ContextId");
  142. sqlBulkCopy.ColumnMappings.Add("FormatId", "FormatId");
  143. sqlBulkCopy.ColumnMappings.Add("MeasurandId", "MeasurandId");
  144. sqlBulkCopy.ColumnMappings.Add("PhaseId", "PhaseId");
  145. sqlBulkCopy.ColumnMappings.Add("LocationId", "LocationId");
  146. sqlBulkCopy.ColumnMappings.Add("UnitId", "UnitId");
  147. sqlBulkCopy.ColumnMappings.Add("TransactionId", "TransactionId");
  148. t3 = watcher.ElapsedMilliseconds;
  149. sqlBulkCopy.WriteToServer(table);
  150. }
  151. watcher.Stop();
  152. t4 = watcher.ElapsedMilliseconds;
  153. if (t4 > 500)
  154. {
  155. logger.LogWarning("BulkInsertWithCache Slow {0}/{1}/{2}/{3}/{4}",t0,t1,t2,t3,t4);
  156. }
  157. }
  158. private async ValueTask<bool> GetTableExist(DateTime tableDateTime)
  159. {
  160. var tableName = GetTableName(tableDateTime);
  161. if (_existTables.Contains(tableName))
  162. {
  163. return true;
  164. }
  165. FormattableString checkTableSql = $"SELECT Count(*) FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = {tableName}";
  166. using var db = await meterValueDbContextFactory.CreateDbContextAsync();
  167. var resultList = db.Database.SqlQuery<int>(checkTableSql)?.ToList();
  168. if (resultList is not null && resultList.Count > 0 && resultList[0] > 0)
  169. {
  170. _existTables.Enqueue(tableName);
  171. if (_existTables.Count > 30)
  172. {
  173. _existTables.TryDequeue(out _);
  174. }
  175. return true;
  176. }
  177. return false;
  178. }
  179. private async Task InsertWithStoredProcedure(InsertMeterValueParam param)
  180. {
  181. using var db = await meterValueDbContextFactory.CreateDbContextAsync();
  182. string sp = "[dbo].[uspInsertMeterValueRecord] @ChargeBoxId," +
  183. "@ConnectorId,@Value,@CreatedOn,@ContextId,@FormatId,@MeasurandId,@PhaseId,@LocationId,@UnitId,@TransactionId";
  184. List<SqlParameter> parameter = new List<SqlParameter>();
  185. parameter.AddInsertMeterValueRecordSqlParameters(
  186. chargeBoxId: param.chargeBoxId
  187. , connectorId: (byte)param.connectorId
  188. , value: param.value
  189. , createdOn: param.createdOn
  190. , contextId: param.contextId
  191. , formatId: param.formatId
  192. , measurandId: param.measurandId
  193. , phaseId: param.phaseId
  194. , locationId: param.locationId
  195. , unitId: param.unitId
  196. , transactionId: param.transactionId);
  197. db.Database.ExecuteSqlRaw(sp, parameter.ToArray());
  198. }
  199. private static string GetTableName(DateTime dateTime)
  200. => $"ConnectorMeterValueRecord{dateTime:yyMMdd}";
  201. private int GetInsertLimit(IConfiguration configuration)
  202. {
  203. var limitConfig = configuration["MeterValueDbInsertLimit"];
  204. int limit = 10;
  205. if (limitConfig != default)
  206. {
  207. int.TryParse(limitConfig, out limit);
  208. }
  209. return limit;
  210. }
  211. }
  212. public record InsertMeterValueParam(string chargeBoxId, byte connectorId, decimal value, DateTime createdOn
  213. , int contextId, int formatId, int measurandId, int phaseId
  214. , int locationId, int unitId, int transactionId);