联网获取天气信息并保存到本地数据库

自启动定时请求天气信息类,请求到的天气数据存储在本地数据库 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.ejb.Timeout;
import javax.ejb.Timer;
import javax.ejb.TimerConfig;
import javax.ejb.TimerService;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.http.HttpStatus;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.taiji.apps.base.utility.DateUtil;
import com.taiji.apps.base.weather.domain.WeatherInfo;
import com.taiji.apps.base.weather.service.WeatherService;

/**
* @ClassName:WeatherTimer定时请求天气信息类
* @Description:自启动定时请求天气信息类,请求到的天气数据存储在本地数据库
* @date:2017年5月27日
*/
@Singleton
@Startup
public class WeatherTimer {
	
	@Resource
    TimerService timerService;
	
	@EJB
	public WeatherService weatherService;	//存储到本地数据库,获取本地数据库数据 服务接口
	
	private Date lastProgrammaticTimeout;	//最后一次请求天气信息的时间
	
	private Logger logger = LoggerFactory.getLogger(this.getClass());	//日志输出
	
	
	/** 
	* @Description: @PostConstruct注解自启动
	* @date: 2017年5月27日 上午10:45:59
	*/
	@PostConstruct
    public void init() {
    	setTimer((long)60*60*1000); //设置定时执行频率:1小时
    }
	
    /** 
    * @Description: 调用定时器,启动定时器
    * @param intervalDuration:定时执行频率
    * @date: 2017年5月27日 上午10:47:26
    */
    public void setTimer(long intervalDuration) {
    	logger.info("Setting a programmatic timeout for " + intervalDuration + " milliseconds from now.");
    	TimerConfig timerConfig = new TimerConfig();
        timerConfig.setPersistent(false);
        this.timerService.createIntervalTimer(5000, intervalDuration, timerConfig);
    }
	
    @Timeout
    public void programmaticTimeout(Timer timer) {
    	logger.info("获取天气信息定时器已启动");
        this.setLastProgrammaticTimeout(new Date());
		if (tryConnection()) {
			getCurrentData();
			getForecastData();
			getAQIData();
		}
    }
    
	/** 
	* @Description: 通过url获取天气json
	* @param url 接口地址
	* @return:天气json串
	* @date: 2017年5月27日 上午10:55:07
	*/
	private String getWeatherJson(String url) {
		try {
			URLConnection uc = new URL(url).openConnection();
			BufferedReader reader =
					new BufferedReader(new InputStreamReader(uc.getInputStream(), "utf-8"));
			StringBuffer jsonBuffer = new StringBuffer();
			String line = null;
			while (null != (line = reader.readLine())) {
				jsonBuffer.append(line);
			}
			return jsonBuffer.toString();
		} catch (IOException e) {
			this.logger.error("通过" + url + "获取天气信息失败,原因如下:>>>>>>>>>>"+ e.getMessage());
			return null;
		}
	}
    
	/** 
	* @Description: 尝试连接URL指定网站
	* @return:连接成功/失败
	* @date: 2017年5月27日 上午10:57:05
	*/
	public boolean tryConnection() {
		boolean flag = false;
		try {
			URL url = new URL("http://api.k780.com:88/");
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod("GET");
			connection.setReadTimeout(1000);
			connection.setConnectTimeout(1000);
			if (HttpStatus.SC_OK == connection.getResponseCode()) {
				flag = true;
			}
		} catch (IOException e) {
			this.logger.error("天气信息接口http://api.k780.com:88/连接失败,原因如下:>>>>>>>>>>"+ e.getMessage());
		}
		return flag;
	}
    
	/** 
	* @Description: 获取当前天气
	* @date: 2017年5月27日 上午11:00:05
	*/
	private void getCurrentData() {
		String url = "http://api.k780.com:88/?app=weather.today&weaid=101030600"
				+ "&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json";
		String jsonStr = getWeatherJson(url);
		if (StringUtils.isNotBlank(jsonStr)) {
			JSONObject jsonObj = new JSONObject(jsonStr);
			String success = jsonObj.getString("success");
			if ("1".equals(success)) {
				JSONObject result = jsonObj.getJSONObject("result");
				SimpleDateFormat myFmt = new SimpleDateFormat("yyyy-MM-dd");
				String todayStr = myFmt.format(new Date());
				WeatherInfo tempWeather = this.weatherService.getWeatherInfoByDays(todayStr);
				if (null == tempWeather) {
					WeatherInfo weatherInfo = new WeatherInfo();
					setCurrData(result, weatherInfo);
				} else {
					setCurrData(result, tempWeather);
				}
			}
		}
	}
    

