DatabaseCleaner.cs 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Configuration;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using System.Timers;
  8. using Aitex.Core.RT.DBCore;
  9. using Aitex.Core.RT.Log;
  10. using Aitex.Core.RT.SCCore;
  11. using Aitex.Core.Util;
  12. using log4net.Repository.Hierarchy;
  13. using Npgsql;
  14. namespace MECF.Framework.Common.DBCore
  15. {
  16. /// <summary>
  17. /// 单例模式,周期性地执行删除数据表的操作
  18. /// </summary>
  19. public sealed class DatabaseCleaner
  20. {
  21. NpgsqlConnection conn;
  22. List<string> tableNames = new List<string>();
  23. bool _isDataCleanEnabled = false;
  24. int _daysOfRetainData = 90;
  25. DateTime _dateDataKeepTo;
  26. private PeriodicJob _cleanThread;
  27. private string _dbName;
  28. public DatabaseCleaner()
  29. {
  30. }
  31. public void Initialize(string dbName)
  32. {
  33. _dbName = dbName;
  34. _isDataCleanEnabled = !SC.ContainsItem("System.EnableDataClean") || SC.GetValue<bool>("System.EnableDataClean");
  35. if (_isDataCleanEnabled)
  36. {
  37. GetDaysOfRetainData();
  38. }
  39. _cleanThread = new PeriodicJob(24 * 60 * 60 *1000, MonitorCleanData, "Database cleaner", true);
  40. }
  41. public void Terminate()
  42. {
  43. _cleanThread.Stop();
  44. }
  45. public bool MonitorCleanData( )
  46. {
  47. try
  48. {
  49. string sql = null;
  50. string log = null;
  51. int count = 0;
  52. NpgsqlCommand command = null;
  53. string[,] timeStamp = { { "carrier_data", "load_time" },
  54. { "event_data", "occur_time" },
  55. { "process_data", "process_begin_time" },
  56. { "wafer_data", "create_time" },
  57. { "wafer_move_history", "arrive_time" } };
  58. GetDaysOfRetainData();
  59. tableNames.Clear();
  60. GetTableNames();
  61. if (tableNames.Count == 0) return true; // 数据库中没有需要删除的数据表
  62. // 实例化一个NpsqlConnection的对象
  63. conn = new NpgsqlConnection(PostgresqlHelper.ConnectionString);
  64. conn.Open();
  65. conn.ChangeDatabase(_dbName);
  66. DeviceTimer timer = new DeviceTimer();
  67. for (int i = 0; i < timeStamp.GetLength(0); i++)
  68. {
  69. // 判断数据库中是否存在指定的表和字段
  70. sql = string.Format("select count(*) from information_schema.columns where table_schema='public' and table_name ='{0}' and column_name='{1}'", timeStamp[i, 0], timeStamp[i, 1]);
  71. command = new NpgsqlCommand(sql, conn);
  72. count = Convert.ToInt32(command.ExecuteScalar());
  73. if (count == 1) // 存在则返回1,不存在则返回0
  74. {
  75. // 删除指定日期前的所有记录
  76. timer.Start(300 * 1000);
  77. sql = string.Format("delete from \"{0}\" where \"{1}\" <= '{2}'", timeStamp[i, 0], timeStamp[i, 1], _dateDataKeepTo.ToString("yyyy/MM/dd HH:mm:ss.fff"));
  78. command = new NpgsqlCommand(sql, conn);
  79. command.ExecuteNonQuery();
  80. double elapsedTime = timer.GetElapseTime() / 1000;
  81. log = string.Format("当前日期为{0},删除目录表{1}里{2}天前的记录,用时{3}秒,执行的sql:{4}", System.DateTime.Now.ToString("D"), timeStamp[i, 0], _daysOfRetainData, elapsedTime, sql);
  82. LOG.Info(log);
  83. System.Threading.Thread.Sleep(50);
  84. }
  85. }
  86. foreach (string tableName in tableNames)
  87. {
  88. timer.Start(300 * 1000);
  89. sql = string.Format("drop table \"{0}\"", tableName);
  90. command = new NpgsqlCommand(sql, conn);
  91. command.ExecuteNonQuery();
  92. double elapsedTime = timer.GetElapseTime() / 1000;
  93. log = string.Format("当前日期为{0},删除{1}天前的数据表{2},用时{3}秒,执行的sql:{4}", System.DateTime.Now.ToString("D"), _daysOfRetainData, tableName, elapsedTime, sql);
  94. LOG.Info(log);
  95. System.Threading.Thread.Sleep(50);
  96. }
  97. conn.Close();
  98. conn.ClearPool();
  99. conn = null;
  100. }
  101. catch (Exception ex)
  102. {
  103. LOG.Write(ex);
  104. if (conn != null)
  105. {
  106. conn.Close();
  107. conn.ClearPool();
  108. }
  109. conn = null;
  110. }
  111. return true;
  112. }
  113. /// <summary>
  114. /// 获取数据表的总数
  115. /// </summary>
  116. /// <returns></returns>
  117. public void GetTableNames()
  118. {
  119. try
  120. {
  121. // 实例化一个NpsqlConnection的对象
  122. conn = new NpgsqlConnection(PostgresqlHelper.ConnectionString);
  123. _dateDataKeepTo = System.DateTime.Now.AddDays(-_daysOfRetainData); // 获取90天前的年月日
  124. string sql = "select tablename from pg_tables where schemaname='public' and tablename like '20%' order by tablename asc";
  125. conn.Open();
  126. conn.ChangeDatabase(_dbName);
  127. NpgsqlCommand command = new NpgsqlCommand(sql, conn);
  128. NpgsqlDataReader dataReader = command.ExecuteReader(); // 获得一个结果集的检索结果
  129. while (dataReader.Read())
  130. {
  131. for (int i = 0; i < dataReader.FieldCount; i++)
  132. {
  133. string tableName = dataReader[i].ToString();
  134. tableName = tableName.Substring(0, 8);
  135. if (DateTime.ParseExact(tableName, "yyyyMMdd", System.Globalization.CultureInfo.InvariantCulture) <= _dateDataKeepTo) // 判断是否早于指定的日期
  136. {
  137. tableNames.Add(dataReader[i].ToString());
  138. }
  139. }
  140. }
  141. dataReader.Close();
  142. dataReader.Dispose();
  143. conn.Close();
  144. conn.ClearPool();
  145. conn = null;
  146. }
  147. catch (Exception ex)
  148. {
  149. LOG.Write(ex);
  150. if (conn != null)
  151. {
  152. conn.Close();
  153. conn.ClearPool();
  154. }
  155. conn = null;
  156. }
  157. }
  158. /// <summary>
  159. /// 获取需要保留数据的天数
  160. /// </summary>
  161. public void GetDaysOfRetainData()
  162. {
  163. int days = 90;
  164. if (SC.ContainsItem("System.DataKeepDays"))
  165. days = SC.GetValue<int>("System.DataKeepDays");
  166. if (days < 10)
  167. {
  168. LOG.Warning($"database keep days should be at least 10 days.current setting {days}");
  169. days = 10;
  170. }
  171. if (days > 365)
  172. {
  173. LOG.Warning($"database keep days should be less than 365 days.current setting {days}");
  174. days = 365;
  175. }
  176. _daysOfRetainData = days;
  177. }
  178. }
  179. }