使用百度天气API制作天气组件

百度天气APi

目前百度天气API提供全国得实时查询,但是没有提供历史查询,在一些应用中需要天气模块,如果是和天气密切相关得可能还需要历史天气,这时候直接调用百度API就不太好用,于是我结合百度API搞了个查询天气,支持历史数据(但是需要积累)。

百度API调用

这里先简单介绍百度API中天气得调用。
https://lbsyun.baidu.com/index.php?title=webapi/weather
官方网站
这里有详细得介绍,使用时需要先申请KEY。调用起来还是很简单。
调用示例
这里说下注意事项:
1.天气会返回预测+实时,实时大概是半小时左右更新一次。
2.查询得次数有限制,一天一千次。需要得可以升级,得加钱。

处理思路

因为天气API得局限性,必须解决以下几个问题:
1.调用次数限制
2.不能查询历史
3.不能自定义使用
这里给出得解决方案是首先次数限制,如果个人使用一般也不会超,即使项目需要,使用不频繁也不会超。但是以防万一,我这里使用了缓存来解决次数问题,减少对API得调用。使用缓存解决了次数问题,有一个新的问题产生,数据是不是最新得,一般情况下,天气不会变得很频繁,不会说1:00天气预报是晴天,1:05是冰雹,1:10是闪电,如果是这种也不适合使用这种简单得API天气。那解决数据时效性问题就是给缓存设置失效时间,我这里控制得是两小时。可以根据需要自行修改。
对于查询历史得方案,需要具体,如果是需要一个从今天开始到后续,这段时间得历史天气数据,建立数据库,将API结果存起来,需要查历史再从数据库查。但是如果需要去年或者前年得数据,这时这个方案就只能解决一半,对于之前得历史天气,api做不到,这时就需要其他得API搭配使用。我这里找到一个可以使用历史天气得API。将历史数据搞出来,然后存进数据库,就可以解决这个问题。
对于自定义使用,这个当然是结合API进行改造,反正这些数据进入数据库了,至于怎么展示或者说需要什么样得提供形式,就完全参照自己发挥。下面给出我做的一个。
自定义演示
这里区别于百度有设置时间。

代码层面得实现