    /** 
    * @Description: 入库当前天气数据
    * @param jsonObj jsonObj 当前天气的json对象
    * @param weatherInfo: weatherInfo 天气对象
    * @date: 2017年5月27日 上午11:01:16
    */
    private void setCurrData(JSONObject jsonObj, WeatherInfo weatherInfo) {
    	if(StringUtils.isNotBlank(jsonObj.getString("days"))) {
    		weatherInfo.setDays(jsonObj.getString("days"));
    	}
    	if(StringUtils.isNotBlank(jsonObj.getString("week"))) {
    		weatherInfo.setWeek(jsonObj.getString("week"));
    	}
    	if(StringUtils.isNotBlank(jsonObj.getString("temperature_curr"))) {
    		weatherInfo.setTemperatureCurr(jsonObj.getString("temperature_curr"));
    	}
    	if(StringUtils.isNotBlank(jsonObj.getString("weather_curr")) && (StringUtils.isNotBlank(jsonObj.getString("weather_icon")) || StringUtils.isNotBlank(jsonObj.getString("weather_icon1")))) {
    		weatherInfo.setWeatherCurr(jsonObj.getString("weather_curr"));
    		if(StringUtils.isNotBlank(jsonObj.getString("weather_icon"))) {
        		weatherInfo.setWeatherIconCurr((jsonObj.getString("weather_icon")));
        	} else if(StringUtils.isNotBlank(jsonObj.getString("weather_icon1"))) {
        		weatherInfo.setWeatherIconCurr(jsonObj.getString("weather_icon1"));
        	}
    	}
    	if(StringUtils.isNotBlank(jsonObj.getString("wind"))) {
    		weatherInfo.setWindCurr(jsonObj.getString("wind"));
    	}
    	if(StringUtils.isNotBlank(jsonObj.getString("winp"))) {
    		weatherInfo.setWinpCurr(jsonObj.getString("winp"));
    	}
    	weatherInfo.setUpdateTime(new Date());
		this.weatherService.saveWeatherInfo(weatherInfo);
    }
    
	/** 
	* @Description: 获取未来七天天气
	* @date: 2017年5月27日 上午11:01:47
	*/
	private void getForecastData() {
		String url = "http://api.k780.com:88/?app=weather.future&weaid=101030600"
				+ "&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json";
		String jsonStr = getWeatherJson(url);
		if (StringUtils.isNotBlank(jsonStr)) {
			JSONObject jsonObj = new JSONObject(jsonStr);
			String success = jsonObj.getString("success");
			if ("1".equals(success)) {
				JSONArray jsonArr = jsonObj.getJSONArray("result");
				Date today = new Date();
				String todayStr = DateUtil.format(today, DateUtil.datePattern);
				String tomorrowStr = DateUtil.format(DateUtil.getAfterDate(1),
						DateUtil.datePattern);
				String thirdStr = DateUtil.format(DateUtil.getAfterDate(2),
						DateUtil.datePattern);
				String fourthStr = DateUtil.format(DateUtil.getAfterDate(3),
						DateUtil.datePattern);
				String fifthStr = DateUtil.format(DateUtil.getAfterDate(4),
						DateUtil.datePattern);
				String sixthStr = DateUtil.format(DateUtil.getAfterDate(5),
						DateUtil.datePattern);
				String seventhStr = DateUtil.format(DateUtil.getAfterDate(6),
						DateUtil.datePattern);
				// 未来七天的日期字符串数组
				String[] sevenDays = new String[] { todayStr, tomorrowStr,
						thirdStr, fourthStr, fifthStr, sixthStr, seventhStr };

				for (int i = 0; i < jsonArr.length(); i++) {
					JSONObject tempJson = jsonArr.getJSONObject(i);
					// 解析并入库未来七天的天气
					String days = tempJson.getString("days");
					if (ArrayUtils.contains(sevenDays, days)) {
						setForecast(days, tempJson);
					}
				}
			}
		} 
	}
    
    /** 
    * @Description: 设置未来七天天气数据
    * @param dayStr未来一天的日期串
    * @param jsonObj:未来一天天气的json对象
    * @date: 2017年5月27日 上午11:02:50
    */
    private void setForecast(String dayStr, JSONObject jsonObj) {
    	WeatherInfo tempWeather = this.weatherService.getWeatherInfoByDays(dayStr);
		if(null==tempWeather) {
			WeatherInfo weatherInfo = new WeatherInfo();
			setForData(jsonObj, weatherInfo);
		} else {
			setForData(jsonObj, tempWeather);
		}
    }

