HanTingDataUploadJob.cs 17 KB

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