MemDbService.cs 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. using Dapper;
  2. using EVCB_OCPP.DBAPI.ConnectionFactory;
  3. using EVCB_OCPP.DBAPI.Models.DBContext;
  4. using EVCB_OCPP.DBAPI.Services.ServerMessageServices;
  5. using Microsoft.Data.Sqlite;
  6. using Microsoft.Extensions.DependencyInjection;
  7. using Newtonsoft.Json;
  8. using SQLitePCL;
  9. using System.Diagnostics;
  10. namespace EVCB_OCPP.DBAPI.Services
  11. {
  12. public static class MemDbServiceExtentions
  13. {
  14. public const string BackupFileName = "SqlLiteBackup.db";
  15. public static IServiceCollection AddMemConnectionFactory(this IServiceCollection services)
  16. {
  17. services.AddSingleton<ISqliteConnectionConnectionFactory<MemDBContext>>(
  18. (serviceProvider) =>
  19. {
  20. return new SqliteConnectionFactory<MemDBContext>(serviceProvider.GetRequiredService<ILogger<SqliteConnectionFactory<MemDBContext>>>())
  21. {
  22. ConnectionString = "Data Source=InMemory;Mode=Memory;Cache=Shared"
  23. };
  24. });
  25. return services;
  26. }
  27. public static IServiceCollection AddFileCacheConnectionFactory(this IServiceCollection services)
  28. {
  29. services.AddSingleton<ISqliteConnectionConnectionFactory<FileDBContext>>(
  30. (serviceProvider) =>
  31. {
  32. var safePath = GetSafeFolderPath(serviceProvider.GetRequiredService<IConfiguration>());
  33. var backupFilePath = Path.Combine(safePath, BackupFileName);
  34. return new SqliteConnectionFactory<FileDBContext>(serviceProvider.GetRequiredService<ILogger<SqliteConnectionFactory<FileDBContext>>>())
  35. {
  36. ConnectionString = string.Format("Data Source= '{0}';", backupFilePath)
  37. };
  38. });
  39. return services;
  40. }
  41. public static IServiceCollection AddMemDbService(this IServiceCollection services)
  42. {
  43. services.AddFileCacheConnectionFactory();
  44. services.AddMemConnectionFactory();
  45. services.AddSingleton<MemDbService>();
  46. services.AddHostedService<MemDbService>( x => x.GetRequiredService<MemDbService>());
  47. return services;
  48. }
  49. internal static string GetSafeFolderPath(IConfiguration configuration)
  50. {
  51. var configSafeFolderPath = configuration["SafeFolderPath"];
  52. return string.IsNullOrEmpty(configSafeFolderPath) ? Directory.GetCurrentDirectory() : configSafeFolderPath;
  53. }
  54. }
  55. public class MemDbService : IHostedService
  56. {
  57. public MemDbService(
  58. IConfiguration configuration,
  59. ISqliteConnectionConnectionFactory<MemDBContext> memDbConnectionFactory,
  60. ISqliteConnectionConnectionFactory<FileDBContext> fileDbConnectionFactory,
  61. ILogger<MemDbService> logger
  62. )
  63. {
  64. this.memDbConnectionFactory = memDbConnectionFactory;
  65. this.fileDbConnectionFactory = fileDbConnectionFactory;
  66. this.logger = logger;
  67. }
  68. private readonly ISqliteConnectionConnectionFactory<MemDBContext> memDbConnectionFactory;
  69. private readonly ISqliteConnectionConnectionFactory<FileDBContext> fileDbConnectionFactory;
  70. private readonly ILogger<MemDbService> logger;
  71. private SqliteConnection? memConnectionCache = null;
  72. public async Task StartAsync(CancellationToken cancellationToken)
  73. {
  74. Stopwatch stopwatch = Stopwatch.StartNew();
  75. memConnectionCache = await memDbConnectionFactory.CreateAsync();
  76. await LoadBackupedData();
  77. await InitializeDbAsync();
  78. stopwatch.Stop();
  79. logger.LogDebug("MemDbService StartAsync cost {time} ms", stopwatch.ElapsedMilliseconds);
  80. }
  81. public async Task StopAsync(CancellationToken cancellationToken)
  82. {
  83. Stopwatch stopwatch = Stopwatch.StartNew();
  84. await SaveDbToFileAsync();
  85. await memConnectionCache!.DisposeAsync();
  86. stopwatch.Stop();
  87. logger.LogDebug("MemDbService StopAsync cost {time} ms", stopwatch.ElapsedMilliseconds);
  88. }
  89. public async Task<string> GetMemoryUsage()
  90. {
  91. var memoryUsed = raw.sqlite3_memory_used();
  92. return $"Memory used by SQLite (in bytes): {memoryUsed}";
  93. var cmd0 = """
  94. PRAGMA page_size
  95. """;
  96. var cmd1 = """
  97. PRAGMA page_count
  98. """;
  99. var connection = await memDbConnectionFactory.CreateAsync();
  100. var page_size = await connection.QueryFirstOrDefaultAsync<int>(cmd0);
  101. var page_count = await connection.QueryFirstOrDefaultAsync<int>(cmd1);
  102. return $"{page_count}x{page_size}={page_count* page_size} (bytes):";
  103. }
  104. private async Task InitializeDbAsync()
  105. {
  106. var connection = await memDbConnectionFactory.CreateAsync();
  107. await MemDbServerMessageService.IinitMemDbAsync(connection);
  108. }
  109. private async Task SaveDbToFileAsync()
  110. {
  111. using var memConnection = await memDbConnectionFactory.CreateAsync();
  112. using var fileConnection = await fileDbConnectionFactory.CreateAsync();
  113. memConnection.BackupDatabase(fileConnection);
  114. }
  115. private async Task LoadBackupedData()
  116. {
  117. using var memConnection = await memDbConnectionFactory.CreateAsync();
  118. using var fileConnection = await fileDbConnectionFactory.CreateAsync();
  119. fileConnection.BackupDatabase(memConnection);
  120. }
  121. }
  122. }