    /** 
    * @Description: 入库未来七天天气数据
    * @param jsonObj未来一天天气的json对象
    * @param weatherInfo:天气对象
    * @date: 2017年5月27日 上午11:03:41
    */
    private void setForData(JSONObject jsonObj, WeatherInfo weatherInfo) {
    	if(StringUtils.isNotBlank(jsonObj.getString("days"))) {
    		weatherInfo.setDays(jsonObj.getString("days"));
    	}
    	if(StringUtils.isNotBlank(jsonObj.getString("week"))) {
    		weatherInfo.setWeek(jsonObj.getString("week"));
    	}
    	if(StringUtils.isNotBlank(jsonObj.getString("temperature"))) {
    		weatherInfo.setTemperature(jsonObj.getString("temperature"));
    	}
    	if(StringUtils.isNotBlank(jsonObj.getString("weather"))
    			&& (StringUtils.isNotBlank(jsonObj.getString("weather_icon"))
    					|| StringUtils.isNotBlank(jsonObj.getString("weather_icon1")))) {
    		weatherInfo.setWeather(jsonObj.getString("weather"));
    		if(StringUtils.isNotBlank(jsonObj.getString("weather_icon"))) {
    			weatherInfo.setWeatherIconD(jsonObj.getString("weather_icon"));
    		}
    		if(StringUtils.isNotBlank(jsonObj.getString("weather_icon1"))) {
    			weatherInfo.setWeatherIconN(jsonObj.getString("weather_icon1"));
    		}
    	}
    	if(StringUtils.isNotBlank(jsonObj.getString("wind"))) {
    		weatherInfo.setWind(jsonObj.getString("wind"));
    	}
    	if(StringUtils.isNotBlank(jsonObj.getString("winp"))) {
    		weatherInfo.setWinp(jsonObj.getString("winp"));
    	}
    	weatherInfo.setUpdateTime(new Date());
		this.weatherService.saveWeatherInfo(weatherInfo);
    }
    
    /**
     * 获取当前空气指数AQI
     */
	private void getAQIData() {
		String url = "http://api.k780.com:88/?app=weather.pm25&weaid=101030100"
				+ "&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json";
		String jsonStr = getWeatherJson(url);
		if (StringUtils.isNotBlank(jsonStr)) {
			JSONObject jsonObj = new JSONObject(jsonStr);
			String success = jsonObj.getString("success");
			if ("1".equals(success)) {
				JSONObject result = jsonObj.getJSONObject("result");
				SimpleDateFormat myFmt = new SimpleDateFormat("yyyy-MM-dd");
				String todayStr = myFmt.format(new Date());
				WeatherInfo tempWeather = this.weatherService
						.getWeatherInfoByDays(todayStr);
				if (null == tempWeather) {
					WeatherInfo weatherInfo = new WeatherInfo();
					setAQIData(todayStr, result, weatherInfo);
				} else {
					setAQIData(todayStr, result, tempWeather);
				}
			}
		}
	}
    
    /**
     * 入库当前空气指数
     * @param todayStr 今天日期串
     * @param jsonObj 当前天气的json对象
     * @param weatherInfo 天气对象
     */
    private void setAQIData(String todayStr, JSONObject jsonObj, WeatherInfo weatherInfo) {
    	if(StringUtils.isBlank(weatherInfo.getDays())) {
    		weatherInfo.setDays(todayStr);
    	}
    	if(StringUtils.isNotBlank(jsonObj.getString("aqi"))) {
    		weatherInfo.setAqi(jsonObj.getString("aqi"));
        	if(StringUtils.isNotBlank(jsonObj.getString("aqi_scope"))) {
        		weatherInfo.setAqiScope(jsonObj.getString("aqi_scope"));
        	}
        	if(StringUtils.isNotBlank(jsonObj.getString("aqi_levid"))) {
        		weatherInfo.setAqiLevid(jsonObj.getString("aqi_levid"));
        	}
        	if(StringUtils.isNotBlank(jsonObj.getString("aqi_levnm"))) {
        		weatherInfo.setAqiLevnm(jsonObj.getString("aqi_levnm"));
        	}
        	if(StringUtils.isNotBlank(jsonObj.getString("aqi_remark"))) {
        		weatherInfo.setAqiRemark(jsonObj.getString("aqi_remark"));
        	}
    	}
    	weatherInfo.setUpdateTime(new Date());
		this.weatherService.saveWeatherInfo(weatherInfo);
    }
  
    @PreDestroy
	private void destroy() {
	}
    
    public String getLastProgrammaticTimeout() {
        if (lastProgrammaticTimeout != null) {
            return lastProgrammaticTimeout.toString();
        } else {
            return "never";
        }
        
    }

    public void setLastProgrammaticTimeout(Date lastTimeout) {
        this.lastProgrammaticTimeout = lastTimeout;
    }

}

