首先包括定时器的控制,和服务的开始,也包括加载xml的方法,以及JSON反序列化的方法和Get请求的方法。
首先上代码
using Gdky.Common; using Gdky.CS.DBUtility; using GdkyWeatherService; using MySql.Data.MySqlClient; using System; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Data; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Runtime.Serialization.Json; using System.ServiceProcess; using System.Text; using System.Timers; using System.Xml; namespace WeatherService { public partial class Service1 : ServiceBase { /// <summary> /// 所有需要采集天气的城市编码 /// </summary> public List<cityConfig> CitysConfig = new List<cityConfig>(); /// <summary> /// 采集天气方式 /// </summary> public string type { get; set; } /// <summary> /// 采集预测天气时间点 /// </summary> public string[] hours { get; set; } public string xmlPath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "CityConfig.xml"; public Service1() { InitializeComponent(); } DbHelperMySQL helper = new DbHelperMySQL(); protected override void OnStart(string[] args) { try { ///采集天气的方式 0:天气网 1:新浪网 type = helper.Query("select * from sys_dictionary where ID='134'").Tables[0].Rows[0]["WorkValue"].ToString(); ///预测天气采集时间点 string hoursStr = helper.Query("select * from sys_dictionary where ID='135'").Tables[0].Rows[0]["WorkValue"].ToString(); if (string.IsNullOrEmpty(hoursStr)) { hoursStr = "2:00,08:00,12:00"; } hours = hoursStr.Split(','); LoadCityConfigXml(type = "0"); LogHelper.WriteWebLog("天气采集服务启动..."); StartWeatherServer(); } catch (Exception ex) { LogHelper.WriteWebLog(ex.Message + "OnStart方法"); } } private void StartWeatherServer() { try { System.Timers.Timer timer_weater = new System.Timers.Timer(60000); //间隔60s timer_weater.AutoReset = true; timer_weater.Enabled = false; //执行一次 timer_weater.Elapsed += new ElapsedEventHandler(ExecutionCode); timer_weater.Start(); } catch (Exception ex) { LogHelper.WriteWebLog(ex.Message + "StartWeatherServer方法"); } } protected override void OnStop() { LogHelper.WriteWebLog("天气采集服务停止..."); } private void ExecutionCode(object source, System.Timers.ElapsedEventArgs e) { try { if (DateTime.Now.ToString("mm") == "00") //每整点报告运行状态 LogHelper.WriteWebLog(string.Format("天气采集服务正在运行...")); #region 固定时刻采集天气预报 if (hours.Contains(DateTime.Now.ToString("HH:mm")))//固定时刻采集天气预报 { Result weather = new Result(); //天气采集逻辑 foreach (cityConfig item in CitysConfig) { weather = GetWeatherData(item.cityCode); if (weather.code != 200) { LogHelper.WriteWebLog(string.Format("【Info】:{0}获取天气信息失败--{1}", item.cityCode, weather.message)); continue; } if (weather.data.day7.Count > 0 && weather.data.h24.Count > 0)//删除sta_weatherforecast中大于等于今天的数据 { if (!DeleteWeatherForecast6And24(item)) LogHelper.WriteWebLog("【Info】:删除sta_weatherforecast数据失败"); } foreach (DayData day in weather.data.day7) { if (!InsertWeatherForeCast(day, item)) LogHelper.WriteWebLog("【Info】:插入sta_weatherforecast数据失败"); } } } } catch (Exception ex) { LogHelper.WriteWebLog(ex.Message + "ExecutionCode方法"); } #endregion } /// <summary> /// 获取未来7天天气预报及当前天气状况 /// </summary> /// <param name="cityid"></param> /// <returns></returns> private Result GetWeatherData(string city) { try { string json = HttpGet("http://xxx.xxx.xxx.xxx", "city=" + city + "&type=" + type); Result result = JsonDeserialize<Result>(json); LogHelper.WriteWebLog(string.Format("获取地区:{0}【{1}】天气信息成功", city, result.data.now.cityname)); return result; } catch (Exception ex) { LogHelper.WriteWebLog("【Error】:请求getWeather接口时发生错误--" + ex.Message); return new Result(); } } #region 逻辑方法 /// <summary> /// 插入sta_weatherforecast数据 /// </summary> /// <param name="day"></param> /// <param name="cityCode"></param> /// <returns></returns> private bool InsertWeatherForeCast(DayData day, cityConfig city) { bool signal = false; try { string sql = @"INSERT INTO sta_weatherforecast (GetTime, CityId,TempAvg,TempMax,TempMin,Weather,Wind) VALUES (@GetTime, @CityId,@TempAvg,@TempMax,@TempMin,@Weather,@Wind)"; MySqlParameter[] sqlParams = { new MySqlParameter("@GetTime",day.Date), new MySqlParameter("@CityId",city.cityID), new MySqlParameter("@TempAvg",((day.maxTemp+day.minTemp)/2)), new MySqlParameter("@TempMax",day.maxTemp), new MySqlParameter("@TempMin",day.minTemp), new MySqlParameter("@Weather",day.wea), new MySqlParameter("@Wind",day.win) }; int num = helper.ExecuteSql2(sql, sqlParams); if (num > 0) { signal = true; } else { LogHelper.WriteWebLog(string.Format("【Info】:插入sta_weatherforecast数据失败")); signal = false; } } catch (Exception ex) { LogHelper.WriteWebLog("【Error】:插入sta_weatherforecast数据异常--" + ex.Message); return false; } return signal; } /// <summary> /// 删除sta_weatherforecast大于今天的数据 /// </summary> /// <param name="cityCode"></param> /// <returns></returns> private bool DeleteWeatherForecast6And24(cityConfig city) { bool signal = false; try { //保留前23天的数据 string sql = @"Delete from sta_weatherforecast Where CityId='" + city.cityID + "' and GetTime>=DATE_FORMAT('" + DateTime.Now.Date + "','%Y-%m-%d')"; DbHelperMySQL helper = new DbHelperMySQL(); int num = helper.ExecuteSql2(sql); if (num >= 0) { signal = true; } else { LogHelper.WriteWebLog(string.Format("【Info】:删除sta_weatherforecast数据失败")); signal = false; } return signal; } catch (Exception ex) { LogHelper.WriteWebLog("【Error】:删除sta_weatherforecast数据异常--" + ex.Message); return false; } } #endregion #region 通用方法 public string HttpGet(string Url, string postDataStr) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr); request.Method = "GET"; request.ContentType = "text/html;charset=UTF-8"; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream myResponseStream = response.GetResponseStream(); StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8")); string retString = myStreamReader.ReadToEnd(); myStreamReader.Close(); myResponseStream.Close(); return retString; } /// <summary> /// JSON序列化 /// </summary> public string JsonSerializer<T>(T t) { DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T)); MemoryStream ms = new MemoryStream(); ser.WriteObject(ms, t); string jsonString = Encoding.UTF8.GetString(ms.ToArray()); ms.Close(); return jsonString; } /// <summary> /// JSON反序列化 /// </summary> public T JsonDeserialize<T>(string jsonString) { DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T)); MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)); T obj = (T)ser.ReadObject(ms); return obj; } #endregion #region 加载XML /// <summary> /// 加载城市列表 /// </summary> /// <param name="type"></param> private void LoadCityConfigXml(string type) { try { CitysConfig = new List<cityConfig>(); //初始化 XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(xmlPath); XmlNode configsXml = xmlDoc.SelectSingleNode("CityConfigs"); XmlNodeList cityConfigXmls = configsXml.ChildNodes; foreach (XmlNode item in cityConfigXmls) { cityConfig cityConfig = new cityConfig(); cityConfig.cityName = item.Attributes["cityName"].Value; cityConfig.cityCode = item.Attributes["cityCode_" + type].Value; cityConfig.cityID = item.Attributes["cityID"].Value; XmlNodeList databaseXmls = item.ChildNodes; //foreach (XmlNode db in databaseXmls) //{ // cityConfig.databases.Add(db.Attributes["name"].Value, GdkyEncrypt.GDKY_DESDecrypt(db.InnerText.Trim())); //} CitysConfig.Add(cityConfig); } } catch (Exception ex) { LogHelper.WriteWebLog("【Error】:加载CityConfigXML时发生错误--" + ex.Message); } } #endregion public class cityConfig { public string cityCode { get; set; } public string cityName { get; set; } /// <summary> /// 数据库里city /// </summary> public string cityID { get; set; } public Dictionary<string, string> databases = new Dictionary<string, string>(); } } }