DataUploadJob.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. using log4net;
  2. using Quartz;
  3. using RabbitMQ.Client;
  4. using RDIFramework.Utilities;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Configuration;
  8. using System.Data;
  9. using System.IO;
  10. using System.Text;
  11. namespace TimedUpload.QuartzJobs
  12. {
  13. [DisallowConcurrentExecution]
  14. public class DataUploadJob:IJob
  15. {
  16. private readonly ILog log = LogManager.GetLogger(typeof(DataUploadJob));
  17. public void Execute(IJobExecutionContext context)
  18. {
  19. string[] uploadUrls = Constants.UploadUrl.Split('|');
  20. Dictionary<string, IConnection> connections = new Dictionary<string, IConnection>();
  21. Dictionary<string, IModel> channels = new Dictionary<string, IModel>();
  22. Dictionary<string, IBasicProperties> properties = new Dictionary<string, IBasicProperties>();
  23. foreach (string uploadUrl in uploadUrls)
  24. {
  25. ConnectionFactory factory = new ConnectionFactory();
  26. factory.HostName = uploadUrl;//主机名,Rabbit会拿这个IP生成一个endpoint,这个很熟悉吧,就是socket绑定的那个终结点。
  27. factory.UserName = Constants.UploadUserName;//默认用户名,用户可以在服务端自定义创建,有相关命令行
  28. factory.Password = Constants.UploadPassword;//默认密码
  29. factory.AutomaticRecoveryEnabled = true; // 链接断开会自动重连
  30. IConnection connection = factory.CreateConnection();
  31. IModel channel = connection.CreateModel();
  32. channel.QueueDeclare("zone.device", true, false, false, null);//创建一个名称为kibaqueue的消息队列
  33. channel.QueueDeclare("zone.deviceHis", true, false, false, null);//创建一个名称为kibaqueue的消息队列
  34. IBasicProperties property = channel.CreateBasicProperties();
  35. property.ContentType = "text/plain";
  36. property.DeliveryMode = 2; //持久化
  37. connections.Add(uploadUrl, connection);
  38. properties.Add(uploadUrl, property);
  39. channels.Add(uploadUrl, channel);
  40. }
  41. if (channels.Count > 0)
  42. {
  43. SendZoneDevice(channels, properties);
  44. SendZoneDeviceHis(channels, properties);
  45. }
  46. foreach (KeyValuePair<string, IConnection> item in connections)
  47. {
  48. IConnection connection = item.Value;
  49. connection.Close();
  50. }
  51. }
  52. /// <summary>
  53. /// 大表设备添加
  54. /// </summary>
  55. /// <param name="channels"></param>
  56. /// <param name="properties"></param>
  57. private void SendZoneDevice(Dictionary<string, IModel> channels, Dictionary<string, IBasicProperties> properties)
  58. {
  59. try
  60. {
  61. String meterId = Constants.MeterId;
  62. String sql = "SELECT a.ID,a.名称,a.考核表编码,a.X坐标,a.Y坐标,b.传输协议参数 FROM [设备信息] a left join 传输设备 b on a.传输设备ID = b.ID where a.是否启用 = '是' and a.考核表编码 is not null and a.ID > " + meterId + " order by a.ID";
  63. DataTable dt = dbHelper.Fill(sql);
  64. if (dt == null)
  65. {
  66. log.Info("大表设备同步任务查询报错.................\r\n");
  67. return;
  68. }
  69. if (dt.Rows.Count == 0)
  70. {
  71. log.Info("大表设备同步任务,没有需要同步的设备.................\r\n");
  72. return;
  73. }
  74. log.Info("大表设备同步任务开始执行.................\r\n");
  75. StringBuilder message = new StringBuilder();
  76. for (int i = 0; i < dt.Rows.Count; i++)
  77. {
  78. message.Clear();
  79. try
  80. {
  81. DataRow dr = dt.Rows[i];
  82. String iccid = "";
  83. if (!"".Equals(dr["传输协议参数"].ToString()))
  84. {
  85. iccid = dr["传输协议参数"].ToString().Split(',')[0];
  86. }
  87. String lngAndLat = "";
  88. if (!"".Equals(dr["X坐标"].ToString()) && !"".Equals(dr["Y坐标"].ToString()))
  89. {
  90. lngAndLat = dr["X坐标"].ToString() + "|" + dr["Y坐标"].ToString();
  91. }
  92. message.Append("{");
  93. message.Append("\"meterAssessmentName\": \"").Append(dr["名称"]).Append("\",");
  94. message.Append("\"iccId\": ").Append(iccid).Append(",");
  95. //message.Append("\"areaId\": 22,");
  96. message.Append("\"lngAndLat\": \"").Append(lngAndLat).Append("\",");
  97. //message.Append("\"pipeCailber\": \"DN32\",");
  98. //message.Append("\"pipeTexture\": \"PVC\",");
  99. //message.Append("\"imei\": \"77564212\",");
  100. message.Append("\"isPressucre\": 1,");
  101. message.Append("\"isFlow\": 1,");
  102. message.Append("\"isZoneMeter\": 1,");
  103. message.Append("\"isTradeMeter\": 0,");
  104. message.Append("\"isLargeUser\": 0,");
  105. message.Append("\"meterAssessmentCode\": \"").Append(dr["考核表编码"]).Append("\",");
  106. message.Append("\"manufacturerCode\": \"").Append(Constants.ManufacturerCode).Append("\",");
  107. message.Append("\"meterTypeId\": \"2\"");
  108. message.Append("}");
  109. foreach (KeyValuePair<string, IModel> item in channels)
  110. {
  111. string key = item.Key;
  112. IModel channel = item.Value;
  113. IBasicProperties property = properties[key];
  114. channel.BasicPublish("zone.device", "", property, Encoding.UTF8.GetBytes(message.ToString())); //生产消息
  115. }
  116. meterId = dr["ID"].ToString();
  117. }
  118. catch (Exception ex)
  119. {
  120. log.Info("大表设备同步任务数据推送失败:" + message.ToString() + "\r\n");
  121. log.Error(ex.Message + "===========" + ex.StackTrace + "\r\n");
  122. }
  123. }
  124. UpdateAppConfig("MeterId", meterId);
  125. log.Info("大表设备同步任务执行结束.................\r\n");
  126. }
  127. catch (Exception ex)
  128. {
  129. log.Error("大表设备同步任务执行错误:" + ex.Message + "===========" + ex.StackTrace + "\r\n");
  130. }
  131. }
  132. /// <summary>
  133. /// 大表历史数据
  134. /// </summary>
  135. /// <param name="channels"></param>
  136. /// <param name="properties"></param>
  137. private void SendZoneDeviceHis(Dictionary<string, IModel> channels, Dictionary<string, IBasicProperties> properties)
  138. {
  139. try
  140. {
  141. log.Info("大表设备历史数据同步任务开始执行.................\r\n");
  142. String sqlMeter = "SELECT ID,考核表编码 FROM [设备信息] where 是否启用 = '是' and 考核表编码 is not null order by ID";
  143. DataTable dtMeter = dbHelper.Fill(sqlMeter);
  144. //Dictionary<string, object> arguments = new Dictionary<string, object>();
  145. //arguments["x-max-length-bytes"] = 2147383648;
  146. //arguments["x-overflow"] = "reject-publish";
  147. Dictionary<String, String> uploadHis = new Dictionary<string, string>();
  148. using (StreamReader sr = new StreamReader(@"TextFile1.txt"))
  149. {
  150. String line = "";
  151. while ((line = sr.ReadLine()) != null)
  152. {
  153. if (!"".Equals(line))
  154. {
  155. String[] item = line.Split(',');
  156. uploadHis[item[0]] = item[1];
  157. }
  158. }
  159. }
  160. for (int i = 0; i < dtMeter.Rows.Count; i++)
  161. {
  162. DataRow drMeter = dtMeter.Rows[i];
  163. String meterId = drMeter["ID"].ToString();
  164. String meterCode = drMeter["考核表编码"].ToString();
  165. String lastTime = "";
  166. int nowYear = DateTime.Now.Year;
  167. int lastYear = uploadHis.ContainsKey(meterCode) ? Convert.ToDateTime(uploadHis[meterCode]).Year : nowYear;
  168. for (int k = lastYear; k <= nowYear; k++)
  169. {
  170. string tablename = "历史记录_" + ("000000" + meterId).Substring(meterId.Length, 6) + "_" + k;
  171. // 判断历史记录表是否存在
  172. if (!CheckTableExist(tablename))
  173. {
  174. continue;
  175. }
  176. String sqlMeterHis = "select 记录时间,采集时间,正累计流量,负累计流量,净累计流量,瞬时流量,电池电压,压力 from " + tablename;
  177. if (uploadHis.ContainsKey(meterCode))
  178. {
  179. sqlMeterHis += " where 采集时间 > '" + uploadHis[meterCode] + "'";
  180. }
  181. sqlMeterHis += " order by 采集时间";
  182. DataTable dtMeterHis = dbHelper.Fill(sqlMeterHis);
  183. StringBuilder message = new StringBuilder();
  184. for (int j = 0; j < dtMeterHis.Rows.Count; j++)
  185. {
  186. message.Clear();
  187. try
  188. {
  189. DataRow drMeterHis = dtMeterHis.Rows[j];
  190. String getDateTime = Convert.ToDateTime(drMeterHis["采集时间"]).ToString("yyyy-MM-dd HH:mm:ss");
  191. message.Append("{");
  192. message.Append("\"meterAssessmentCode\": \"").Append(meterCode).Append("\",");
  193. message.Append("\"manufacturerCode\": ").Append(Constants.ManufacturerCode).Append(",");
  194. message.Append("\"getDateTime\": \"").Append(getDateTime).Append("\",");
  195. if (Convert.DBNull != drMeterHis["净累计流量"])
  196. {
  197. message.Append("\"netCumulativeFlow\": ").Append(Convert.ToDecimal(drMeterHis["净累计流量"])).Append(",");
  198. }
  199. if (Convert.DBNull != drMeterHis["正累计流量"])
  200. {
  201. message.Append("\"positiveCumulativeFlow\": ").Append(Convert.ToDecimal(drMeterHis["正累计流量"])).Append(",");
  202. }
  203. if (Convert.DBNull != drMeterHis["负累计流量"])
  204. {
  205. message.Append("\"negativeCumulativeFlow\": ").Append(Convert.ToDecimal(drMeterHis["负累计流量"])).Append(",");
  206. }
  207. if (Convert.DBNull != drMeterHis["瞬时流量"])
  208. {
  209. message.Append("\"instantaneousFlow\": ").Append(Convert.ToDecimal(drMeterHis["瞬时流量"])).Append(",");
  210. }
  211. if (Convert.DBNull != drMeterHis["压力"])
  212. {
  213. message.Append("\"pressure\": ").Append(Convert.ToDecimal(drMeterHis["压力"])).Append(",");
  214. }
  215. if (Convert.DBNull != drMeterHis["电池电压"])
  216. {
  217. message.Append("\"batteryVoltageValue\": ").Append(Convert.ToDecimal(drMeterHis["电池电压"])).Append(",");
  218. }
  219. message.Append("}");
  220. foreach (KeyValuePair<string, IModel> item in channels)
  221. {
  222. string key = item.Key;
  223. IModel channel = item.Value;
  224. IBasicProperties property = properties[key];
  225. channel.BasicPublish("zone.deviceHis", "", property, Encoding.UTF8.GetBytes(message.ToString())); //生产消息
  226. }
  227. lastTime = getDateTime;
  228. }
  229. catch (Exception ex)
  230. {
  231. log.Info("大表设备历史记录同步任务数据推送失败:" + message.ToString() + "\r\n");
  232. log.Error(ex.Message + "===========" + ex.StackTrace + "\r\n");
  233. }
  234. }
  235. }
  236. if (!"".Equals(lastTime))
  237. {
  238. uploadHis[meterCode] = lastTime;
  239. }
  240. }
  241. SavaUploadHis(uploadHis);
  242. log.Info("大表设备历史记录同步任务执行结束.................\r\n");
  243. }
  244. catch (Exception ex)
  245. {
  246. log.Error("大表设备历史记录同步任务执行错误:" + ex.Message + "===========" + ex.StackTrace + "\r\n");
  247. }
  248. }
  249. /// <summary>
  250. /// 更新配置文件中的值
  251. /// </summary>
  252. /// <param name="key">键</param>
  253. /// <param name="value">值</param>
  254. private void UpdateAppConfig(String key, String value)
  255. {
  256. var cfg = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
  257. cfg.AppSettings.Settings[key].Value = value;
  258. cfg.Save();
  259. ConfigurationManager.RefreshSection("appSettings");
  260. }
  261. /// <summary>
  262. /// 判断历史记录表是否存在
  263. /// </summary>
  264. /// <param name="tablename"></param>
  265. /// <returns></returns>
  266. private bool CheckTableExist(string tablename)
  267. {
  268. DataTable table = dbHelper.Fill("select top 1 * from sysobjects where name='" + tablename + "' and xtype='u'");
  269. if (table == null || table.Rows.Count == 0)
  270. {
  271. return false;
  272. }
  273. return true;
  274. }
  275. /// <summary>
  276. /// 保存每块块表的上传最后一条历史记录
  277. /// </summary>
  278. /// <param name="uploadHis"></param>
  279. private void SavaUploadHis(Dictionary<String,String> uploadHis)
  280. {
  281. // 清除之前的内容
  282. FileStream stream = File.Open(@"TextFile1.txt", FileMode.OpenOrCreate, FileAccess.Write);
  283. stream.Seek(0, SeekOrigin.Begin);
  284. stream.SetLength(0);
  285. stream.Close();
  286. using (StreamWriter sw = new StreamWriter(@"TextFile1.txt"))
  287. {
  288. foreach (var item in uploadHis)
  289. {
  290. sw.WriteLine(item.Key + "," + item.Value);
  291. }
  292. }
  293. }
  294. static IDbProvider dbHelper
  295. {
  296. get
  297. {
  298. var DbDefine = DbFactoryProvider.GetProvider(CurrentDbType.SqlServer, Constants.DbConncetion);
  299. return DbDefine;
  300. }
  301. }
  302. }
  303. }