天气对象实体类,存储在数据库中

import java.io.Serializable;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

import lombok.Getter;
import lombok.Setter;

import org.hibernate.annotations.GenericGenerator;

import com.taiji.framework.api.base.domain.BaseModel;

/**
* @ClassName:WeatherInfo 天气对象实体类
* @Description:天气对象实体类,存储在数据库中
* @date:2017年5月27日
*/
@Entity
@Table(name = "ES_WEATHER_INFO")
public class WeatherInfo extends BaseModel implements Serializable {

	private static final long serialVersionUID = 1L;

    @Getter @Setter
    @Id
    @GeneratedValue(generator = "generator")
    @GenericGenerator(name = "generator", strategy = "uuid2")
    private String id;
    
    @Getter @Setter
    private String days; //日期 yyyy-MM-dd

    @Getter @Setter
    private String week; //星期
    
    @Getter @Setter
    private String temperature; //气温
    
    @Getter @Setter
    @Column(name = "TEMPERATURE_CURR")
    private String temperatureCurr; //当前气温
    
    @Getter @Setter
    private String weather; //天气
    
    @Getter @Setter
    @Column(name = "WEATHER_CURR")
    private String weatherCurr; //当前天气
    
    @Getter @Setter
    @Column(name = "WEATHER_ICON_D")
    private String weatherIconD; //白天图标
    
    @Getter @Setter
    @Column(name = "WEATHER_ICON_N")
    private String weatherIconN; //夜间图标
    
    @Getter @Setter
    @Column(name = "WEATHER_ICON_CURR")
    private String weatherIconCurr; //当前图标
    
    @Getter @Setter
    private String wind; //风向
    
    @Getter @Setter
    @Column(name = "WIND_CURR")
    private String windCurr; //当前风向
    
    @Getter @Setter
    private String winp; //风力
    
    @Getter @Setter
    @Column(name = "WINP_CURR")
    private String winpCurr; //当前风力
    
    @Getter @Setter
    private String aqi; //空气指数
    
    @Getter @Setter
    @Column(name = "AQI_SCOPE")
    private String aqiScope; //指数范围
    
    @Getter @Setter
    @Column(name = "AQI_LEVID")
    private String aqiLevid; //级别编号
    
    @Getter @Setter
    @Column(name = "AQI_LEVNM")
    private String aqiLevnm; //级别
    
    @Getter @Setter
    @Column(name = "AQI_REMARK")
    private String aqiRemark; //注意事项

    @Getter @Setter
    @Column(name = "UPDATE_TIME")
    @Temporal(TemporalType.TIMESTAMP)
    private Date updateTime; //更新时间

    public WeatherInfo(){
    }
    
    @Override
    public Object retrieveId() {
        return this.id;
    }
	
}


参考:http://blog.csdn.net/daydayupzzc/article/details/38866489  http://blog.csdn.net/u012204058/article/details/71034047


  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
首先,你需要一个传感器来获取温湿度数据。一些常用的传感器包括DHT11、DHT22和AM2302等。你还需要一个microcontroller将传感器读数并将其发送到网络上。 以下是一个示例代码,使用ESP8266 microcontroller和DHT11传感器来获取温湿度数据,并将其插入到MySQL数据库中。 ```python import pymysql.cursors import machine import dht import time import network # 连接WiFi网络 ssid = "your_SSID" password = "your_PASSWORD" station = network.WLAN(network.STA_IF) station.active(True) station.connect(ssid, password) while not station.isconnected(): pass print("WiFi已连接") # 连接MySQL数据库 connection = pymysql.connect(host='your_host', user='your_user', password='your_password', db='your_database', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor) # 初始化DHT11传感器 d = dht.DHT11(machine.Pin(2)) while True: # 读取温湿度数据 d.measure() temperature = d.temperature() humidity = d.humidity() # 插入数据到MySQL数据库 try: with connection.cursor() as cursor: sql = "INSERT INTO `temperature_humidity` (`temperature`, `humidity`) VALUES (%s, %s)" cursor.execute(sql, (temperature, humidity)) connection.commit() print("数据插入成功") except: print("数据插入失败") # 等待1分钟 time.sleep(60) ``` 在这个示例中,我们使用`network`模块连接到WiFi网络,并使用`pymysql`模块连接到MySQL数据库。我们还使用`dht`模块初始化DHT11传感器,并使用`time`模块等待1分钟,以便我们可以获取温湿度数据的定期更新。 在插入数据数据库时,我们使用`try`和`except`语句来处理任何可能的错误,例如网络连接中断或数据库插入失败。 请注意,此示例代码仅供参考,你需要根据自己的具体情况进行修改。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值