package com.sutpc.service;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.druid.util.StringUtils;
import com.sutpc.convert.BeanConvert;
import com.sutpc.entity.ForecastEntity;
import com.sutpc.entity.WeatherEntity;
import com.sutpc.mapper.DistrictMapper;
import com.sutpc.mapper.WeatherMapper;
import com.sutpc.model.DistrictWeather;
import com.sutpc.model.Forecasts;
import com.sutpc.model.Location;
import com.sutpc.model.Weather;
import com.sutpc.utils.CultivateUtils;
import com.sutpc.utils.LogUtils;
import com.sutpc.utils.TimeLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class WeatherService {

    @Value("${sutpc.baidu-api-weather}")
    String weatherUrl;

    @Value("${sutpc.ak}")
    String ak;

    @Autowired
    DistrictMapper districtMapper;

    @Autowired
    WeatherMapper weatherMapper;

    TimeLock lock = new TimeLock();

    /**
     * 接口获取城市辖区天气入库
     * TODO 组装数据,供后续使用
     *
     * @param city
     * @return
     */
    public Map addWeather(String city) {
        Map<String, Object> weatherMap = new ConcurrentHashMap<>();
        List<Map> districts = districtMapper.getDistrictByCity(city);
        List<WeatherEntity> weathers = new ArrayList<>();
        List<ForecastEntity> forecastWeathers = new ArrayList<>();

        if (!districts.isEmpty()) {
            districts.forEach(x -> {
                String district_id = (String) x.get("districtcode");
                String url = weatherUrl + "?district_id=" + district_id + "&data_type=all&ak=" + ak;

                //先从缓存取没有才调用接口
                String result = (String) lock.get(x.get("districtcode").toString());
                LogUtils.info("从缓存中获取数据,获取结果是否为空:", StringUtils.isEmpty(result));
                if (StringUtils.isEmpty(result)) {
                    LogUtils.info("调用百度API天气接口:" + url);
                    result = HttpUtil.get(url);
                }
                //存入缓存两小时内有效 key为districtcode
                lock.set(x.get("districtcode").toString(), result, 3600 * 1000 * 2);
                JSONObject jsonObject = JSONUtil.parseObj(result);
                JSONObject results = jsonObject.getJSONObject("result");
                //获取定位信息
                Location location = results.get("location", Location.class);
                //获取当前天气信息
                Weather weather = results.get("now", Weather.class);
                weather.setDate(DateUtil.today());
                String dayProperty = CultivateUtils.getDateproperty();
                weather.setDay_property(dayProperty);
                //获取预测信息
                List<Forecasts> forecasts = results.getJSONArray("forecasts").toList(Forecasts.class);
                //数据入库前检查是否已存在,存在就更新,根据date name dayproperty三个属性判断

                //当前天气入库
                LogUtils.info("天气数据入库:", weather, location);
                int weatherCount = weatherMapper.checkIsAddWeather(weather.getDate(), location.getName(), dayProperty);
                if (weatherCount == 0) {
                    weatherMapper.addWeather(new DistrictWeather(location, weather));
                } else {
                    weatherMapper.updateWeather(new DistrictWeather(location, weather));
                }
                LogUtils.info("预测天气数据入库:", forecasts.size());
                //预测天气入库
                forecasts.forEach(y -> {
                    //先检查今天是否已经插入,插入就更新,否则就插入
                    int ForecastCount = weatherMapper.checkIsAddForecast(y.getDate(), location.getName());
                    if (ForecastCount == 0) {
                        weatherMapper.addForecast(new DistrictWeather(location, y));
                    } else {
                        weatherMapper.updateForecast(new DistrictWeather(location, y));
                    }
                    ForecastEntity forecastEntity = BeanConvert.INSTANCE.ForecastToEntity(y, location);
                    forecastWeathers.add(forecastEntity);
                });
                WeatherEntity weatherEntity = BeanConvert.INSTANCE.WeatherToEntity(weather, location);
                weathers.add(weatherEntity);
                weatherMap.put("day-weather", weathers);
                weatherMap.put("forecast", forecastWeathers);
                lock.set("weather" + city, weatherMap, 3600 * 1000 * 2);
            });
        }
        return weatherMap;
    }

    /**
     * 根据城市和日期获取指定得天气,仅限于当前时间以前,并附带预测天气
     * TODO 访问接口添加缓存,缓存设置2小时过期,优先使用数据库数据,没有才调用接口
     *
     * @return
     */
    public Object getWeather(String date, String city) {
        //先查数据库
        Date endDate = DateUtil.offsetDay(DateUtil.parse(date), 4);
        //实际天气
        List<WeatherEntity> weathers = weatherMapper.getWeather(date, city);
        //预测天气
        List<ForecastEntity> forecastWeathers = weatherMapper.getForecastWeather(date, DateUtil.formatDate(endDate), city);
        Map<String, Object> weatherMap = new ConcurrentHashMap<>();
        //如果数据库为空则查询缓存,缓存没有就调用接口,缓存没有调接口,返回当前时间得天气
        if (weathers.isEmpty() || forecastWeathers.isEmpty()) {
            weatherMap = Convert.toMap(String.class, Object.class, lock.get("weather" + city));
            LogUtils.info("从缓存中获取数据,获取结果是否为空:", weatherMap == null);
            //缓存为空调用一次接口,并返回结果
            if (weatherMap == null || weatherMap.isEmpty()) {
                weatherMap = addWeather(city);
            }
            return weatherMap;
        }
        weatherMap.put("day-weather", weathers);
        weatherMap.put("forecast", forecastWeathers);
        return weatherMap;
    }

}

核心得逻辑都放在这里一些关键得地方都有注释。这里我会把源代码放到后面,供需要得人使用。直接使用就是改配置文件。

文件介绍

cultivate.rar 天气组件+平时训练得代码
weather.rar 天气需要得基础表 district表是必须,其余是自己定义。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值